2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
16 using System.Collections.Generic;
21 using MetaType = IKVM.Reflection.Type;
22 using IKVM.Reflection;
23 using IKVM.Reflection.Emit;
25 using MetaType = System.Type;
26 using System.Reflection;
27 using System.Reflection.Emit;
30 namespace Mono.CSharp {
31 public class VarianceDecl
33 public VarianceDecl (Variance variance, Location loc)
35 this.Variance = variance;
39 public Variance Variance { get; private set; }
40 public Location Location { get; private set; }
42 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
44 var tp = t as TypeParameterSpec;
47 if (expected == Variance.None && v != expected ||
48 expected == Variance.Covariant && v == Variance.Contravariant ||
49 expected == Variance.Contravariant && v == Variance.Covariant) {
50 ((TypeParameter) tp.MemberDefinition).ErrorInvalidVariance (member, expected);
56 if (t.TypeArguments.Length > 0) {
57 var targs_definition = t.MemberDefinition.TypeParameters;
58 TypeSpec[] targs = TypeManager.GetTypeArguments (t);
59 for (int i = 0; i < targs.Length; ++i) {
60 var v = targs_definition[i].Variance;
61 CheckTypeVariance (targs[i], (Variance) ((int) v * (int) expected), member);
67 var ac = t as ArrayContainer;
69 return CheckTypeVariance (ac.Element, expected, member);
78 // Don't add or modify internal values, they are used as -/+ calculation signs
86 public enum SpecialConstraint
94 public class SpecialContraintExpr : FullNamedExpression
96 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
99 this.Constraint = constraint;
102 public SpecialConstraint Constraint { get; private set; }
104 protected override Expression DoResolve (ResolveContext rc)
106 throw new NotImplementedException ();
109 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
111 throw new NotImplementedException ();
116 // A set of parsed constraints for a type parameter
118 public class Constraints
120 readonly SimpleMemberName tparam;
121 readonly List<FullNamedExpression> constraints;
122 readonly Location loc;
126 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
128 this.tparam = tparam;
129 this.constraints = constraints;
135 public List<FullNamedExpression> TypeExpressions {
141 public Location Location {
147 public SimpleMemberName TypeParameter {
155 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
157 if (spec.HasSpecialClass && bb.IsStruct) {
158 context.Module.Compiler.Report.Error (455, loc,
159 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
160 spec.Name, "class", bb.GetSignatureForError ());
165 return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
168 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
173 if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
176 Error_ConflictingConstraints (context, spec, ba, bb, loc);
180 public static void Error_ConflictingConstraints (IMemberContext context, TypeParameterSpec tp, TypeSpec ba, TypeSpec bb, Location loc)
182 context.Module.Compiler.Report.Error (455, loc,
183 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
184 tp.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
187 public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
189 foreach (var c in constraints) {
198 ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
199 if (obsolete_attr != null)
200 AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
203 ConstraintChecker.Check (context, t, c.Location);
208 // Resolve the constraints types with only possible early checks, return
209 // value `false' is reserved for recursive failure
211 public bool Resolve (IMemberContext context, TypeParameter tp)
221 List<TypeParameterSpec> tparam_types = null;
222 bool iface_found = false;
224 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
226 for (int i = 0; i < constraints.Count; ++i) {
227 var constraint = constraints[i];
229 if (constraint is SpecialContraintExpr) {
230 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
231 if (spec.HasSpecialStruct)
232 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
234 // Set to null as it does not have a type
235 constraints[i] = null;
239 var type = constraint.ResolveAsType (context);
243 if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
244 context.Module.Compiler.Report.Error (1968, constraint.Location,
245 "A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
249 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
250 context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
251 context.Module.Compiler.Report.Error (703, loc,
252 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
253 type.GetSignatureForError (), context.GetSignatureForError ());
256 if (type.IsInterface) {
257 if (!spec.AddInterface (type)) {
258 context.Module.Compiler.Report.Error (405, constraint.Location,
259 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
267 var constraint_tp = type as TypeParameterSpec;
268 if (constraint_tp != null) {
269 if (tparam_types == null) {
270 tparam_types = new List<TypeParameterSpec> (2);
271 } else if (tparam_types.Contains (constraint_tp)) {
272 context.Module.Compiler.Report.Error (405, constraint.Location,
273 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
278 // Checks whether each generic method parameter constraint type
279 // is valid with respect to T
281 if (tp.IsMethodTypeParameter) {
282 VarianceDecl.CheckTypeVariance (type, Variance.Contravariant, context);
285 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
286 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
287 context.Module.Compiler.Report.Error (454, constraint.Location,
288 "Circular constraint dependency involving `{0}' and `{1}'",
289 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
294 // Checks whether there are no conflicts between type parameter constraints
300 // A and B are not convertible and only 1 class constraint is allowed
302 if (constraint_tp.HasTypeConstraint) {
303 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
304 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
307 for (int ii = 0; ii < tparam_types.Count; ++ii) {
308 if (!tparam_types[ii].HasTypeConstraint)
311 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
317 if (constraint_tp.HasSpecialStruct) {
318 context.Module.Compiler.Report.Error (456, constraint.Location,
319 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
320 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
324 tparam_types.Add (constraint_tp);
328 if (iface_found || spec.HasTypeConstraint) {
329 context.Module.Compiler.Report.Error (406, constraint.Location,
330 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
331 type.GetSignatureForError ());
334 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
335 context.Module.Compiler.Report.Error (450, constraint.Location,
336 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
337 type.GetSignatureForError ());
340 switch (type.BuiltinType) {
341 case BuiltinTypeSpec.Type.Array:
342 case BuiltinTypeSpec.Type.Delegate:
343 case BuiltinTypeSpec.Type.MulticastDelegate:
344 case BuiltinTypeSpec.Type.Enum:
345 case BuiltinTypeSpec.Type.ValueType:
346 case BuiltinTypeSpec.Type.Object:
347 context.Module.Compiler.Report.Error (702, constraint.Location,
348 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
350 case BuiltinTypeSpec.Type.Dynamic:
351 context.Module.Compiler.Report.Error (1967, constraint.Location,
352 "A constraint cannot be the dynamic type");
356 if (type.IsSealed || !type.IsClass) {
357 context.Module.Compiler.Report.Error (701, loc,
358 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
359 type.GetSignatureForError ());
364 context.Module.Compiler.Report.Error (717, constraint.Location,
365 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
366 type.GetSignatureForError ());
369 spec.BaseType = type;
372 if (tparam_types != null)
373 spec.TypeArguments = tparam_types.ToArray ();
380 public void VerifyClsCompliance (Report report)
382 foreach (var c in constraints)
387 if (!c.Type.IsCLSCompliant ()) {
388 report.SymbolRelatedToPreviousError (c.Type);
389 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
390 c.Type.GetSignatureForError ());
397 // A type parameter for a generic type or generic method definition
399 public class TypeParameter : MemberCore, ITypeDefinition
401 static readonly string[] attribute_target = { "type parameter" };
403 Constraints constraints;
404 GenericTypeParameterBuilder builder;
405 readonly TypeParameterSpec spec;
407 public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance Variance)
408 : base (null, name, attrs)
410 this.constraints = constraints;
411 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, Variance, null);
417 public TypeParameter (MemberName name, Attributes attrs, VarianceDecl variance)
418 : base (null, name, attrs)
420 var var = variance == null ? Variance.None : variance.Variance;
421 this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, var, null);
422 this.VarianceDecl = variance;
425 public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
426 : base (null, name, attrs)
428 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
429 BaseType = spec.BaseType,
430 InterfacesDefined = spec.InterfacesDefined,
431 TypeArguments = spec.TypeArguments
437 public override AttributeTargets AttributeTargets {
439 return AttributeTargets.GenericParameter;
443 public Constraints Constraints {
452 public IAssemblyDefinition DeclaringAssembly {
454 return Module.DeclaringAssembly;
458 public override string DocCommentHeader {
460 throw new InvalidOperationException (
461 "Unexpected attempt to get doc comment from " + this.GetType ());
465 bool ITypeDefinition.IsComImport {
471 bool ITypeDefinition.IsPartial {
477 public bool IsMethodTypeParameter {
479 return spec.IsMethodOwned;
483 bool ITypeDefinition.IsTypeForwarder {
489 bool ITypeDefinition.IsCyclicTypeForwarder {
497 return MemberName.Name;
501 public string Namespace {
507 public TypeParameterSpec Type {
513 public int TypeParametersCount {
519 public TypeParameterSpec[] TypeParameters {
525 public override string[] ValidAttributeTargets {
527 return attribute_target;
531 public Variance Variance {
533 return spec.Variance;
537 public VarianceDecl VarianceDecl { get; private set; }
542 // This is called for each part of a partial generic type definition.
544 // If partial type parameters constraints are not null and we don't
545 // already have constraints they become our constraints. If we already
546 // have constraints, we must check that they're same.
548 public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
551 throw new InvalidOperationException ();
553 var new_constraints = tp.constraints;
554 if (new_constraints == null)
557 // TODO: could create spec only
558 //tp.Define (null, -1, part.Definition);
559 tp.spec.DeclaringType = part.Definition;
560 if (!tp.ResolveConstraints (part))
563 if (constraints != null)
564 return spec.HasSameConstraintsDefinition (tp.Type);
566 // Copy constraint from resolved part to partial container
567 spec.SpecialConstraint = tp.spec.SpecialConstraint;
568 spec.InterfacesDefined = tp.spec.InterfacesDefined;
569 spec.TypeArguments = tp.spec.TypeArguments;
570 spec.BaseType = tp.spec.BaseType;
575 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
577 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
580 public void CheckGenericConstraints (bool obsoleteCheck)
582 if (constraints != null)
583 constraints.CheckGenericConstraints (this, obsoleteCheck);
586 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
588 return new TypeParameter (spec, declaringSpec, MemberName, null);
591 public override bool Define ()
597 // This is the first method which is called during the resolving
598 // process; we're called immediately after creating the type parameters
599 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
602 public void Create (TypeSpec declaringType, TypeContainer parent)
605 throw new InternalErrorException ();
607 // Needed to get compiler reference
608 this.Parent = parent;
609 spec.DeclaringType = declaringType;
612 public void Define (GenericTypeParameterBuilder type)
615 spec.SetMetaInfo (type);
618 public void EmitConstraints (GenericTypeParameterBuilder builder)
620 var attr = GenericParameterAttributes.None;
621 if (spec.Variance == Variance.Contravariant)
622 attr |= GenericParameterAttributes.Contravariant;
623 else if (spec.Variance == Variance.Covariant)
624 attr |= GenericParameterAttributes.Covariant;
626 if (spec.HasSpecialClass)
627 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
628 else if (spec.HasSpecialStruct)
629 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
631 if (spec.HasSpecialConstructor)
632 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
634 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
635 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
637 if (spec.InterfacesDefined != null)
638 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
640 if (spec.TypeArguments != null) {
641 var meta_constraints = new List<MetaType> (spec.TypeArguments.Length);
642 foreach (var c in spec.TypeArguments) {
644 // Inflated type parameters can collide with special constraint types, don't
645 // emit any such type parameter.
647 if (c.BuiltinType == BuiltinTypeSpec.Type.Object || c.BuiltinType == BuiltinTypeSpec.Type.ValueType)
650 meta_constraints.Add (c.GetMetaInfo ());
653 builder.SetInterfaceConstraints (meta_constraints.ToArray ());
656 builder.SetGenericParameterAttributes (attr);
659 public override void Emit ()
661 EmitConstraints (builder);
663 if (OptAttributes != null)
664 OptAttributes.Emit ();
669 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
671 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
672 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
673 string gtype_variance;
675 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
676 case Variance.Covariant: gtype_variance = "covariantly"; break;
677 default: gtype_variance = "invariantly"; break;
680 Delegate d = mc as Delegate;
681 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
683 Report.Error (1961, Location,
684 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
685 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
688 public TypeSpec GetAttributeCoClass ()
693 public string GetAttributeDefaultMember ()
695 throw new NotSupportedException ();
698 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
700 throw new NotSupportedException ();
703 public override string GetSignatureForDocumentation ()
705 throw new NotImplementedException ();
708 public override string GetSignatureForError ()
710 return MemberName.Name;
713 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
715 return spec.MemberDefinition.DeclaringAssembly == assembly;
718 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
720 throw new NotSupportedException ("Not supported for compiled definition");
724 // Resolves all type parameter constraints
726 public bool ResolveConstraints (IMemberContext context)
728 if (constraints != null)
729 return constraints.Resolve (context, this);
731 if (spec.BaseType == null)
732 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
737 public override bool IsClsComplianceRequired ()
742 public new void VerifyClsCompliance ()
744 if (constraints != null)
745 constraints.VerifyClsCompliance (Report);
748 public void WarningParentNameConflict (TypeParameter conflict)
750 conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
751 conflict.Report.Warning (693, 3, Location,
752 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
753 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
757 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
758 public class TypeParameterSpec : TypeSpec
760 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
763 SpecialConstraint spec;
766 TypeSpec[] ifaces_defined;
769 // Creates type owned type parameter
771 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
772 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
774 this.variance = variance;
776 state &= ~StateFlags.Obsolete_Undetected;
781 // Creates method owned type parameter
783 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
784 : this (null, index, definition, spec, variance, info)
790 public int DeclaredPosition {
799 public bool HasSpecialConstructor {
801 return (spec & SpecialConstraint.Constructor) != 0;
805 public bool HasSpecialClass {
807 return (spec & SpecialConstraint.Class) != 0;
811 public bool HasSpecialStruct {
813 return (spec & SpecialConstraint.Struct) != 0;
817 public bool HasAnyTypeConstraint {
819 return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
823 public bool HasTypeConstraint {
825 var bt = BaseType.BuiltinType;
826 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
830 public override IList<TypeSpec> Interfaces {
832 if ((state & StateFlags.InterfacesExpanded) == 0) {
833 if (ifaces != null) {
834 if (ifaces_defined == null)
835 ifaces_defined = ifaces.ToArray ();
837 for (int i = 0; i < ifaces_defined.Length; ++i ) {
838 var iface_type = ifaces_defined[i];
839 var td = iface_type.MemberDefinition as TypeDefinition;
841 td.DoExpandBaseInterfaces ();
843 if (iface_type.Interfaces != null) {
844 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
845 var ii_iface_type = iface_type.Interfaces [ii];
846 AddInterface (ii_iface_type);
850 } else if (ifaces_defined == null) {
851 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
855 // Include all base type interfaces too, see ImportTypeBase for details
857 if (BaseType != null) {
858 var td = BaseType.MemberDefinition as TypeDefinition;
860 td.DoExpandBaseInterfaces ();
862 if (BaseType.Interfaces != null) {
863 foreach (var iface in BaseType.Interfaces) {
864 AddInterface (iface);
869 state |= StateFlags.InterfacesExpanded;
877 // Unexpanded interfaces list
879 public TypeSpec[] InterfacesDefined {
881 if (ifaces_defined == null) {
882 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
885 return ifaces_defined.Length == 0 ? null : ifaces_defined;
888 ifaces_defined = value;
889 if (value != null && value.Length != 0)
890 ifaces = new List<TypeSpec> (value);
894 public bool IsConstrained {
896 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
901 // Returns whether the type parameter is known to be a reference type
903 public new bool IsReferenceType {
905 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
906 return (spec & SpecialConstraint.Class) != 0;
909 // Full check is needed (see IsValueType for details)
911 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
915 foreach (var ta in targs) {
917 // Secondary special constraints are ignored (I am not sure why)
919 var tp = ta as TypeParameterSpec;
920 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
923 if (TypeSpec.IsReferenceType (ta))
933 // Returns whether the type parameter is known to be a value type
935 public new bool IsValueType {
938 // Even if structs/enums cannot be used directly as constraints
939 // they can apear as constraint type when inheriting base constraint
940 // which has dependant type parameter constraint which has been
941 // inflated using value type
943 // class A : B<int> { override void Foo<U> () {} }
944 // class B<T> { virtual void Foo<U> () where U : T {} }
946 if (HasSpecialStruct)
950 foreach (var ta in targs) {
951 if (TypeSpec.IsValueType (ta))
960 public override string Name {
962 return definition.Name;
966 public bool IsMethodOwned {
968 return DeclaringType == null;
972 public SpecialConstraint SpecialConstraint {
982 // Types used to inflate the generic type
984 public new TypeSpec[] TypeArguments {
993 public Variance Variance {
1001 public string DisplayDebugInfo ()
1003 var s = GetSignatureForError ();
1004 return IsMethodOwned ? s + "!!" : s + "!";
1008 // Finds effective base class. The effective base class is always a class-type
1010 public TypeSpec GetEffectiveBase ()
1012 if (HasSpecialStruct)
1016 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
1018 if (BaseType != null && targs == null) {
1020 // 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.
1022 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
1024 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
1025 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
1027 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
1031 if (HasTypeConstraint) {
1032 Array.Resize (ref types, types.Length + 1);
1034 for (int i = 0; i < types.Length - 1; ++i) {
1035 types[i] = types[i].BaseType;
1038 types[types.Length - 1] = BaseType;
1040 types = types.Select (l => l.BaseType).ToArray ();
1044 return Convert.FindMostEncompassedType (types);
1049 public override string GetSignatureForDocumentation ()
1051 var prefix = IsMethodOwned ? "``" : "`";
1052 return prefix + DeclaredPosition;
1055 public override string GetSignatureForError ()
1061 // Constraints have to match by definition but not position, used by
1062 // partial classes or methods
1064 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
1066 if (spec != other.spec)
1069 if (BaseType != other.BaseType)
1072 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
1075 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
1082 // Constraints have to match by using same set of types, used by
1083 // implicit interface implementation
1085 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
1087 if (spec != other.spec)
1091 // It can be same base type or inflated type parameter
1093 // interface I<T> { void Foo<U> where U : T; }
1094 // class A : I<int> { void Foo<X> where X : int {} }
1097 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
1098 if (other.targs == null)
1102 foreach (var otarg in other.targs) {
1103 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1113 // Check interfaces implementation -> definition
1114 if (InterfacesDefined != null) {
1116 // Iterate over inflated interfaces
1118 foreach (var iface in Interfaces) {
1120 if (other.InterfacesDefined != null) {
1121 foreach (var oiface in other.Interfaces) {
1122 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1132 if (other.targs != null) {
1133 foreach (var otarg in other.targs) {
1134 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1146 // Check interfaces implementation <- definition
1147 if (other.InterfacesDefined != null) {
1148 if (InterfacesDefined == null)
1152 // Iterate over inflated interfaces
1154 foreach (var oiface in other.Interfaces) {
1156 foreach (var iface in Interfaces) {
1157 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1168 // Check type parameters implementation -> definition
1169 if (targs != null) {
1170 if (other.targs == null)
1173 foreach (var targ in targs) {
1175 foreach (var otarg in other.targs) {
1176 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1187 // Check type parameters implementation <- definition
1188 if (other.targs != null) {
1189 foreach (var otarg in other.targs) {
1190 // Ignore inflated type arguments, were checked above
1191 if (!otarg.IsGenericParameter)
1198 foreach (var targ in targs) {
1199 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1213 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1215 return InflateConstraints (tparams, l => l, inflator);
1218 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1220 TypeParameterSpec[] constraints = null;
1221 TypeParameterInflator? inflator = null;
1223 for (int i = 0; i < tparams.Length; ++i) {
1224 var tp = tparams[i];
1225 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1226 if (constraints == null) {
1227 constraints = new TypeParameterSpec[tparams.Length];
1228 Array.Copy (tparams, constraints, constraints.Length);
1232 // Using a factory to avoid possibly expensive inflator build up
1234 if (inflator == null)
1235 inflator = inflatorFactory (arg);
1237 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1241 if (constraints == null)
1242 constraints = tparams;
1247 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1249 tps.BaseType = inflator.Inflate (BaseType);
1251 var defined = InterfacesDefined;
1252 if (defined != null) {
1253 tps.ifaces_defined = new TypeSpec[defined.Length];
1254 for (int i = 0; i < defined.Length; ++i)
1255 tps.ifaces_defined [i] = inflator.Inflate (defined[i]);
1256 } else if (ifaces_defined == TypeSpec.EmptyTypes) {
1257 tps.ifaces_defined = TypeSpec.EmptyTypes;
1260 var ifaces = Interfaces;
1261 if (ifaces != null) {
1262 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1263 for (int i = 0; i < ifaces.Count; ++i)
1264 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1265 tps.state |= StateFlags.InterfacesExpanded;
1268 if (targs != null) {
1269 tps.targs = new TypeSpec[targs.Length];
1270 for (int i = 0; i < targs.Length; ++i)
1271 tps.targs[i] = inflator.Inflate (targs[i]);
1275 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1277 var tps = (TypeParameterSpec) MemberwiseClone ();
1282 InflateConstraints (inflator, tps);
1287 // Populates type parameter members using type parameter constraints
1288 // The trick here is to be called late enough but not too late to
1289 // populate member cache with all members from other types
1291 protected override void InitializeMemberCache (bool onlyTypes)
1293 cache = new MemberCache ();
1296 // For a type parameter the membercache is the union of the sets of members of the types
1297 // specified as a primary constraint or secondary constraint
1299 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1300 cache.AddBaseType (BaseType);
1302 if (InterfacesDefined != null) {
1303 foreach (var iface_type in InterfacesDefined) {
1304 cache.AddInterface (iface_type);
1308 if (targs != null) {
1309 foreach (var ta in targs) {
1310 var b_type = ta.BaseType;
1311 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1312 cache.AddBaseType (b_type);
1314 var tps = ta as TypeParameterSpec;
1315 var ifaces = tps != null ? tps.InterfacesDefined : ta.Interfaces;
1317 if (ifaces != null) {
1318 foreach (var iface_type in ifaces) {
1319 cache.AddInterface (iface_type);
1326 public bool IsConvertibleToInterface (TypeSpec iface)
1328 if (Interfaces != null) {
1329 foreach (var t in Interfaces) {
1335 if (TypeArguments != null) {
1336 foreach (var t in TypeArguments) {
1337 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1345 public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
1347 var tps = md.TypeParameters;
1348 for (int i = 0; i < md.TypeParametersCount; ++i) {
1349 if (tps[i].HasAnyTypeConstraint) {
1357 public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
1359 var tps = md.TypeParameters;
1360 for (int i = 0; i < md.TypeParametersCount; ++i) {
1361 if (tps[i].IsConstrained) {
1369 public bool HasDependencyOn (TypeSpec type)
1371 if (TypeArguments != null) {
1372 foreach (var targ in TypeArguments) {
1373 if (TypeSpecComparer.Override.IsEqual (targ, type))
1376 var tps = targ as TypeParameterSpec;
1377 if (tps != null && tps.HasDependencyOn (type))
1385 public override TypeSpec Mutate (TypeParameterMutator mutator)
1387 return mutator.Mutate (this);
1391 public struct TypeParameterInflator
1393 readonly TypeSpec type;
1394 readonly TypeParameterSpec[] tparams;
1395 readonly TypeSpec[] targs;
1396 readonly IModuleContext context;
1398 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1399 : this (nested.context, type, nested.tparams, nested.targs)
1403 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1405 if (tparams.Length != targs.Length)
1406 throw new ArgumentException ("Invalid arguments");
1408 this.context = context;
1409 this.tparams = tparams;
1416 public IModuleContext Context {
1422 public TypeSpec TypeInstance {
1429 // Type parameters to inflate
1431 public TypeParameterSpec[] TypeParameters {
1439 public TypeSpec Inflate (TypeSpec type)
1441 var tp = type as TypeParameterSpec;
1443 return Inflate (tp);
1445 var ac = type as ArrayContainer;
1447 var et = Inflate (ac.Element);
1448 if (et != ac.Element)
1449 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1454 if (type.Kind == MemberKind.MissingType)
1458 // When inflating a nested type, inflate its parent first
1459 // in case it's using same type parameters (was inflated within the type)
1463 if (type.IsNested) {
1464 var parent = Inflate (type.DeclaringType);
1467 // Keep the inflated type arguments
1469 targs = type.TypeArguments;
1472 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1473 // because the import cache helps us to catch it. However, that means we have to look at
1474 // type definition to get type argument (they are in fact type parameter in this case)
1476 if (targs.Length == 0 && type.Arity > 0)
1477 targs = type.MemberDefinition.TypeParameters;
1480 // Parent was inflated, find the same type on inflated type
1481 // to use same cache for nested types on same generic parent
1483 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1486 // Handle the tricky case where parent shares local type arguments
1487 // which means inflating inflated type
1490 // public static Nested<T> Foo () { return null; }
1492 // public class Nested<U> {}
1495 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1497 if (targs.Length > 0) {
1498 var inflated_targs = new TypeSpec[targs.Length];
1499 for (; i < targs.Length; ++i)
1500 inflated_targs[i] = Inflate (targs[i]);
1502 type = type.MakeGenericType (context, inflated_targs);
1508 // Nothing to do for non-generic type
1509 if (type.Arity == 0)
1512 targs = new TypeSpec[type.Arity];
1515 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1517 if (type is InflatedTypeSpec) {
1518 for (; i < targs.Length; ++i)
1519 targs[i] = Inflate (type.TypeArguments[i]);
1521 type = type.GetDefinition ();
1524 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1526 var args = type.MemberDefinition.TypeParameters;
1527 foreach (var ds_tp in args)
1528 targs[i++] = Inflate (ds_tp);
1531 return type.MakeGenericType (context, targs);
1534 public TypeSpec Inflate (TypeParameterSpec tp)
1536 for (int i = 0; i < tparams.Length; ++i)
1537 if (tparams [i] == tp)
1540 // This can happen when inflating nested types
1541 // without type arguments specified
1547 // Before emitting any code we have to change all MVAR references to VAR
1548 // when the method is of generic type and has hoisted variables
1550 public class TypeParameterMutator
1552 readonly TypeParameters mvar;
1553 readonly TypeParameters var;
1554 readonly TypeParameterSpec[] src;
1555 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1557 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1559 if (mvar.Count != var.Count)
1560 throw new ArgumentException ();
1566 public TypeParameterMutator (TypeParameterSpec[] srcVar, TypeParameters destVar)
1568 if (srcVar.Length != destVar.Count)
1569 throw new ArgumentException ();
1577 public TypeParameters MethodTypeParameters {
1585 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1587 if (type is InflatedTypeSpec) {
1588 if (type.DeclaringType == null)
1589 return type.GetDefinition ();
1591 var parent = GetMemberDeclaringType (type.DeclaringType);
1592 type = MemberCache.GetMember<TypeSpec> (parent, type);
1598 public TypeSpec Mutate (TypeSpec ts)
1601 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1604 value = ts.Mutate (this);
1605 if (mutated_typespec == null)
1606 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1608 mutated_typespec.Add (ts, value);
1612 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1615 for (int i = 0; i < mvar.Count; ++i) {
1616 if (mvar[i].Type == tp)
1620 for (int i = 0; i < src.Length; ++i) {
1629 public TypeSpec[] Mutate (TypeSpec[] targs)
1631 TypeSpec[] mutated = new TypeSpec[targs.Length];
1632 bool changed = false;
1633 for (int i = 0; i < targs.Length; ++i) {
1634 mutated[i] = Mutate (targs[i]);
1635 changed |= targs[i] != mutated[i];
1638 return changed ? mutated : targs;
1643 /// A TypeExpr which already resolved to a type parameter.
1645 public class TypeParameterExpr : TypeExpression
1647 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1648 : base (type_parameter.Type, loc)
1650 this.eclass = ExprClass.TypeParameter;
1654 public class InflatedTypeSpec : TypeSpec
1657 TypeParameterSpec[] constraints;
1658 readonly TypeSpec open_type;
1659 readonly IModuleContext context;
1661 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1662 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1665 throw new ArgumentNullException ("targs");
1667 this.state &= ~SharedStateFlags;
1668 this.state |= (openType.state & SharedStateFlags);
1670 this.context = context;
1671 this.open_type = openType;
1674 foreach (var arg in targs) {
1675 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1676 state |= StateFlags.HasDynamicElement;
1681 if (open_type.Kind == MemberKind.MissingType)
1682 MemberCache = MemberCache.Empty;
1684 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1685 state |= StateFlags.ConstraintsChecked;
1690 public override TypeSpec BaseType {
1692 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1693 InitializeMemberCache (true);
1695 return base.BaseType;
1700 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1702 public TypeParameterSpec[] Constraints {
1704 if (constraints == null) {
1705 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1713 // Used to cache expensive constraints validation on constructed types
1715 public bool HasConstraintsChecked {
1717 return (state & StateFlags.ConstraintsChecked) != 0;
1720 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1724 public override IList<TypeSpec> Interfaces {
1727 InitializeMemberCache (true);
1729 return base.Interfaces;
1733 public override bool IsExpressionTreeType {
1735 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1739 public override bool IsArrayGenericInterface {
1741 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1745 public override bool IsGenericTask {
1747 return (open_type.state & StateFlags.GenericTask) != 0;
1751 public override bool IsNullableType {
1753 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1758 // Types used to inflate the generic type
1760 public override TypeSpec[] TypeArguments {
1768 public override bool AddInterface (TypeSpec iface)
1770 var inflator = CreateLocalInflator (context);
1771 iface = inflator.Inflate (iface);
1775 return base.AddInterface (iface);
1778 public static bool ContainsTypeParameter (TypeSpec type)
1780 if (type.Kind == MemberKind.TypeParameter)
1783 var element_container = type as ElementTypeSpec;
1784 if (element_container != null)
1785 return ContainsTypeParameter (element_container.Element);
1787 foreach (var t in type.TypeArguments) {
1788 if (ContainsTypeParameter (t)) {
1796 public TypeParameterInflator CreateLocalInflator (IModuleContext context)
1798 TypeParameterSpec[] tparams_full;
1799 TypeSpec[] targs_full = targs;
1802 // Special case is needed when we are inflating an open type (nested type definition)
1803 // on inflated parent. Consider following case
1805 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1807 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1809 List<TypeSpec> merged_targs = null;
1810 List<TypeParameterSpec> merged_tparams = null;
1812 var type = DeclaringType;
1815 if (type.TypeArguments.Length > 0) {
1816 if (merged_targs == null) {
1817 merged_targs = new List<TypeSpec> ();
1818 merged_tparams = new List<TypeParameterSpec> ();
1819 if (targs.Length > 0) {
1820 merged_targs.AddRange (targs);
1821 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1824 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1825 merged_targs.AddRange (type.TypeArguments);
1827 type = type.DeclaringType;
1828 } while (type != null);
1830 if (merged_targs != null) {
1831 // Type arguments are not in the right order but it should not matter in this case
1832 targs_full = merged_targs.ToArray ();
1833 tparams_full = merged_tparams.ToArray ();
1834 } else if (targs.Length == 0) {
1835 tparams_full = TypeParameterSpec.EmptyTypes;
1837 tparams_full = open_type.MemberDefinition.TypeParameters;
1839 } else if (targs.Length == 0) {
1840 tparams_full = TypeParameterSpec.EmptyTypes;
1842 tparams_full = open_type.MemberDefinition.TypeParameters;
1845 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1848 MetaType CreateMetaInfo ()
1851 // Converts nested type arguments into right order
1852 // Foo<string, bool>.Bar<int> => string, bool, int
1854 var all = new List<MetaType> ();
1855 TypeSpec type = this;
1856 TypeSpec definition = type;
1858 if (type.GetDefinition().IsGeneric) {
1860 type.TypeArguments != TypeSpec.EmptyTypes ?
1861 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1862 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1865 definition = definition.GetDefinition ();
1866 type = type.DeclaringType;
1867 } while (type != null);
1869 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1872 public override ObsoleteAttribute GetAttributeObsolete ()
1874 return open_type.GetAttributeObsolete ();
1877 protected override bool IsNotCLSCompliant (out bool attrValue)
1879 if (base.IsNotCLSCompliant (out attrValue))
1882 foreach (var ta in TypeArguments) {
1883 if (ta.MemberDefinition.CLSAttributeValue == false)
1890 public override TypeSpec GetDefinition ()
1895 public override MetaType GetMetaInfo ()
1898 info = CreateMetaInfo ();
1903 public override string GetSignatureForError ()
1906 return targs[0].GetSignatureForError () + "?";
1908 return base.GetSignatureForError ();
1911 protected override string GetTypeNameSignature ()
1913 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1916 return "<" + TypeManager.CSharpName (targs) + ">";
1919 public bool HasDynamicArgument ()
1921 for (int i = 0; i < targs.Length; ++i) {
1922 var item = targs[i];
1924 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1927 if (item is InflatedTypeSpec) {
1928 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1935 while (item.IsArray) {
1936 item = ((ArrayContainer) item).Element;
1939 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1947 protected override void InitializeMemberCache (bool onlyTypes)
1949 if (cache == null) {
1950 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1952 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1953 // for imported type parameter constraints referencing nested type of this declaration
1955 cache = new MemberCache (open_cache);
1958 var inflator = CreateLocalInflator (context);
1961 // Two stage inflate due to possible nested types recursive
1971 // When resolving type of `b' members of `B' cannot be
1972 // inflated because are not yet available in membercache
1974 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1975 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1978 // Inflate any implemented interfaces
1980 if (open_type.Interfaces != null) {
1981 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1982 foreach (var iface in open_type.Interfaces) {
1983 var iface_inflated = inflator.Inflate (iface);
1984 if (iface_inflated == null)
1987 base.AddInterface (iface_inflated);
1992 // Handles the tricky case of recursive nested base generic type
1994 // class A<T> : Base<A<T>.Nested> {
1998 // When inflating A<T>. base type is not yet known, secondary
1999 // inflation is required (not common case) once base scope
2002 if (open_type.BaseType == null) {
2004 state |= StateFlags.PendingBaseTypeInflate;
2006 BaseType = inflator.Inflate (open_type.BaseType);
2008 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2010 // It can happen when resolving base type without being defined
2011 // which is not allowed to happen and will always lead to an error
2013 // class B { class N {} }
2014 // class A<T> : A<B.N> {}
2016 if (open_type.BaseType == null)
2019 BaseType = inflator.Inflate (open_type.BaseType);
2020 state &= ~StateFlags.PendingBaseTypeInflate;
2024 state |= StateFlags.PendingMemberCacheMembers;
2028 var tc = open_type.MemberDefinition as TypeDefinition;
2029 if (tc != null && !tc.HasMembersDefined) {
2031 // Inflating MemberCache with undefined members
2036 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2037 BaseType = inflator.Inflate (open_type.BaseType);
2038 state &= ~StateFlags.PendingBaseTypeInflate;
2041 state &= ~StateFlags.PendingMemberCacheMembers;
2042 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
2045 public override TypeSpec Mutate (TypeParameterMutator mutator)
2047 var targs = TypeArguments;
2049 targs = mutator.Mutate (targs);
2051 var decl = DeclaringType;
2052 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
2053 decl = mutator.Mutate (decl);
2055 if (targs == TypeArguments && decl == DeclaringType)
2058 var mutated = (InflatedTypeSpec) MemberwiseClone ();
2059 if (decl != DeclaringType) {
2060 // Gets back MethodInfo in case of metaInfo was inflated
2061 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
2063 mutated.declaringType = decl;
2064 mutated.state |= StateFlags.PendingMetaInflate;
2067 if (targs != null) {
2068 mutated.targs = targs;
2069 mutated.info = null;
2078 // Tracks the type arguments when instantiating a generic type. It's used
2079 // by both type arguments and type parameters
2081 public class TypeArguments
2083 List<FullNamedExpression> args;
2086 public TypeArguments (params FullNamedExpression[] types)
2088 this.args = new List<FullNamedExpression> (types);
2091 public void Add (FullNamedExpression type)
2097 /// We may only be used after Resolve() is called and return the fully
2100 // TODO: Not needed, just return type from resolve
2101 public TypeSpec[] Arguments {
2116 public virtual bool IsEmpty {
2122 public List<FullNamedExpression> TypeExpressions {
2128 public string GetSignatureForError()
2130 StringBuilder sb = new StringBuilder ();
2131 for (int i = 0; i < Count; ++i) {
2134 sb.Append (expr.GetSignatureForError ());
2140 return sb.ToString ();
2144 /// Resolve the type arguments.
2146 public virtual bool Resolve (IMemberContext ec)
2151 int count = args.Count;
2154 atypes = new TypeSpec [count];
2156 for (int i = 0; i < count; i++){
2157 var te = args[i].ResolveAsType (ec);
2166 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
2167 te.GetSignatureForError ());
2171 if (te.IsPointer || te.IsSpecialRuntimeType) {
2172 ec.Module.Compiler.Report.Error (306, args[i].Location,
2173 "The type `{0}' may not be used as a type argument",
2174 te.GetSignatureForError ());
2185 public TypeArguments Clone ()
2187 TypeArguments copy = new TypeArguments ();
2188 foreach (var ta in args)
2195 public class UnboundTypeArguments : TypeArguments
2197 public UnboundTypeArguments (int arity)
2198 : base (new FullNamedExpression[arity])
2202 public override bool IsEmpty {
2208 public override bool Resolve (IMemberContext ec)
2210 // Nothing to be resolved
2215 public class TypeParameters
2217 List<TypeParameter> names;
2218 TypeParameterSpec[] types;
2220 public TypeParameters ()
2222 names = new List<TypeParameter> ();
2225 public TypeParameters (int count)
2227 names = new List<TypeParameter> (count);
2238 public TypeParameterSpec[] Types {
2246 public void Add (TypeParameter tparam)
2251 public void Add (TypeParameters tparams)
2253 names.AddRange (tparams.names);
2256 public void Create (TypeSpec declaringType, int parentOffset, TypeContainer parent)
2258 types = new TypeParameterSpec[Count];
2259 for (int i = 0; i < types.Length; ++i) {
2262 tp.Create (declaringType, parent);
2264 types[i].DeclaredPosition = i + parentOffset;
2266 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2267 parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2272 public void Define (GenericTypeParameterBuilder[] builders)
2274 for (int i = 0; i < types.Length; ++i) {
2276 tp.Define (builders [types [i].DeclaredPosition]);
2280 public TypeParameter this[int index] {
2282 return names [index];
2285 names[index] = value;
2289 public TypeParameter Find (string name)
2291 foreach (var tp in names) {
2292 if (tp.Name == name)
2299 public string[] GetAllNames ()
2301 return names.Select (l => l.Name).ToArray ();
2304 public string GetSignatureForError ()
2306 StringBuilder sb = new StringBuilder ();
2307 for (int i = 0; i < Count; ++i) {
2311 var name = names[i];
2313 sb.Append (name.GetSignatureForError ());
2316 return sb.ToString ();
2320 public void CheckPartialConstraints (Method part)
2322 var partTypeParameters = part.CurrentTypeParameters;
2324 for (int i = 0; i < Count; i++) {
2325 var tp_a = names[i];
2326 var tp_b = partTypeParameters [i];
2327 if (tp_a.Constraints == null) {
2328 if (tp_b.Constraints == null)
2330 } else if (tp_b.Constraints != null && tp_a.Type.HasSameConstraintsDefinition (tp_b.Type)) {
2334 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition.Location, "");
2335 part.Compiler.Report.Error (761, part.Location,
2336 "Partial method declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2337 part.GetSignatureForError (), partTypeParameters[i].GetSignatureForError ());
2341 public void UpdateConstraints (TypeDefinition part)
2343 var partTypeParameters = part.MemberName.TypeParameters;
2345 for (int i = 0; i < Count; i++) {
2347 if (tp.AddPartialConstraints (part, partTypeParameters [i]))
2350 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition);
2351 part.Compiler.Report.Error (265, part.Location,
2352 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2353 part.GetSignatureForError (), tp.GetSignatureForError ());
2357 public void VerifyClsCompliance ()
2359 foreach (var tp in names) {
2360 tp.VerifyClsCompliance ();
2366 // A type expression of generic type with type arguments
2368 class GenericTypeExpr : TypeExpr
2374 /// Instantiate the generic type `t' with the type arguments `args'.
2375 /// Use this constructor if you already know the fully resolved
2378 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2380 this.open_type = open_type;
2385 public override string GetSignatureForError ()
2387 return type.GetSignatureForError ();
2390 public override TypeSpec ResolveAsType (IMemberContext mc)
2392 if (eclass != ExprClass.Unresolved)
2395 if (!args.Resolve (mc))
2398 TypeSpec[] atypes = args.Arguments;
2401 // Now bind the parameters
2403 var inflated = open_type.MakeGenericType (mc, atypes);
2405 eclass = ExprClass.Type;
2408 // The constraints can be checked only when full type hierarchy is known
2410 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2411 var constraints = inflated.Constraints;
2412 if (constraints != null) {
2413 var cc = new ConstraintChecker (mc);
2414 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2415 inflated.HasConstraintsChecked = true;
2423 public override bool Equals (object obj)
2425 GenericTypeExpr cobj = obj as GenericTypeExpr;
2429 if ((type == null) || (cobj.type == null))
2432 return type == cobj.type;
2435 public override int GetHashCode ()
2437 return base.GetHashCode ();
2442 // Generic type with unbound type arguments, used for typeof (G<,,>)
2444 class GenericOpenTypeExpr : TypeExpression
2446 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2447 : base (type.GetDefinition (), loc)
2452 struct ConstraintChecker
2455 bool recursive_checks;
2457 public ConstraintChecker (IMemberContext ctx)
2460 recursive_checks = false;
2464 // Checks the constraints of open generic type against type
2465 // arguments. This version is used for types which could not be
2466 // checked immediatelly during construction because the type
2467 // hierarchy was not yet fully setup (before Emit phase)
2469 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2472 // Check declaring type first if there is any
2474 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2477 while (type is ElementTypeSpec)
2478 type = ((ElementTypeSpec) type).Element;
2480 if (type.Arity == 0)
2483 var gtype = type as InflatedTypeSpec;
2487 var constraints = gtype.Constraints;
2488 if (constraints == null)
2491 if (gtype.HasConstraintsChecked)
2494 var cc = new ConstraintChecker (mc);
2495 cc.recursive_checks = true;
2497 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2498 gtype.HasConstraintsChecked = true;
2506 // Checks all type arguments againts type parameters constraints
2507 // NOTE: It can run in probing mode when `this.mc' is null
2509 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2511 for (int i = 0; i < tparams.Length; i++) {
2512 var targ = targs[i];
2513 if (!CheckConstraint (context, targ, tparams [i], loc))
2516 if (!recursive_checks)
2519 if (!Check (mc, targ, loc))
2526 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2529 // First, check the `class' and `struct' constraints.
2531 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2533 mc.Module.Compiler.Report.Error (452, loc,
2534 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2535 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2541 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2543 mc.Module.Compiler.Report.Error (453, loc,
2544 "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}'",
2545 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2554 // Check the class constraint
2556 if (tparam.HasTypeConstraint) {
2557 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2566 // Check the interfaces constraints
2568 if (tparam.InterfacesDefined != null) {
2569 foreach (TypeSpec iface in tparam.InterfacesDefined) {
2570 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2581 // Check the type parameter constraint
2583 if (tparam.TypeArguments != null) {
2584 foreach (var ta in tparam.TypeArguments) {
2585 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2596 // Finally, check the constructor constraint.
2598 if (!tparam.HasSpecialConstructor)
2601 if (!HasDefaultConstructor (atype)) {
2603 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2604 mc.Module.Compiler.Report.Error (310, loc,
2605 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2606 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2614 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2616 for (int i = 0; i < targs.Length; ++i) {
2617 var targ = targs [i];
2618 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2621 if (HasDynamicTypeArgument (targ.TypeArguments))
2628 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2633 if (atype.IsGenericParameter) {
2634 var tps = (TypeParameterSpec) atype;
2635 if (tps.HasDependencyOn (ttype))
2638 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2641 } else if (TypeSpec.IsValueType (atype)) {
2642 if (atype.IsNullableType) {
2644 // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2646 if (TypeSpec.IsBaseClass (atype, ttype, false))
2649 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2653 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2658 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2659 if (atype.IsGenericParameter) {
2660 mc.Module.Compiler.Report.Error (314, loc,
2661 "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}'",
2662 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2663 } else if (TypeSpec.IsValueType (atype)) {
2664 if (atype.IsNullableType) {
2665 if (ttype.IsInterface) {
2666 mc.Module.Compiler.Report.Error (313, loc,
2667 "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}'",
2668 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2670 mc.Module.Compiler.Report.Error (312, loc,
2671 "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}'",
2672 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2675 mc.Module.Compiler.Report.Error (315, loc,
2676 "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}'",
2677 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2680 mc.Module.Compiler.Report.Error (311, loc,
2681 "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}'",
2682 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2689 static bool HasDefaultConstructor (TypeSpec atype)
2691 var tp = atype as TypeParameterSpec;
2693 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2696 if (atype.IsStruct || atype.IsEnum)
2699 if (atype.IsAbstract)
2702 var tdef = atype.GetDefinition ();
2704 var found = MemberCache.FindMember (tdef,
2705 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2706 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2708 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2713 // Implements C# type inference
2718 // Tracks successful rate of type inference
2720 int score = int.MaxValue;
2721 readonly Arguments arguments;
2722 readonly int arg_count;
2724 public TypeInference (Arguments arguments)
2726 this.arguments = arguments;
2727 if (arguments != null)
2728 arg_count = arguments.Count;
2731 public int InferenceScore {
2737 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2739 var method_generic_args = method.GenericDefinition.TypeParameters;
2740 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2741 if (!context.UnfixedVariableExists)
2742 return TypeSpec.EmptyTypes;
2744 AParametersCollection pd = method.Parameters;
2745 if (!InferInPhases (ec, context, pd))
2748 return context.InferredTypeArguments;
2752 // Implements method type arguments inference
2754 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2756 int params_arguments_start;
2757 if (methodParameters.HasParams) {
2758 params_arguments_start = methodParameters.Count - 1;
2760 params_arguments_start = arg_count;
2763 TypeSpec [] ptypes = methodParameters.Types;
2766 // The first inference phase
2768 TypeSpec method_parameter = null;
2769 for (int i = 0; i < arg_count; i++) {
2770 Argument a = arguments [i];
2774 if (i < params_arguments_start) {
2775 method_parameter = methodParameters.Types [i];
2776 } else if (i == params_arguments_start) {
2777 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2778 method_parameter = methodParameters.Types [params_arguments_start];
2780 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2782 ptypes = (TypeSpec[]) ptypes.Clone ();
2783 ptypes [i] = method_parameter;
2787 // When a lambda expression, an anonymous method
2788 // is used an explicit argument type inference takes a place
2790 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2792 if (am.ExplicitTypeInference (tic, method_parameter))
2798 score -= tic.ExactInference (a.Type, method_parameter);
2802 if (a.Expr.Type == InternalType.NullLiteral)
2805 if (TypeSpec.IsValueType (method_parameter)) {
2806 score -= tic.LowerBoundInference (a.Type, method_parameter);
2811 // Otherwise an output type inference is made
2813 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2817 // Part of the second phase but because it happens only once
2818 // we don't need to call it in cycle
2820 bool fixed_any = false;
2821 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2824 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2827 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2829 bool fixed_any = false;
2830 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2833 // If no further unfixed type variables exist, type inference succeeds
2834 if (!tic.UnfixedVariableExists)
2837 if (!fixed_any && fixDependent)
2840 // For all arguments where the corresponding argument output types
2841 // contain unfixed type variables but the input types do not,
2842 // an output type inference is made
2843 for (int i = 0; i < arg_count; i++) {
2845 // Align params arguments
2846 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2848 if (!t_i.IsDelegate) {
2849 if (!t_i.IsExpressionTreeType)
2852 t_i = TypeManager.GetTypeArguments (t_i) [0];
2855 var mi = Delegate.GetInvokeMethod (t_i);
2856 TypeSpec rtype = mi.ReturnType;
2858 if (tic.IsReturnTypeNonDependent (mi, rtype)) {
2859 // It can be null for default arguments
2860 if (arguments[i] == null)
2863 score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2868 return DoSecondPhase (ec, tic, methodParameters, true);
2872 public class TypeInferenceContext
2874 protected enum BoundKind
2881 struct BoundInfo : IEquatable<BoundInfo>
2883 public readonly TypeSpec Type;
2884 public readonly BoundKind Kind;
2886 public BoundInfo (TypeSpec type, BoundKind kind)
2892 public override int GetHashCode ()
2894 return Type.GetHashCode ();
2897 public Expression GetTypeExpression ()
2899 return new TypeExpression (Type, Location.Null);
2902 #region IEquatable<BoundInfo> Members
2904 public bool Equals (BoundInfo other)
2906 return Type == other.Type && Kind == other.Kind;
2912 readonly TypeSpec[] tp_args;
2913 readonly TypeSpec[] fixed_types;
2914 readonly List<BoundInfo>[] bounds;
2916 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2917 public TypeInferenceContext (TypeSpec[] typeArguments)
2919 if (typeArguments.Length == 0)
2920 throw new ArgumentException ("Empty generic arguments");
2922 fixed_types = new TypeSpec [typeArguments.Length];
2923 for (int i = 0; i < typeArguments.Length; ++i) {
2924 if (typeArguments [i].IsGenericParameter) {
2925 if (bounds == null) {
2926 bounds = new List<BoundInfo> [typeArguments.Length];
2927 tp_args = new TypeSpec [typeArguments.Length];
2929 tp_args [i] = typeArguments [i];
2931 fixed_types [i] = typeArguments [i];
2937 // Used together with AddCommonTypeBound fo implement
2938 // 7.4.2.13 Finding the best common type of a set of expressions
2940 public TypeInferenceContext ()
2942 fixed_types = new TypeSpec [1];
2943 tp_args = new TypeSpec [1];
2944 tp_args[0] = InternalType.Arglist; // it can be any internal type
2945 bounds = new List<BoundInfo> [1];
2948 public TypeSpec[] InferredTypeArguments {
2954 public void AddCommonTypeBound (TypeSpec type)
2956 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, false);
2959 public void AddCommonTypeBoundAsync (TypeSpec type)
2961 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, true);
2964 void AddToBounds (BoundInfo bound, int index, bool voidAllowed)
2967 // Some types cannot be used as type arguments
2969 if ((bound.Type.Kind == MemberKind.Void && !voidAllowed) || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2970 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
2973 var a = bounds [index];
2975 a = new List<BoundInfo> (2);
2981 if (a.Contains (bound))
2987 bool AllTypesAreFixed (TypeSpec[] types)
2989 foreach (TypeSpec t in types) {
2990 if (t.IsGenericParameter) {
2996 if (TypeManager.IsGenericType (t))
2997 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
3004 // 26.3.3.8 Exact Inference
3006 public int ExactInference (TypeSpec u, TypeSpec v)
3008 // If V is an array type
3013 var ac_u = (ArrayContainer) u;
3014 var ac_v = (ArrayContainer) v;
3015 if (ac_u.Rank != ac_v.Rank)
3018 return ExactInference (ac_u.Element, ac_v.Element);
3021 // If V is constructed type and U is constructed type
3022 if (TypeManager.IsGenericType (v)) {
3023 if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
3026 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
3027 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
3028 if (ga_u.Length != ga_v.Length)
3032 for (int i = 0; i < ga_u.Length; ++i)
3033 score += ExactInference (ga_u [i], ga_v [i]);
3035 return System.Math.Min (1, score);
3038 // If V is one of the unfixed type arguments
3039 int pos = IsUnfixed (v);
3043 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos, false);
3047 public bool FixAllTypes (ResolveContext ec)
3049 for (int i = 0; i < tp_args.Length; ++i) {
3050 if (!FixType (ec, i))
3057 // All unfixed type variables Xi are fixed for which all of the following hold:
3058 // a, There is at least one type variable Xj that depends on Xi
3059 // b, Xi has a non-empty set of bounds
3061 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
3063 for (int i = 0; i < tp_args.Length; ++i) {
3064 if (fixed_types[i] != null)
3067 if (bounds[i] == null)
3070 if (!FixType (ec, i))
3080 // All unfixed type variables Xi which depend on no Xj are fixed
3082 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
3084 var types_to_fix = new List<TypeSpec> (tp_args);
3085 for (int i = 0; i < methodParameters.Length; ++i) {
3086 TypeSpec t = methodParameters[i];
3088 if (!t.IsDelegate) {
3089 if (!t.IsExpressionTreeType)
3092 t = TypeManager.GetTypeArguments (t) [0];
3095 if (t.IsGenericParameter)
3098 var invoke = Delegate.GetInvokeMethod (t);
3099 TypeSpec rtype = invoke.ReturnType;
3100 while (rtype.IsArray)
3101 rtype = ((ArrayContainer) rtype).Element;
3103 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3106 // Remove dependent types, they cannot be fixed yet
3107 RemoveDependentTypes (types_to_fix, rtype);
3110 foreach (TypeSpec t in types_to_fix) {
3114 int idx = IsUnfixed (t);
3115 if (idx >= 0 && !FixType (ec, idx)) {
3120 fixed_any = types_to_fix.Count > 0;
3127 public bool FixType (ResolveContext ec, int i)
3129 // It's already fixed
3130 if (fixed_types[i] != null)
3131 throw new InternalErrorException ("Type argument has been already fixed");
3133 var candidates = bounds [i];
3134 if (candidates == null)
3137 if (candidates.Count == 1) {
3138 TypeSpec t = candidates[0].Type;
3139 if (t == InternalType.NullLiteral)
3142 fixed_types [i] = t;
3147 // The set of candidate types Uj starts out as the set of
3148 // all types in the set of bounds for Xi
3150 var applicable = new bool [candidates.Count];
3151 for (int ci = 0; ci < applicable.Length; ++ci)
3152 applicable [ci] = true;
3154 for (int ci = 0; ci < applicable.Length; ++ci) {
3155 var bound = candidates [ci];
3158 switch (bound.Kind) {
3159 case BoundKind.Exact:
3160 for (; cii != applicable.Length; ++cii) {
3164 if (!applicable[cii])
3168 // For each exact bound U of Xi all types Uj which are not identical
3169 // to U are removed from the candidate set
3171 if (candidates [cii].Type != bound.Type)
3172 applicable[cii] = false;
3176 case BoundKind.Lower:
3177 for (; cii != applicable.Length; ++cii) {
3181 if (!applicable[cii])
3185 // For each lower bound U of Xi all types Uj to which there is not an implicit conversion
3186 // from U are removed from the candidate set
3188 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), candidates [cii].Type)) {
3189 applicable[cii] = false;
3195 case BoundKind.Upper:
3196 for (; cii != applicable.Length; ++cii) {
3200 if (!applicable[cii])
3204 // For each upper bound U of Xi all types Uj from which there is not an implicit conversion
3205 // to U are removed from the candidate set
3207 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3208 applicable[cii] = false;
3215 TypeSpec best_candidate = null;
3216 for (int ci = 0; ci < applicable.Length; ++ci) {
3217 if (!applicable[ci])
3220 var bound = candidates [ci];
3221 if (bound.Type == best_candidate)
3225 for (; cii < applicable.Length; ++cii) {
3229 if (!applicable[cii])
3232 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3236 if (cii != applicable.Length)
3240 // We already have the best candidate, break if it's different (non-unique)
3242 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3244 if (best_candidate != null) {
3246 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3249 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3253 best_candidate = bound.Type;
3256 if (best_candidate == null)
3259 fixed_types[i] = best_candidate;
3263 public bool HasBounds (int pos)
3265 return bounds[pos] != null;
3269 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3270 // null when type parameter has not been fixed
3272 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3274 var tp = parameter as TypeParameterSpec;
3277 // Type inference works on generic arguments (MVAR) only
3279 if (!tp.IsMethodOwned)
3283 // Ensure the type parameter belongs to same container
3285 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3286 return fixed_types[tp.DeclaredPosition] ?? parameter;
3291 var gt = parameter as InflatedTypeSpec;
3293 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3294 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3295 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3296 if (inflated == null)
3299 inflated_targs[ii] = inflated;
3302 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3305 var ac = parameter as ArrayContainer;
3307 var inflated = InflateGenericArgument (context, ac.Element);
3308 if (inflated != ac.Element)
3309 return ArrayContainer.MakeType (context.Module, inflated);
3316 // Tests whether all delegate input arguments are fixed and generic output type
3317 // requires output type inference
3319 public bool IsReturnTypeNonDependent (MethodSpec invoke, TypeSpec returnType)
3321 AParametersCollection d_parameters = invoke.Parameters;
3323 if (d_parameters.IsEmpty)
3326 while (returnType.IsArray)
3327 returnType = ((ArrayContainer) returnType).Element;
3329 if (returnType.IsGenericParameter) {
3330 if (IsFixed (returnType))
3332 } else if (TypeManager.IsGenericType (returnType)) {
3333 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3335 // At least one unfixed return type has to exist
3336 if (AllTypesAreFixed (g_args))
3342 // All generic input arguments have to be fixed
3343 return AllTypesAreFixed (d_parameters.Types);
3346 bool IsFixed (TypeSpec type)
3348 return IsUnfixed (type) == -1;
3351 int IsUnfixed (TypeSpec type)
3353 if (!type.IsGenericParameter)
3356 for (int i = 0; i < tp_args.Length; ++i) {
3357 if (tp_args[i] == type) {
3358 if (fixed_types[i] != null)
3369 // 26.3.3.9 Lower-bound Inference
3371 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3373 return LowerBoundInference (u, v, false);
3377 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3379 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3381 // If V is one of the unfixed type arguments
3382 int pos = IsUnfixed (v);
3384 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos, false);
3388 // If U is an array type
3389 var u_ac = u as ArrayContainer;
3391 var v_ac = v as ArrayContainer;
3393 if (u_ac.Rank != v_ac.Rank)
3396 if (TypeSpec.IsValueType (u_ac.Element))
3397 return ExactInference (u_ac.Element, v_ac.Element);
3399 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3402 if (u_ac.Rank != 1 || !v.IsArrayGenericInterface)
3405 var v_i = TypeManager.GetTypeArguments (v) [0];
3406 if (TypeSpec.IsValueType (u_ac.Element))
3407 return ExactInference (u_ac.Element, v_i);
3409 return LowerBoundInference (u_ac.Element, v_i);
3412 if (v.IsGenericOrParentIsGeneric) {
3414 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3415 // such that U is identical to, inherits from (directly or indirectly),
3416 // or implements (directly or indirectly) C<U1..Uk>
3418 var u_candidates = new List<TypeSpec> ();
3419 var open_v = v.MemberDefinition;
3421 for (TypeSpec t = u; t != null; t = t.BaseType) {
3422 if (open_v == t.MemberDefinition)
3423 u_candidates.Add (t);
3426 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3427 // that would complicate the process a lot, instead I treat them as dynamic
3429 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3430 u_candidates.Add (t);
3433 if (u.Interfaces != null) {
3434 foreach (var iface in u.Interfaces) {
3435 if (open_v == iface.MemberDefinition)
3436 u_candidates.Add (iface);
3440 TypeSpec[] unique_candidate_targs = null;
3441 var ga_v = TypeSpec.GetAllTypeArguments (v);
3442 foreach (TypeSpec u_candidate in u_candidates) {
3444 // The unique set of types U1..Uk means that if we have an interface I<T>,
3445 // class U : I<int>, I<long> then no type inference is made when inferring
3446 // type I<T> by applying type U because T could be int or long
3448 if (unique_candidate_targs != null) {
3449 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3450 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3451 unique_candidate_targs = second_unique_candidate_targs;
3456 // Break when candidate arguments are ambiguous
3462 // A candidate is dynamic type expression, to simplify things use dynamic
3463 // for all type parameter of this type. For methods like this one
3465 // void M<T, U> (IList<T>, IList<U[]>)
3467 // dynamic becomes both T and U when the arguments are of dynamic type
3469 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3470 unique_candidate_targs = new TypeSpec[ga_v.Length];
3471 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3472 unique_candidate_targs[i] = u_candidate;
3474 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3478 if (unique_candidate_targs != null) {
3481 TypeParameterSpec[] tps = null;
3483 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3485 while (v.Arity == 0)
3486 v = v.DeclaringType;
3488 tps = v.MemberDefinition.TypeParameters;
3489 tp_index = tps.Length - 1;
3492 Variance variance = tps [tp_index--].Variance;
3494 TypeSpec u_i = unique_candidate_targs [i];
3495 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3496 if (ExactInference (u_i, ga_v [i]) == 0)
3499 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3500 (variance == Variance.Covariant && inversed);
3502 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3515 // 26.3.3.6 Output Type Inference
3517 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3519 // If e is a lambda or anonymous method with inferred return type
3520 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3522 TypeSpec rt = ame.InferReturnType (ec, this, t);
3523 var invoke = Delegate.GetInvokeMethod (t);
3526 AParametersCollection pd = invoke.Parameters;
3527 return ame.Parameters.Count == pd.Count ? 1 : 0;
3530 TypeSpec rtype = invoke.ReturnType;
3531 return LowerBoundInference (rt, rtype) + 1;
3535 // if E is a method group and T is a delegate type or expression tree type
3536 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3537 // resolution of E with the types T1..Tk yields a single method with return type U,
3538 // then a lower-bound inference is made from U for Tb.
3540 if (e is MethodGroupExpr) {
3541 if (!t.IsDelegate) {
3542 if (!t.IsExpressionTreeType)
3545 t = TypeManager.GetTypeArguments (t)[0];
3548 var invoke = Delegate.GetInvokeMethod (t);
3549 TypeSpec rtype = invoke.ReturnType;
3551 if (!IsReturnTypeNonDependent (invoke, rtype))
3554 // LAMESPEC: Standard does not specify that all methodgroup arguments
3555 // has to be fixed but it does not specify how to do recursive type inference
3556 // either. We choose the simple option and infer return type only
3557 // if all delegate generic arguments are fixed.
3558 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3559 for (int i = 0; i < param_types.Length; ++i) {
3560 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3561 if (inflated == null)
3564 param_types[i] = inflated;
3567 MethodGroupExpr mg = (MethodGroupExpr) e;
3568 Arguments args = DelegateCreation.CreateDelegateMethodArguments (ec, invoke.Parameters, param_types, e.Location);
3569 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3573 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3577 // if e is an expression with type U, then
3578 // a lower-bound inference is made from U for T
3580 return LowerBoundInference (e.Type, t) * 2;
3583 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3585 int idx = IsUnfixed (returnType);
3591 if (TypeManager.IsGenericType (returnType)) {
3592 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3593 RemoveDependentTypes (types, t);
3598 public bool UnfixedVariableExists {
3600 foreach (TypeSpec ut in fixed_types) {