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 mc, bool allowUnboundTypeArguments)
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);
266 var constraint_tp = type as TypeParameterSpec;
267 if (constraint_tp != null) {
268 if (tparam_types == null) {
269 tparam_types = new List<TypeParameterSpec> (2);
270 } else if (tparam_types.Contains (constraint_tp)) {
271 context.Module.Compiler.Report.Error (405, constraint.Location,
272 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
277 // Checks whether each generic method parameter constraint type
278 // is valid with respect to T
280 if (tp.IsMethodTypeParameter) {
281 VarianceDecl.CheckTypeVariance (type, Variance.Contravariant, context);
284 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
285 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
286 context.Module.Compiler.Report.Error (454, constraint.Location,
287 "Circular constraint dependency involving `{0}' and `{1}'",
288 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
293 // Checks whether there are no conflicts between type parameter constraints
299 // A and B are not convertible and only 1 class constraint is allowed
301 if (constraint_tp.HasTypeConstraint) {
302 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
303 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
306 for (int ii = 0; ii < tparam_types.Count; ++ii) {
307 if (!tparam_types[ii].HasTypeConstraint)
310 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
316 if (constraint_tp.TypeArguments != null) {
317 var eb = constraint_tp.GetEffectiveBase ();
318 if (eb != null && !CheckConflictingInheritedConstraint (spec, eb, spec.BaseType, context, constraint.Location))
322 if (constraint_tp.HasSpecialStruct) {
323 context.Module.Compiler.Report.Error (456, constraint.Location,
324 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
325 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
329 tparam_types.Add (constraint_tp);
333 if (iface_found || spec.HasTypeConstraint) {
334 context.Module.Compiler.Report.Error (406, constraint.Location,
335 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
336 type.GetSignatureForError ());
339 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
340 context.Module.Compiler.Report.Error (450, constraint.Location,
341 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
342 type.GetSignatureForError ());
345 switch (type.BuiltinType) {
346 case BuiltinTypeSpec.Type.Array:
347 case BuiltinTypeSpec.Type.Delegate:
348 case BuiltinTypeSpec.Type.MulticastDelegate:
349 case BuiltinTypeSpec.Type.Enum:
350 case BuiltinTypeSpec.Type.ValueType:
351 case BuiltinTypeSpec.Type.Object:
352 context.Module.Compiler.Report.Error (702, constraint.Location,
353 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
355 case BuiltinTypeSpec.Type.Dynamic:
356 context.Module.Compiler.Report.Error (1967, constraint.Location,
357 "A constraint cannot be the dynamic type");
361 if (type.IsSealed || !type.IsClass) {
362 context.Module.Compiler.Report.Error (701, loc,
363 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
364 type.GetSignatureForError ());
369 context.Module.Compiler.Report.Error (717, constraint.Location,
370 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
371 type.GetSignatureForError ());
374 spec.BaseType = type;
377 if (tparam_types != null)
378 spec.TypeArguments = tparam_types.ToArray ();
385 public void VerifyClsCompliance (Report report)
387 foreach (var c in constraints)
392 if (!c.Type.IsCLSCompliant ()) {
393 report.SymbolRelatedToPreviousError (c.Type);
394 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
395 c.Type.GetSignatureForError ());
402 // A type parameter for a generic type or generic method definition
404 public class TypeParameter : MemberCore, ITypeDefinition
406 static readonly string[] attribute_target = { "type parameter" };
408 Constraints constraints;
409 GenericTypeParameterBuilder builder;
410 readonly TypeParameterSpec spec;
412 public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance Variance)
413 : base (null, name, attrs)
415 this.constraints = constraints;
416 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, Variance, null);
422 public TypeParameter (MemberName name, Attributes attrs, VarianceDecl variance)
423 : base (null, name, attrs)
425 var var = variance == null ? Variance.None : variance.Variance;
426 this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, var, null);
427 this.VarianceDecl = variance;
430 public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
431 : base (null, name, attrs)
433 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
434 BaseType = spec.BaseType,
435 InterfacesDefined = spec.InterfacesDefined,
436 TypeArguments = spec.TypeArguments
442 public override AttributeTargets AttributeTargets {
444 return AttributeTargets.GenericParameter;
448 public Constraints Constraints {
457 public IAssemblyDefinition DeclaringAssembly {
459 return Module.DeclaringAssembly;
463 public override string DocCommentHeader {
465 throw new InvalidOperationException (
466 "Unexpected attempt to get doc comment from " + this.GetType ());
470 bool ITypeDefinition.IsComImport {
476 bool ITypeDefinition.IsPartial {
482 public bool IsMethodTypeParameter {
484 return spec.IsMethodOwned;
488 bool ITypeDefinition.IsTypeForwarder {
494 bool ITypeDefinition.IsCyclicTypeForwarder {
502 return MemberName.Name;
506 public string Namespace {
512 public TypeParameterSpec Type {
518 public int TypeParametersCount {
524 public TypeParameterSpec[] TypeParameters {
530 public override string[] ValidAttributeTargets {
532 return attribute_target;
536 public Variance Variance {
538 return spec.Variance;
542 public VarianceDecl VarianceDecl { get; private set; }
547 // This is called for each part of a partial generic type definition.
549 // If partial type parameters constraints are not null and we don't
550 // already have constraints they become our constraints. If we already
551 // have constraints, we must check that they're same.
553 public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
556 throw new InvalidOperationException ();
558 var new_constraints = tp.constraints;
559 if (new_constraints == null)
562 // TODO: could create spec only
563 //tp.Define (null, -1, part.Definition);
564 tp.spec.DeclaringType = part.Definition;
565 if (!tp.ResolveConstraints (part))
568 if (constraints != null)
569 return spec.HasSameConstraintsDefinition (tp.Type);
571 // Copy constraint from resolved part to partial container
572 spec.SpecialConstraint = tp.spec.SpecialConstraint;
573 spec.InterfacesDefined = tp.spec.InterfacesDefined;
574 spec.TypeArguments = tp.spec.TypeArguments;
575 spec.BaseType = tp.spec.BaseType;
580 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
582 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
585 public void CheckGenericConstraints (bool obsoleteCheck)
587 if (constraints != null)
588 constraints.CheckGenericConstraints (this, obsoleteCheck);
591 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
593 return new TypeParameter (spec, declaringSpec, MemberName, null);
596 public override bool Define ()
602 // This is the first method which is called during the resolving
603 // process; we're called immediately after creating the type parameters
604 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
607 public void Create (TypeSpec declaringType, TypeContainer parent)
610 throw new InternalErrorException ();
612 // Needed to get compiler reference
613 this.Parent = parent;
614 spec.DeclaringType = declaringType;
617 public void Define (GenericTypeParameterBuilder type)
620 spec.SetMetaInfo (type);
623 public void Define (TypeParameter tp)
625 builder = tp.builder;
628 public void EmitConstraints (GenericTypeParameterBuilder builder)
630 var attr = GenericParameterAttributes.None;
631 if (spec.Variance == Variance.Contravariant)
632 attr |= GenericParameterAttributes.Contravariant;
633 else if (spec.Variance == Variance.Covariant)
634 attr |= GenericParameterAttributes.Covariant;
636 if (spec.HasSpecialClass)
637 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
638 else if (spec.HasSpecialStruct)
639 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
641 if (spec.HasSpecialConstructor)
642 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
644 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
645 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
647 if (spec.InterfacesDefined != null)
648 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
650 if (spec.TypeArguments != null) {
651 var meta_constraints = new List<MetaType> (spec.TypeArguments.Length);
652 foreach (var c in spec.TypeArguments) {
654 // Inflated type parameters can collide with special constraint types, don't
655 // emit any such type parameter.
657 if (c.BuiltinType == BuiltinTypeSpec.Type.Object || c.BuiltinType == BuiltinTypeSpec.Type.ValueType)
660 meta_constraints.Add (c.GetMetaInfo ());
663 builder.SetInterfaceConstraints (meta_constraints.ToArray ());
666 builder.SetGenericParameterAttributes (attr);
669 public override void Emit ()
671 EmitConstraints (builder);
673 if (OptAttributes != null)
674 OptAttributes.Emit ();
679 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
681 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
682 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
683 string gtype_variance;
685 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
686 case Variance.Covariant: gtype_variance = "covariantly"; break;
687 default: gtype_variance = "invariantly"; break;
690 Delegate d = mc as Delegate;
691 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
693 Report.Error (1961, Location,
694 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
695 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
698 public TypeSpec GetAttributeCoClass ()
703 public string GetAttributeDefaultMember ()
705 throw new NotSupportedException ();
708 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
710 throw new NotSupportedException ();
713 public override string GetSignatureForDocumentation ()
715 throw new NotImplementedException ();
718 public override string GetSignatureForError ()
720 return MemberName.Name;
723 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
725 return spec.MemberDefinition.DeclaringAssembly == assembly;
728 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
730 throw new NotSupportedException ("Not supported for compiled definition");
734 // Resolves all type parameter constraints
736 public bool ResolveConstraints (IMemberContext context)
738 if (constraints != null)
739 return constraints.Resolve (context, this);
741 if (spec.BaseType == null)
742 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
747 public override bool IsClsComplianceRequired ()
752 public new void VerifyClsCompliance ()
754 if (constraints != null)
755 constraints.VerifyClsCompliance (Report);
758 public void WarningParentNameConflict (TypeParameter conflict)
760 conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
761 conflict.Report.Warning (693, 3, Location,
762 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
763 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
767 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
768 public class TypeParameterSpec : TypeSpec
770 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
773 SpecialConstraint spec;
776 TypeSpec[] ifaces_defined;
777 TypeSpec effective_base;
780 // Creates type owned type parameter
782 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
783 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
785 this.variance = variance;
787 state &= ~StateFlags.Obsolete_Undetected;
792 // Creates method owned type parameter
794 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
795 : this (null, index, definition, spec, variance, info)
801 public int DeclaredPosition {
810 public bool HasSpecialConstructor {
812 return (spec & SpecialConstraint.Constructor) != 0;
816 public bool HasSpecialClass {
818 return (spec & SpecialConstraint.Class) != 0;
822 public bool HasSpecialStruct {
824 return (spec & SpecialConstraint.Struct) != 0;
828 public bool HasAnyTypeConstraint {
830 return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
834 public bool HasTypeConstraint {
836 var bt = BaseType.BuiltinType;
837 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
841 public override IList<TypeSpec> Interfaces {
843 if ((state & StateFlags.InterfacesExpanded) == 0) {
844 if (ifaces != null) {
845 if (ifaces_defined == null)
846 ifaces_defined = ifaces.ToArray ();
848 for (int i = 0; i < ifaces_defined.Length; ++i ) {
849 var iface_type = ifaces_defined[i];
850 var td = iface_type.MemberDefinition as TypeDefinition;
852 td.DoExpandBaseInterfaces ();
854 if (iface_type.Interfaces != null) {
855 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
856 var ii_iface_type = iface_type.Interfaces [ii];
857 AddInterface (ii_iface_type);
861 } else if (ifaces_defined == null) {
862 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
866 // Include all base type interfaces too, see ImportTypeBase for details
868 if (BaseType != null) {
869 var td = BaseType.MemberDefinition as TypeDefinition;
871 td.DoExpandBaseInterfaces ();
873 if (BaseType.Interfaces != null) {
874 foreach (var iface in BaseType.Interfaces) {
875 AddInterface (iface);
880 state |= StateFlags.InterfacesExpanded;
888 // Unexpanded interfaces list
890 public TypeSpec[] InterfacesDefined {
892 if (ifaces_defined == null) {
893 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
896 return ifaces_defined.Length == 0 ? null : ifaces_defined;
899 ifaces_defined = value;
900 if (value != null && value.Length != 0)
901 ifaces = new List<TypeSpec> (value);
905 public bool IsConstrained {
907 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
912 // Returns whether the type parameter is known to be a reference type
914 public new bool IsReferenceType {
916 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
917 return (spec & SpecialConstraint.Class) != 0;
920 // Full check is needed (see IsValueType for details)
922 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
926 foreach (var ta in targs) {
928 // Secondary special constraints are ignored (I am not sure why)
930 var tp = ta as TypeParameterSpec;
931 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
934 if (TypeSpec.IsReferenceType (ta))
944 // Returns whether the type parameter is known to be a value type
946 public new bool IsValueType {
949 // Even if structs/enums cannot be used directly as constraints
950 // they can apear as constraint type when inheriting base constraint
951 // which has dependant type parameter constraint which has been
952 // inflated using value type
954 // class A : B<int> { override void Foo<U> () {} }
955 // class B<T> { virtual void Foo<U> () where U : T {} }
957 if (HasSpecialStruct)
961 foreach (var ta in targs) {
962 if (TypeSpec.IsValueType (ta))
971 public override string Name {
973 return definition.Name;
977 public bool IsMethodOwned {
979 return DeclaringType == null;
983 public SpecialConstraint SpecialConstraint {
993 // Types used to inflate the generic type
995 public new TypeSpec[] TypeArguments {
1004 public Variance Variance {
1012 public string DisplayDebugInfo ()
1014 var s = GetSignatureForError ();
1015 return IsMethodOwned ? s + "!!" : s + "!";
1019 // Finds effective base class. The effective base class is always a class-type
1021 public TypeSpec GetEffectiveBase ()
1023 if (HasSpecialStruct)
1027 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
1029 if (BaseType != null && targs == null) {
1031 // 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.
1033 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
1035 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
1036 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
1038 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
1041 if (effective_base != null)
1042 return effective_base;
1044 var types = new TypeSpec [HasTypeConstraint ? targs.Length + 1 : targs.Length];
1046 for (int i = 0; i < targs.Length; ++i) {
1049 // Same issue as above, inherited constraints can be of struct type
1051 types [i] = t.BaseType;
1055 var tps = t as TypeParameterSpec;
1056 types [i] = tps != null ? tps.GetEffectiveBase () : t;
1059 if (HasTypeConstraint)
1060 types [types.Length - 1] = BaseType;
1062 return effective_base = Convert.FindMostEncompassedType (types);
1065 public override string GetSignatureForDocumentation (bool explicitName)
1070 var prefix = IsMethodOwned ? "``" : "`";
1071 return prefix + DeclaredPosition;
1074 public override string GetSignatureForError ()
1080 // Constraints have to match by definition but not position, used by
1081 // partial classes or methods
1083 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
1085 if (spec != other.spec)
1088 if (BaseType != other.BaseType)
1091 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
1094 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
1101 // Constraints have to match by using same set of types, used by
1102 // implicit interface implementation
1104 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
1106 if (spec != other.spec)
1110 // It can be same base type or inflated type parameter
1112 // interface I<T> { void Foo<U> where U : T; }
1113 // class A : I<int> { void Foo<X> where X : int {} }
1116 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
1117 if (other.targs == null)
1121 foreach (var otarg in other.targs) {
1122 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1132 // Check interfaces implementation -> definition
1133 if (InterfacesDefined != null) {
1135 // Iterate over inflated interfaces
1137 foreach (var iface in Interfaces) {
1139 if (other.InterfacesDefined != null) {
1140 foreach (var oiface in other.Interfaces) {
1141 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1151 if (other.targs != null) {
1152 foreach (var otarg in other.targs) {
1153 if (TypeSpecComparer.Override.IsEqual (iface, otarg)) {
1165 // Check interfaces implementation <- definition
1166 if (other.InterfacesDefined != null) {
1167 if (InterfacesDefined == null)
1171 // Iterate over inflated interfaces
1173 foreach (var oiface in other.Interfaces) {
1175 foreach (var iface in Interfaces) {
1176 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1187 // Check type parameters implementation -> definition
1188 if (targs != null) {
1189 if (other.targs == null)
1192 foreach (var targ in targs) {
1194 foreach (var otarg in other.targs) {
1195 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1206 // Check type parameters implementation <- definition
1207 if (other.targs != null) {
1208 foreach (var otarg in other.targs) {
1209 // Ignore inflated type arguments, were checked above
1210 if (!otarg.IsGenericParameter)
1217 foreach (var targ in targs) {
1218 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1232 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1234 return InflateConstraints (tparams, l => l, inflator);
1237 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1239 TypeParameterSpec[] constraints = null;
1240 TypeParameterInflator? inflator = null;
1242 for (int i = 0; i < tparams.Length; ++i) {
1243 var tp = tparams[i];
1244 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1245 if (constraints == null) {
1246 constraints = new TypeParameterSpec[tparams.Length];
1247 Array.Copy (tparams, constraints, constraints.Length);
1251 // Using a factory to avoid possibly expensive inflator build up
1253 if (inflator == null)
1254 inflator = inflatorFactory (arg);
1256 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1260 if (constraints == null)
1261 constraints = tparams;
1266 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1268 tps.BaseType = inflator.Inflate (BaseType);
1270 var defined = InterfacesDefined;
1271 if (defined != null) {
1272 tps.ifaces_defined = new TypeSpec[defined.Length];
1273 for (int i = 0; i < defined.Length; ++i)
1274 tps.ifaces_defined [i] = inflator.Inflate (defined[i]);
1275 } else if (ifaces_defined == TypeSpec.EmptyTypes) {
1276 tps.ifaces_defined = TypeSpec.EmptyTypes;
1279 var ifaces = Interfaces;
1280 if (ifaces != null) {
1281 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1282 for (int i = 0; i < ifaces.Count; ++i)
1283 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1284 tps.state |= StateFlags.InterfacesExpanded;
1287 if (targs != null) {
1288 tps.targs = new TypeSpec[targs.Length];
1289 for (int i = 0; i < targs.Length; ++i)
1290 tps.targs[i] = inflator.Inflate (targs[i]);
1294 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1296 var tps = (TypeParameterSpec) MemberwiseClone ();
1301 InflateConstraints (inflator, tps);
1306 // Populates type parameter members using type parameter constraints
1307 // The trick here is to be called late enough but not too late to
1308 // populate member cache with all members from other types
1310 protected override void InitializeMemberCache (bool onlyTypes)
1312 cache = new MemberCache ();
1315 // For a type parameter the membercache is the union of the sets of members of the types
1316 // specified as a primary constraint or secondary constraint
1318 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1319 cache.AddBaseType (BaseType);
1321 if (InterfacesDefined != null) {
1322 foreach (var iface_type in InterfacesDefined) {
1323 cache.AddInterface (iface_type);
1327 if (targs != null) {
1328 foreach (var ta in targs) {
1329 var tps = ta as TypeParameterSpec;
1330 IList<TypeSpec> ifaces;
1333 b_type = tps.GetEffectiveBase ();
1334 ifaces = tps.InterfacesDefined;
1337 ifaces = ta.Interfaces;
1341 // Don't add base type which was inflated from base constraints but it's not valid
1344 if (b_type != null && b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType && !b_type.IsStructOrEnum)
1345 cache.AddBaseType (b_type);
1347 if (ifaces != null) {
1348 foreach (var iface_type in ifaces) {
1349 cache.AddInterface (iface_type);
1356 public bool IsConvertibleToInterface (TypeSpec iface)
1358 if (Interfaces != null) {
1359 foreach (var t in Interfaces) {
1365 if (TypeArguments != null) {
1366 foreach (var t in TypeArguments) {
1367 var tps = t as TypeParameterSpec;
1369 if (tps.IsConvertibleToInterface (iface))
1375 if (t.ImplementsInterface (iface, false))
1383 public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
1385 var tps = md.TypeParameters;
1386 for (int i = 0; i < md.TypeParametersCount; ++i) {
1387 if (tps[i].HasAnyTypeConstraint) {
1395 public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
1397 var tps = md.TypeParameters;
1398 for (int i = 0; i < md.TypeParametersCount; ++i) {
1399 if (tps[i].IsConstrained) {
1407 public bool HasDependencyOn (TypeSpec type)
1409 if (TypeArguments != null) {
1410 foreach (var targ in TypeArguments) {
1411 if (TypeSpecComparer.Override.IsEqual (targ, type))
1414 var tps = targ as TypeParameterSpec;
1415 if (tps != null && tps.HasDependencyOn (type))
1423 public override TypeSpec Mutate (TypeParameterMutator mutator)
1425 return mutator.Mutate (this);
1429 public struct TypeParameterInflator
1431 readonly TypeSpec type;
1432 readonly TypeParameterSpec[] tparams;
1433 readonly TypeSpec[] targs;
1434 readonly IModuleContext context;
1436 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1437 : this (nested.context, type, nested.tparams, nested.targs)
1441 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1443 if (tparams.Length != targs.Length)
1444 throw new ArgumentException ("Invalid arguments");
1446 this.context = context;
1447 this.tparams = tparams;
1454 public IModuleContext Context {
1460 public TypeSpec TypeInstance {
1467 // Type parameters to inflate
1469 public TypeParameterSpec[] TypeParameters {
1477 public TypeSpec Inflate (TypeSpec type)
1479 var tp = type as TypeParameterSpec;
1481 return Inflate (tp);
1483 var ec = type as ElementTypeSpec;
1485 var et = Inflate (ec.Element);
1486 if (et != ec.Element) {
1487 var ac = ec as ArrayContainer;
1489 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1491 if (ec is PointerContainer)
1492 return PointerContainer.MakeType (context.Module, et);
1494 throw new NotImplementedException ();
1500 if (type.Kind == MemberKind.MissingType)
1504 // When inflating a nested type, inflate its parent first
1505 // in case it's using same type parameters (was inflated within the type)
1509 if (type.IsNested) {
1510 var parent = Inflate (type.DeclaringType);
1513 // Keep the inflated type arguments
1515 targs = type.TypeArguments;
1518 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1519 // because the import cache helps us to catch it. However, that means we have to look at
1520 // type definition to get type argument (they are in fact type parameter in this case)
1522 if (targs.Length == 0 && type.Arity > 0)
1523 targs = type.MemberDefinition.TypeParameters;
1526 // Parent was inflated, find the same type on inflated type
1527 // to use same cache for nested types on same generic parent
1529 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1532 // Handle the tricky case where parent shares local type arguments
1533 // which means inflating inflated type
1536 // public static Nested<T> Foo () { return null; }
1538 // public class Nested<U> {}
1541 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1543 if (targs.Length > 0) {
1544 var inflated_targs = new TypeSpec[targs.Length];
1545 for (; i < targs.Length; ++i)
1546 inflated_targs[i] = Inflate (targs[i]);
1548 type = type.MakeGenericType (context, inflated_targs);
1554 // Nothing to do for non-generic type
1555 if (type.Arity == 0)
1558 targs = new TypeSpec[type.Arity];
1561 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1563 if (type is InflatedTypeSpec) {
1564 for (; i < targs.Length; ++i)
1565 targs[i] = Inflate (type.TypeArguments[i]);
1567 type = type.GetDefinition ();
1570 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1572 var args = type.MemberDefinition.TypeParameters;
1573 foreach (var ds_tp in args)
1574 targs[i++] = Inflate (ds_tp);
1577 return type.MakeGenericType (context, targs);
1580 public TypeSpec Inflate (TypeParameterSpec tp)
1582 for (int i = 0; i < tparams.Length; ++i)
1583 if (tparams [i] == tp)
1586 // This can happen when inflating nested types
1587 // without type arguments specified
1593 // Before emitting any code we have to change all MVAR references to VAR
1594 // when the method is of generic type and has hoisted variables
1596 public class TypeParameterMutator
1598 readonly TypeParameters mvar;
1599 readonly TypeParameters var;
1600 readonly TypeParameterSpec[] src;
1601 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1603 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1605 if (mvar.Count != var.Count)
1606 throw new ArgumentException ();
1612 public TypeParameterMutator (TypeParameterSpec[] srcVar, TypeParameters destVar)
1614 if (srcVar.Length != destVar.Count)
1615 throw new ArgumentException ();
1623 public TypeParameters MethodTypeParameters {
1631 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1633 if (type is InflatedTypeSpec) {
1634 if (type.DeclaringType == null)
1635 return type.GetDefinition ();
1637 var parent = GetMemberDeclaringType (type.DeclaringType);
1638 type = MemberCache.GetMember<TypeSpec> (parent, type);
1644 public TypeSpec Mutate (TypeSpec ts)
1647 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1650 value = ts.Mutate (this);
1651 if (mutated_typespec == null)
1652 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1654 mutated_typespec.Add (ts, value);
1658 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1661 for (int i = 0; i < mvar.Count; ++i) {
1662 if (mvar[i].Type == tp)
1666 for (int i = 0; i < src.Length; ++i) {
1675 public TypeSpec[] Mutate (TypeSpec[] targs)
1677 TypeSpec[] mutated = new TypeSpec[targs.Length];
1678 bool changed = false;
1679 for (int i = 0; i < targs.Length; ++i) {
1680 mutated[i] = Mutate (targs[i]);
1681 changed |= targs[i] != mutated[i];
1684 return changed ? mutated : targs;
1689 /// A TypeExpr which already resolved to a type parameter.
1691 public class TypeParameterExpr : TypeExpression
1693 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1694 : base (type_parameter.Type, loc)
1696 this.eclass = ExprClass.TypeParameter;
1700 public class InflatedTypeSpec : TypeSpec
1703 TypeParameterSpec[] constraints;
1704 readonly TypeSpec open_type;
1705 readonly IModuleContext context;
1707 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1708 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1711 throw new ArgumentNullException ("targs");
1713 this.state &= ~SharedStateFlags;
1714 this.state |= (openType.state & SharedStateFlags);
1716 this.context = context;
1717 this.open_type = openType;
1720 foreach (var arg in targs) {
1721 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1722 state |= StateFlags.HasDynamicElement;
1727 if (open_type.Kind == MemberKind.MissingType)
1728 MemberCache = MemberCache.Empty;
1730 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1731 state |= StateFlags.ConstraintsChecked;
1736 public override TypeSpec BaseType {
1738 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1739 InitializeMemberCache (true);
1741 return base.BaseType;
1746 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1748 public TypeParameterSpec[] Constraints {
1750 if (constraints == null) {
1751 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1759 // Used to cache expensive constraints validation on constructed types
1761 public bool HasConstraintsChecked {
1763 return (state & StateFlags.ConstraintsChecked) != 0;
1766 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1770 public override IList<TypeSpec> Interfaces {
1773 InitializeMemberCache (true);
1775 return base.Interfaces;
1779 public override bool IsExpressionTreeType {
1781 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1785 public override bool IsArrayGenericInterface {
1787 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1791 public override bool IsGenericTask {
1793 return (open_type.state & StateFlags.GenericTask) != 0;
1797 public override bool IsNullableType {
1799 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1804 // Types used to inflate the generic type
1806 public override TypeSpec[] TypeArguments {
1814 public override bool AddInterface (TypeSpec iface)
1816 var inflator = CreateLocalInflator (context);
1817 iface = inflator.Inflate (iface);
1821 return base.AddInterface (iface);
1824 public static bool ContainsTypeParameter (TypeSpec type)
1826 if (type.Kind == MemberKind.TypeParameter)
1829 var element_container = type as ElementTypeSpec;
1830 if (element_container != null)
1831 return ContainsTypeParameter (element_container.Element);
1833 foreach (var t in type.TypeArguments) {
1834 if (ContainsTypeParameter (t)) {
1842 public TypeParameterInflator CreateLocalInflator (IModuleContext context)
1844 TypeParameterSpec[] tparams_full;
1845 TypeSpec[] targs_full = targs;
1848 // Special case is needed when we are inflating an open type (nested type definition)
1849 // on inflated parent. Consider following case
1851 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1853 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1855 List<TypeSpec> merged_targs = null;
1856 List<TypeParameterSpec> merged_tparams = null;
1858 var type = DeclaringType;
1861 if (type.TypeArguments.Length > 0) {
1862 if (merged_targs == null) {
1863 merged_targs = new List<TypeSpec> ();
1864 merged_tparams = new List<TypeParameterSpec> ();
1865 if (targs.Length > 0) {
1866 merged_targs.AddRange (targs);
1867 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1870 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1871 merged_targs.AddRange (type.TypeArguments);
1873 type = type.DeclaringType;
1874 } while (type != null);
1876 if (merged_targs != null) {
1877 // Type arguments are not in the right order but it should not matter in this case
1878 targs_full = merged_targs.ToArray ();
1879 tparams_full = merged_tparams.ToArray ();
1880 } else if (targs.Length == 0) {
1881 tparams_full = TypeParameterSpec.EmptyTypes;
1883 tparams_full = open_type.MemberDefinition.TypeParameters;
1885 } else if (targs.Length == 0) {
1886 tparams_full = TypeParameterSpec.EmptyTypes;
1888 tparams_full = open_type.MemberDefinition.TypeParameters;
1891 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1894 MetaType CreateMetaInfo ()
1897 // Converts nested type arguments into right order
1898 // Foo<string, bool>.Bar<int> => string, bool, int
1900 var all = new List<MetaType> ();
1901 TypeSpec type = this;
1902 TypeSpec definition = type;
1904 if (type.GetDefinition().IsGeneric) {
1906 type.TypeArguments != TypeSpec.EmptyTypes ?
1907 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1908 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1911 definition = definition.GetDefinition ();
1912 type = type.DeclaringType;
1913 } while (type != null);
1915 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1918 public override ObsoleteAttribute GetAttributeObsolete ()
1920 return open_type.GetAttributeObsolete ();
1923 protected override bool IsNotCLSCompliant (out bool attrValue)
1925 if (base.IsNotCLSCompliant (out attrValue))
1928 foreach (var ta in TypeArguments) {
1929 if (ta.MemberDefinition.CLSAttributeValue == false)
1936 public override TypeSpec GetDefinition ()
1941 public override MetaType GetMetaInfo ()
1944 info = CreateMetaInfo ();
1949 public override string GetSignatureForError ()
1952 return targs[0].GetSignatureForError () + "?";
1954 return base.GetSignatureForError ();
1957 protected override string GetTypeNameSignature ()
1959 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1962 return "<" + TypeManager.CSharpName (targs) + ">";
1965 public bool HasDynamicArgument ()
1967 for (int i = 0; i < targs.Length; ++i) {
1968 var item = targs[i];
1970 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1973 if (item is InflatedTypeSpec) {
1974 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1981 while (item.IsArray) {
1982 item = ((ArrayContainer) item).Element;
1985 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1993 protected override void InitializeMemberCache (bool onlyTypes)
1995 if (cache == null) {
1996 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1998 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1999 // for imported type parameter constraints referencing nested type of this declaration
2001 cache = new MemberCache (open_cache);
2004 var inflator = CreateLocalInflator (context);
2007 // Two stage inflate due to possible nested types recursive
2017 // When resolving type of `b' members of `B' cannot be
2018 // inflated because are not yet available in membercache
2020 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
2021 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
2024 // Inflate any implemented interfaces
2026 if (open_type.Interfaces != null) {
2027 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
2028 foreach (var iface in open_type.Interfaces) {
2029 var iface_inflated = inflator.Inflate (iface);
2030 if (iface_inflated == null)
2033 base.AddInterface (iface_inflated);
2038 // Handles the tricky case of recursive nested base generic type
2040 // class A<T> : Base<A<T>.Nested> {
2044 // When inflating A<T>. base type is not yet known, secondary
2045 // inflation is required (not common case) once base scope
2048 if (open_type.BaseType == null) {
2050 state |= StateFlags.PendingBaseTypeInflate;
2052 BaseType = inflator.Inflate (open_type.BaseType);
2054 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2056 // It can happen when resolving base type without being defined
2057 // which is not allowed to happen and will always lead to an error
2059 // class B { class N {} }
2060 // class A<T> : A<B.N> {}
2062 if (open_type.BaseType == null)
2065 BaseType = inflator.Inflate (open_type.BaseType);
2066 state &= ~StateFlags.PendingBaseTypeInflate;
2070 state |= StateFlags.PendingMemberCacheMembers;
2074 var tc = open_type.MemberDefinition as TypeDefinition;
2075 if (tc != null && !tc.HasMembersDefined) {
2077 // Inflating MemberCache with undefined members
2082 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2083 BaseType = inflator.Inflate (open_type.BaseType);
2084 state &= ~StateFlags.PendingBaseTypeInflate;
2087 state &= ~StateFlags.PendingMemberCacheMembers;
2088 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
2091 public override TypeSpec Mutate (TypeParameterMutator mutator)
2093 var targs = TypeArguments;
2095 targs = mutator.Mutate (targs);
2097 var decl = DeclaringType;
2098 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
2099 decl = mutator.Mutate (decl);
2101 if (targs == TypeArguments && decl == DeclaringType)
2104 var mutated = (InflatedTypeSpec) MemberwiseClone ();
2105 if (decl != DeclaringType) {
2106 // Gets back MethodInfo in case of metaInfo was inflated
2107 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
2109 mutated.declaringType = decl;
2110 mutated.state |= StateFlags.PendingMetaInflate;
2113 if (targs != null) {
2114 mutated.targs = targs;
2115 mutated.info = null;
2124 // Tracks the type arguments when instantiating a generic type. It's used
2125 // by both type arguments and type parameters
2127 public class TypeArguments
2129 List<FullNamedExpression> args;
2132 public TypeArguments (params FullNamedExpression[] types)
2134 this.args = new List<FullNamedExpression> (types);
2137 public void Add (FullNamedExpression type)
2143 /// We may only be used after Resolve() is called and return the fully
2146 // TODO: Not needed, just return type from resolve
2147 public TypeSpec[] Arguments {
2162 public virtual bool IsEmpty {
2168 public List<FullNamedExpression> TypeExpressions {
2174 public string GetSignatureForError()
2176 StringBuilder sb = new StringBuilder ();
2177 for (int i = 0; i < Count; ++i) {
2180 sb.Append (expr.GetSignatureForError ());
2186 return sb.ToString ();
2190 /// Resolve the type arguments.
2192 public virtual bool Resolve (IMemberContext ec, bool allowUnbound)
2197 int count = args.Count;
2200 atypes = new TypeSpec [count];
2202 var errors = ec.Module.Compiler.Report.Errors;
2204 for (int i = 0; i < count; i++){
2205 var te = args[i].ResolveAsType (ec);
2214 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
2215 te.GetSignatureForError ());
2219 if (te.IsPointer || te.IsSpecialRuntimeType) {
2220 ec.Module.Compiler.Report.Error (306, args[i].Location,
2221 "The type `{0}' may not be used as a type argument",
2222 te.GetSignatureForError ());
2227 if (!ok || errors != ec.Module.Compiler.Report.Errors)
2233 public TypeArguments Clone ()
2235 TypeArguments copy = new TypeArguments ();
2236 foreach (var ta in args)
2243 public class UnboundTypeArguments : TypeArguments
2247 public UnboundTypeArguments (int arity, Location loc)
2248 : base (new FullNamedExpression[arity])
2253 public override bool IsEmpty {
2259 public override bool Resolve (IMemberContext mc, bool allowUnbound)
2261 if (!allowUnbound) {
2262 mc.Module.Compiler.Report.Error (7003, loc, "Unbound generic name is not valid in this context");
2265 // Nothing to be resolved
2270 public class TypeParameters
2272 List<TypeParameter> names;
2273 TypeParameterSpec[] types;
2275 public TypeParameters ()
2277 names = new List<TypeParameter> ();
2280 public TypeParameters (int count)
2282 names = new List<TypeParameter> (count);
2293 public TypeParameterSpec[] Types {
2301 public void Add (TypeParameter tparam)
2306 public void Add (TypeParameters tparams)
2308 names.AddRange (tparams.names);
2311 public void Create (TypeSpec declaringType, int parentOffset, TypeContainer parent)
2313 types = new TypeParameterSpec[Count];
2314 for (int i = 0; i < types.Length; ++i) {
2317 tp.Create (declaringType, parent);
2319 types[i].DeclaredPosition = i + parentOffset;
2321 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2322 parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2327 public void Define (GenericTypeParameterBuilder[] builders)
2329 for (int i = 0; i < types.Length; ++i) {
2331 tp.Define (builders [types [i].DeclaredPosition]);
2335 public TypeParameter this[int index] {
2337 return names [index];
2340 names[index] = value;
2344 public TypeParameter Find (string name)
2346 foreach (var tp in names) {
2347 if (tp.Name == name)
2354 public string[] GetAllNames ()
2356 return names.Select (l => l.Name).ToArray ();
2359 public string GetSignatureForError ()
2361 StringBuilder sb = new StringBuilder ();
2362 for (int i = 0; i < Count; ++i) {
2366 var name = names[i];
2368 sb.Append (name.GetSignatureForError ());
2371 return sb.ToString ();
2375 public void CheckPartialConstraints (Method part)
2377 var partTypeParameters = part.CurrentTypeParameters;
2379 for (int i = 0; i < Count; i++) {
2380 var tp_a = names[i];
2381 var tp_b = partTypeParameters [i];
2382 if (tp_a.Constraints == null) {
2383 if (tp_b.Constraints == null)
2385 } else if (tp_b.Constraints != null && tp_a.Type.HasSameConstraintsDefinition (tp_b.Type)) {
2389 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition.Location, "");
2390 part.Compiler.Report.Error (761, part.Location,
2391 "Partial method declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2392 part.GetSignatureForError (), partTypeParameters[i].GetSignatureForError ());
2396 public void UpdateConstraints (TypeDefinition part)
2398 var partTypeParameters = part.MemberName.TypeParameters;
2400 for (int i = 0; i < Count; i++) {
2402 if (tp.AddPartialConstraints (part, partTypeParameters [i]))
2405 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition);
2406 part.Compiler.Report.Error (265, part.Location,
2407 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2408 part.GetSignatureForError (), tp.GetSignatureForError ());
2412 public void VerifyClsCompliance ()
2414 foreach (var tp in names) {
2415 tp.VerifyClsCompliance ();
2421 // A type expression of generic type with type arguments
2423 class GenericTypeExpr : TypeExpr
2429 /// Instantiate the generic type `t' with the type arguments `args'.
2430 /// Use this constructor if you already know the fully resolved
2433 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2435 this.open_type = open_type;
2440 public override string GetSignatureForError ()
2442 return type.GetSignatureForError ();
2445 public override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments = false)
2447 if (eclass != ExprClass.Unresolved)
2450 if (!args.Resolve (mc, allowUnboundTypeArguments))
2453 TypeSpec[] atypes = args.Arguments;
2458 // Now bind the parameters
2460 var inflated = open_type.MakeGenericType (mc, atypes);
2462 eclass = ExprClass.Type;
2465 // The constraints can be checked only when full type hierarchy is known
2467 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2468 var constraints = inflated.Constraints;
2469 if (constraints != null) {
2470 var cc = new ConstraintChecker (mc);
2471 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2472 inflated.HasConstraintsChecked = true;
2480 public override bool Equals (object obj)
2482 GenericTypeExpr cobj = obj as GenericTypeExpr;
2486 if ((type == null) || (cobj.type == null))
2489 return type == cobj.type;
2492 public override int GetHashCode ()
2494 return base.GetHashCode ();
2499 // Generic type with unbound type arguments, used for typeof (G<,,>)
2501 class GenericOpenTypeExpr : TypeExpression
2503 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2504 : base (type.GetDefinition (), loc)
2509 struct ConstraintChecker
2512 bool recursive_checks;
2514 public ConstraintChecker (IMemberContext ctx)
2517 recursive_checks = false;
2521 // Checks the constraints of open generic type against type
2522 // arguments. This version is used for types which could not be
2523 // checked immediatelly during construction because the type
2524 // hierarchy was not yet fully setup (before Emit phase)
2526 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2529 // Check declaring type first if there is any
2531 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2534 while (type is ElementTypeSpec)
2535 type = ((ElementTypeSpec) type).Element;
2537 if (type.Arity == 0)
2540 var gtype = type as InflatedTypeSpec;
2544 var constraints = gtype.Constraints;
2545 if (constraints == null)
2548 if (gtype.HasConstraintsChecked)
2551 var cc = new ConstraintChecker (mc);
2552 cc.recursive_checks = true;
2554 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2555 gtype.HasConstraintsChecked = true;
2563 // Checks all type arguments againts type parameters constraints
2564 // NOTE: It can run in probing mode when `this.mc' is null
2566 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2571 for (int i = 0; i < tparams.Length; i++) {
2572 var targ = targs[i];
2573 if (!CheckConstraint (context, targ, tparams [i], loc))
2576 if (!recursive_checks)
2579 if (!Check (mc, targ, loc))
2586 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2589 // First, check the `class' and `struct' constraints.
2591 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2593 mc.Module.Compiler.Report.Error (452, loc,
2594 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2595 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2601 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2603 mc.Module.Compiler.Report.Error (453, loc,
2604 "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}'",
2605 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2614 // Check the class constraint
2616 if (tparam.HasTypeConstraint) {
2617 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2626 // Check the interfaces constraints
2628 if (tparam.InterfacesDefined != null) {
2629 foreach (TypeSpec iface in tparam.InterfacesDefined) {
2630 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2641 // Check the type parameter constraint
2643 if (tparam.TypeArguments != null) {
2644 foreach (var ta in tparam.TypeArguments) {
2645 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2656 // Finally, check the constructor constraint.
2658 if (!tparam.HasSpecialConstructor)
2661 if (!HasDefaultConstructor (atype)) {
2663 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2664 mc.Module.Compiler.Report.Error (310, loc,
2665 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2666 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2674 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2676 for (int i = 0; i < targs.Length; ++i) {
2677 var targ = targs [i];
2678 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2681 if (HasDynamicTypeArgument (targ.TypeArguments))
2688 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2693 if (atype.IsGenericParameter) {
2694 var tps = (TypeParameterSpec) atype;
2695 if (tps.HasDependencyOn (ttype))
2698 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2701 } else if (TypeSpec.IsValueType (atype)) {
2702 if (atype.IsNullableType) {
2704 // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2706 if (TypeSpec.IsBaseClass (atype, ttype, false))
2709 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2713 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2718 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2719 if (atype.IsGenericParameter) {
2720 mc.Module.Compiler.Report.Error (314, loc,
2721 "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}'",
2722 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2723 } else if (TypeSpec.IsValueType (atype)) {
2724 if (atype.IsNullableType) {
2725 if (ttype.IsInterface) {
2726 mc.Module.Compiler.Report.Error (313, loc,
2727 "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}'",
2728 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2730 mc.Module.Compiler.Report.Error (312, loc,
2731 "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}'",
2732 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2735 mc.Module.Compiler.Report.Error (315, loc,
2736 "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}'",
2737 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2740 mc.Module.Compiler.Report.Error (311, loc,
2741 "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}'",
2742 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2749 static bool HasDefaultConstructor (TypeSpec atype)
2751 var tp = atype as TypeParameterSpec;
2753 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2756 if (atype.IsStruct || atype.IsEnum)
2759 if (atype.IsAbstract)
2762 var tdef = atype.GetDefinition ();
2764 var found = MemberCache.FindMember (tdef,
2765 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2766 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2768 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2773 // Implements C# type inference
2778 // Tracks successful rate of type inference
2781 readonly Arguments arguments;
2782 readonly int arg_count;
2784 public TypeInference (Arguments arguments)
2786 this.arguments = arguments;
2787 if (arguments != null)
2788 arg_count = arguments.Count;
2791 public int InferenceScore {
2797 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2799 var method_generic_args = method.GenericDefinition.TypeParameters;
2800 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2801 if (!context.UnfixedVariableExists)
2802 return TypeSpec.EmptyTypes;
2804 AParametersCollection pd = method.Parameters;
2805 if (!InferInPhases (ec, context, pd))
2808 return context.InferredTypeArguments;
2812 // Implements method type arguments inference
2814 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2816 int params_arguments_start;
2817 if (methodParameters.HasParams) {
2818 params_arguments_start = methodParameters.Count - 1;
2820 params_arguments_start = arg_count;
2823 TypeSpec [] ptypes = methodParameters.Types;
2826 // The first inference phase
2828 TypeSpec method_parameter = null;
2829 for (int i = 0; i < arg_count; i++) {
2830 Argument a = arguments [i];
2834 if (i < params_arguments_start) {
2835 method_parameter = methodParameters.Types [i];
2836 } else if (i == params_arguments_start) {
2837 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2838 method_parameter = methodParameters.Types [params_arguments_start];
2840 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2842 ptypes = (TypeSpec[]) ptypes.Clone ();
2843 ptypes [i] = method_parameter;
2847 // When a lambda expression, an anonymous method
2848 // is used an explicit argument type inference takes a place
2850 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2852 if (am.ExplicitTypeInference (tic, method_parameter))
2858 score += tic.ExactInference (a.Type, method_parameter);
2862 if (a.Expr.Type == InternalType.NullLiteral)
2865 if (TypeSpec.IsValueType (method_parameter)) {
2866 score += tic.LowerBoundInference (a.Type, method_parameter);
2871 // Otherwise an output type inference is made
2873 score += tic.OutputTypeInference (ec, a.Expr, method_parameter);
2877 // Part of the second phase but because it happens only once
2878 // we don't need to call it in cycle
2880 bool fixed_any = false;
2881 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2884 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2887 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2889 bool fixed_any = false;
2890 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2893 // If no further unfixed type variables exist, type inference succeeds
2894 if (!tic.UnfixedVariableExists)
2897 if (!fixed_any && fixDependent)
2900 // For all arguments where the corresponding argument output types
2901 // contain unfixed type variables but the input types do not,
2902 // an output type inference is made
2903 for (int i = 0; i < arg_count; i++) {
2905 // Align params arguments
2906 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2908 if (!t_i.IsDelegate) {
2909 if (!t_i.IsExpressionTreeType)
2912 t_i = TypeManager.GetTypeArguments (t_i) [0];
2915 var mi = Delegate.GetInvokeMethod (t_i);
2916 TypeSpec rtype = mi.ReturnType;
2918 if (tic.IsReturnTypeNonDependent (mi, rtype)) {
2919 // It can be null for default arguments
2920 if (arguments[i] == null)
2923 score += tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2928 return DoSecondPhase (ec, tic, methodParameters, true);
2932 public class TypeInferenceContext
2934 protected enum BoundKind
2941 struct BoundInfo : IEquatable<BoundInfo>
2943 public readonly TypeSpec Type;
2944 public readonly BoundKind Kind;
2946 public BoundInfo (TypeSpec type, BoundKind kind)
2952 public override int GetHashCode ()
2954 return Type.GetHashCode ();
2957 public Expression GetTypeExpression ()
2959 return new TypeExpression (Type, Location.Null);
2962 #region IEquatable<BoundInfo> Members
2964 public bool Equals (BoundInfo other)
2966 return Type == other.Type && Kind == other.Kind;
2972 readonly TypeSpec[] tp_args;
2973 readonly TypeSpec[] fixed_types;
2974 readonly List<BoundInfo>[] bounds;
2976 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2977 public TypeInferenceContext (TypeSpec[] typeArguments)
2979 if (typeArguments.Length == 0)
2980 throw new ArgumentException ("Empty generic arguments");
2982 fixed_types = new TypeSpec [typeArguments.Length];
2983 for (int i = 0; i < typeArguments.Length; ++i) {
2984 if (typeArguments [i].IsGenericParameter) {
2985 if (bounds == null) {
2986 bounds = new List<BoundInfo> [typeArguments.Length];
2987 tp_args = new TypeSpec [typeArguments.Length];
2989 tp_args [i] = typeArguments [i];
2991 fixed_types [i] = typeArguments [i];
2997 // Used together with AddCommonTypeBound fo implement
2998 // 7.4.2.13 Finding the best common type of a set of expressions
3000 public TypeInferenceContext ()
3002 fixed_types = new TypeSpec [1];
3003 tp_args = new TypeSpec [1];
3004 tp_args[0] = InternalType.Arglist; // it can be any internal type
3005 bounds = new List<BoundInfo> [1];
3008 public TypeSpec[] InferredTypeArguments {
3014 public void AddCommonTypeBound (TypeSpec type)
3016 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, false);
3019 public void AddCommonTypeBoundAsync (TypeSpec type)
3021 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, true);
3024 void AddToBounds (BoundInfo bound, int index, bool voidAllowed)
3027 // Some types cannot be used as type arguments
3029 if ((bound.Type.Kind == MemberKind.Void && !voidAllowed) || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
3030 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod || bound.Type == InternalType.VarOutType)
3033 var a = bounds [index];
3035 a = new List<BoundInfo> (2);
3041 if (a.Contains (bound))
3047 bool AllTypesAreFixed (TypeSpec[] types)
3049 foreach (TypeSpec t in types) {
3050 if (t.IsGenericParameter) {
3056 if (t.IsGeneric && !AllTypesAreFixed (t.TypeArguments))
3064 // 26.3.3.8 Exact Inference
3066 public int ExactInference (TypeSpec u, TypeSpec v)
3068 // If V is an array type
3073 var ac_u = (ArrayContainer) u;
3074 var ac_v = (ArrayContainer) v;
3075 if (ac_u.Rank != ac_v.Rank)
3078 return ExactInference (ac_u.Element, ac_v.Element);
3081 // If V is constructed type and U is constructed type
3082 if (TypeManager.IsGenericType (v)) {
3083 if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
3086 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
3087 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
3088 if (ga_u.Length != ga_v.Length)
3092 for (int i = 0; i < ga_u.Length; ++i)
3093 score += ExactInference (ga_u [i], ga_v [i]);
3095 return System.Math.Min (1, score);
3098 // If V is one of the unfixed type arguments
3099 int pos = IsUnfixed (v);
3103 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos, false);
3107 public bool FixAllTypes (ResolveContext ec)
3109 for (int i = 0; i < tp_args.Length; ++i) {
3110 if (!FixType (ec, i))
3117 // All unfixed type variables Xi are fixed for which all of the following hold:
3118 // a, There is at least one type variable Xj that depends on Xi
3119 // b, Xi has a non-empty set of bounds
3121 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
3123 for (int i = 0; i < tp_args.Length; ++i) {
3124 if (fixed_types[i] != null)
3127 if (bounds[i] == null)
3130 if (!FixType (ec, i))
3140 // All unfixed type variables Xi which depend on no Xj are fixed
3142 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
3144 var types_to_fix = new List<TypeSpec> (tp_args);
3145 for (int i = 0; i < methodParameters.Length; ++i) {
3146 TypeSpec t = methodParameters[i];
3148 if (!t.IsDelegate) {
3149 if (!t.IsExpressionTreeType)
3152 t = TypeManager.GetTypeArguments (t) [0];
3155 if (t.IsGenericParameter)
3158 var invoke = Delegate.GetInvokeMethod (t);
3159 TypeSpec rtype = invoke.ReturnType;
3160 while (rtype.IsArray)
3161 rtype = ((ArrayContainer) rtype).Element;
3163 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3166 // Remove dependent types, they cannot be fixed yet
3167 RemoveDependentTypes (types_to_fix, rtype);
3170 foreach (TypeSpec t in types_to_fix) {
3174 int idx = IsUnfixed (t);
3175 if (idx >= 0 && !FixType (ec, idx)) {
3180 fixed_any = types_to_fix.Count > 0;
3187 public bool FixType (ResolveContext ec, int i)
3189 // It's already fixed
3190 if (fixed_types[i] != null)
3191 throw new InternalErrorException ("Type argument has been already fixed");
3193 var candidates = bounds [i];
3194 if (candidates == null)
3197 if (candidates.Count == 1) {
3198 TypeSpec t = candidates[0].Type;
3199 if (t == InternalType.NullLiteral)
3202 fixed_types [i] = t;
3207 // The set of candidate types Uj starts out as the set of
3208 // all types in the set of bounds for Xi
3210 var applicable = new bool [candidates.Count];
3211 for (int ci = 0; ci < applicable.Length; ++ci)
3212 applicable [ci] = true;
3214 for (int ci = 0; ci < applicable.Length; ++ci) {
3215 var bound = candidates [ci];
3218 switch (bound.Kind) {
3219 case BoundKind.Exact:
3220 for (; cii != applicable.Length; ++cii) {
3224 if (!applicable[cii])
3228 // For each exact bound U of Xi all types Uj which are not identical
3229 // to U are removed from the candidate set
3231 if (candidates [cii].Type != bound.Type)
3232 applicable[cii] = false;
3236 case BoundKind.Lower:
3237 for (; cii != applicable.Length; ++cii) {
3241 if (!applicable[cii])
3245 // For each lower bound U of Xi all types Uj to which there is not an implicit conversion
3246 // from U are removed from the candidate set
3248 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), candidates [cii].Type)) {
3249 applicable[cii] = false;
3255 case BoundKind.Upper:
3256 for (; cii != applicable.Length; ++cii) {
3260 if (!applicable[cii])
3264 // For each upper bound U of Xi all types Uj from which there is not an implicit conversion
3265 // to U are removed from the candidate set
3267 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3268 applicable[cii] = false;
3275 TypeSpec best_candidate = null;
3276 for (int ci = 0; ci < applicable.Length; ++ci) {
3277 if (!applicable[ci])
3280 var bound = candidates [ci];
3281 if (bound.Type == best_candidate)
3285 for (; cii < applicable.Length; ++cii) {
3289 if (!applicable[cii])
3292 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3296 if (cii != applicable.Length)
3300 // We already have the best candidate, break if it's different (non-unique)
3302 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3304 if (best_candidate != null) {
3306 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3309 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3313 best_candidate = bound.Type;
3316 if (best_candidate == null)
3319 fixed_types[i] = best_candidate;
3323 public bool HasBounds (int pos)
3325 return bounds[pos] != null;
3329 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3330 // null when type parameter has not been fixed
3332 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3334 var tp = parameter as TypeParameterSpec;
3337 // Type inference works on generic arguments (MVAR) only
3339 if (!tp.IsMethodOwned)
3343 // Ensure the type parameter belongs to same container
3345 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3346 return fixed_types[tp.DeclaredPosition] ?? parameter;
3351 var gt = parameter as InflatedTypeSpec;
3353 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3354 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3355 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3356 if (inflated == null)
3359 inflated_targs[ii] = inflated;
3362 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3365 var ac = parameter as ArrayContainer;
3367 var inflated = InflateGenericArgument (context, ac.Element);
3368 if (inflated != ac.Element)
3369 return ArrayContainer.MakeType (context.Module, inflated);
3376 // Tests whether all delegate input arguments are fixed and generic output type
3377 // requires output type inference
3379 public bool IsReturnTypeNonDependent (MethodSpec invoke, TypeSpec returnType)
3381 AParametersCollection d_parameters = invoke.Parameters;
3383 if (d_parameters.IsEmpty)
3386 while (returnType.IsArray)
3387 returnType = ((ArrayContainer) returnType).Element;
3389 if (returnType.IsGenericParameter) {
3390 if (IsFixed (returnType))
3392 } else if (TypeManager.IsGenericType (returnType)) {
3393 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3395 // At least one unfixed return type has to exist
3396 if (AllTypesAreFixed (g_args))
3402 // All generic input arguments have to be fixed
3403 return AllTypesAreFixed (d_parameters.Types);
3406 bool IsFixed (TypeSpec type)
3408 return IsUnfixed (type) == -1;
3411 int IsUnfixed (TypeSpec type)
3413 if (!type.IsGenericParameter)
3416 for (int i = 0; i < tp_args.Length; ++i) {
3417 if (tp_args[i] == type) {
3418 if (fixed_types[i] != null)
3429 // 26.3.3.9 Lower-bound Inference
3431 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3433 return LowerBoundInference (u, v, false);
3437 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3439 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3441 // If V is one of the unfixed type arguments
3442 int pos = IsUnfixed (v);
3444 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos, false);
3448 // If U is an array type
3449 var u_ac = u as ArrayContainer;
3451 var v_ac = v as ArrayContainer;
3453 if (u_ac.Rank != v_ac.Rank)
3456 if (TypeSpec.IsValueType (u_ac.Element))
3457 return ExactInference (u_ac.Element, v_ac.Element);
3459 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3462 if (u_ac.Rank != 1 || !v.IsArrayGenericInterface)
3465 var v_i = TypeManager.GetTypeArguments (v) [0];
3466 if (TypeSpec.IsValueType (u_ac.Element))
3467 return ExactInference (u_ac.Element, v_i);
3469 return LowerBoundInference (u_ac.Element, v_i);
3472 if (v.IsGenericOrParentIsGeneric) {
3474 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3475 // such that U is identical to, inherits from (directly or indirectly),
3476 // or implements (directly or indirectly) C<U1..Uk>
3478 var u_candidates = new List<TypeSpec> ();
3479 var open_v = v.MemberDefinition;
3481 for (TypeSpec t = u; t != null; t = t.BaseType) {
3482 if (open_v == t.MemberDefinition)
3483 u_candidates.Add (t);
3486 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3487 // that would complicate the process a lot, instead I treat them as dynamic
3489 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3490 u_candidates.Add (t);
3493 if (u.Interfaces != null) {
3494 foreach (var iface in u.Interfaces) {
3495 if (open_v == iface.MemberDefinition)
3496 u_candidates.Add (iface);
3500 TypeSpec[] unique_candidate_targs = null;
3501 var ga_v = TypeSpec.GetAllTypeArguments (v);
3502 foreach (TypeSpec u_candidate in u_candidates) {
3504 // The unique set of types U1..Uk means that if we have an interface I<T>,
3505 // class U : I<int>, I<long> then no type inference is made when inferring
3506 // type I<T> by applying type U because T could be int or long
3508 if (unique_candidate_targs != null) {
3509 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3510 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3511 unique_candidate_targs = second_unique_candidate_targs;
3516 // Break when candidate arguments are ambiguous
3522 // A candidate is dynamic type expression, to simplify things use dynamic
3523 // for all type parameter of this type. For methods like this one
3525 // void M<T, U> (IList<T>, IList<U[]>)
3527 // dynamic becomes both T and U when the arguments are of dynamic type
3529 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3530 unique_candidate_targs = new TypeSpec[ga_v.Length];
3531 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3532 unique_candidate_targs[i] = u_candidate;
3534 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3538 if (unique_candidate_targs != null) {
3541 TypeParameterSpec[] tps = null;
3543 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3545 while (v.Arity == 0)
3546 v = v.DeclaringType;
3548 tps = v.MemberDefinition.TypeParameters;
3549 tp_index = tps.Length - 1;
3552 Variance variance = tps [tp_index--].Variance;
3554 TypeSpec u_i = unique_candidate_targs [i];
3555 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3556 if (ExactInference (u_i, ga_v [i]) == 0)
3559 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3560 (variance == Variance.Covariant && inversed);
3562 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3575 // 26.3.3.6 Output Type Inference
3577 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3579 // If e is a lambda or anonymous method with inferred return type
3580 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3582 TypeSpec rt = ame.InferReturnType (ec, this, t);
3583 var invoke = Delegate.GetInvokeMethod (t);
3586 AParametersCollection pd = invoke.Parameters;
3587 return ame.Parameters.Count == pd.Count ? 1 : 0;
3590 TypeSpec rtype = invoke.ReturnType;
3591 return LowerBoundInference (rt, rtype) + 1;
3595 // if E is a method group and T is a delegate type or expression tree type
3596 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3597 // resolution of E with the types T1..Tk yields a single method with return type U,
3598 // then a lower-bound inference is made from U for Tb.
3600 if (e is MethodGroupExpr) {
3601 if (!t.IsDelegate) {
3602 if (!t.IsExpressionTreeType)
3605 t = TypeManager.GetTypeArguments (t)[0];
3608 var invoke = Delegate.GetInvokeMethod (t);
3609 TypeSpec rtype = invoke.ReturnType;
3611 if (!IsReturnTypeNonDependent (invoke, rtype))
3614 // LAMESPEC: Standard does not specify that all methodgroup arguments
3615 // has to be fixed but it does not specify how to do recursive type inference
3616 // either. We choose the simple option and infer return type only
3617 // if all delegate generic arguments are fixed.
3618 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3619 for (int i = 0; i < param_types.Length; ++i) {
3620 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3621 if (inflated == null)
3624 param_types[i] = inflated;
3627 MethodGroupExpr mg = (MethodGroupExpr) e;
3628 Arguments args = DelegateCreation.CreateDelegateMethodArguments (ec, invoke.Parameters, param_types, e.Location);
3629 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3633 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3637 // if e is an expression with type U, then
3638 // a lower-bound inference is made from U for T
3640 return LowerBoundInference (e.Type, t) * 2;
3643 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3645 int idx = IsUnfixed (returnType);
3651 if (TypeManager.IsGenericType (returnType)) {
3652 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3653 RemoveDependentTypes (types, t);
3658 public bool UnfixedVariableExists {
3660 foreach (TypeSpec ut in fixed_types) {