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 t.CheckObsoleteness (context, c.Location);
201 ConstraintChecker.Check (context, t, c.Location);
206 // Resolve the constraints types with only possible early checks, return
207 // value `false' is reserved for recursive failure
209 public bool Resolve (IMemberContext context, TypeParameter tp)
219 List<TypeParameterSpec> tparam_types = null;
220 bool iface_found = false;
222 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
224 for (int i = 0; i < constraints.Count; ++i) {
225 var constraint = constraints[i];
227 if (constraint is SpecialContraintExpr) {
228 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
229 if (spec.HasSpecialStruct)
230 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
232 // Set to null as it does not have a type
233 constraints[i] = null;
237 var type = constraint.ResolveAsType (context);
241 if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
242 context.Module.Compiler.Report.Error (1968, constraint.Location,
243 "A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
247 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
248 context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
249 context.Module.Compiler.Report.Error (703, loc,
250 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
251 type.GetSignatureForError (), context.GetSignatureForError ());
254 if (type.IsInterface) {
255 if (!spec.AddInterface (type)) {
256 context.Module.Compiler.Report.Error (405, constraint.Location,
257 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
264 var constraint_tp = type as TypeParameterSpec;
265 if (constraint_tp != null) {
266 if (tparam_types == null) {
267 tparam_types = new List<TypeParameterSpec> (2);
268 } else if (tparam_types.Contains (constraint_tp)) {
269 context.Module.Compiler.Report.Error (405, constraint.Location,
270 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
275 // Checks whether each generic method parameter constraint type
276 // is valid with respect to T
278 if (tp.IsMethodTypeParameter) {
279 VarianceDecl.CheckTypeVariance (type, Variance.Contravariant, context);
282 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
283 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
284 context.Module.Compiler.Report.Error (454, constraint.Location,
285 "Circular constraint dependency involving `{0}' and `{1}'",
286 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
291 // Checks whether there are no conflicts between type parameter constraints
297 // A and B are not convertible and only 1 class constraint is allowed
299 if (constraint_tp.HasTypeConstraint) {
300 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
301 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
304 for (int ii = 0; ii < tparam_types.Count; ++ii) {
305 if (!tparam_types[ii].HasTypeConstraint)
308 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
314 if (constraint_tp.TypeArguments != null) {
315 var eb = constraint_tp.GetEffectiveBase ();
316 if (eb != null && !CheckConflictingInheritedConstraint (spec, eb, spec.BaseType, context, constraint.Location))
320 if (constraint_tp.HasSpecialStruct) {
321 context.Module.Compiler.Report.Error (456, constraint.Location,
322 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
323 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
327 tparam_types.Add (constraint_tp);
331 if (iface_found || spec.HasTypeConstraint) {
332 context.Module.Compiler.Report.Error (406, constraint.Location,
333 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
334 type.GetSignatureForError ());
337 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
338 context.Module.Compiler.Report.Error (450, constraint.Location,
339 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
340 type.GetSignatureForError ());
343 switch (type.BuiltinType) {
344 case BuiltinTypeSpec.Type.Array:
345 case BuiltinTypeSpec.Type.Delegate:
346 case BuiltinTypeSpec.Type.MulticastDelegate:
347 case BuiltinTypeSpec.Type.Enum:
348 case BuiltinTypeSpec.Type.ValueType:
349 case BuiltinTypeSpec.Type.Object:
350 context.Module.Compiler.Report.Error (702, constraint.Location,
351 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
353 case BuiltinTypeSpec.Type.Dynamic:
354 context.Module.Compiler.Report.Error (1967, constraint.Location,
355 "A constraint cannot be the dynamic type");
359 if (type.IsSealed || !type.IsClass) {
360 context.Module.Compiler.Report.Error (701, loc,
361 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
362 type.GetSignatureForError ());
367 context.Module.Compiler.Report.Error (717, constraint.Location,
368 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
369 type.GetSignatureForError ());
372 spec.BaseType = type;
375 if (tparam_types != null)
376 spec.TypeArguments = tparam_types.ToArray ();
383 public void VerifyClsCompliance (Report report)
385 foreach (var c in constraints)
390 if (!c.Type.IsCLSCompliant ()) {
391 report.SymbolRelatedToPreviousError (c.Type);
392 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
393 c.Type.GetSignatureForError ());
400 // A type parameter for a generic type or generic method definition
402 public class TypeParameter : MemberCore, ITypeDefinition
404 static readonly string[] attribute_target = { "type parameter" };
406 Constraints constraints;
407 GenericTypeParameterBuilder builder;
408 readonly TypeParameterSpec spec;
410 public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance Variance)
411 : base (null, name, attrs)
413 this.constraints = constraints;
414 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, Variance, null);
420 public TypeParameter (MemberName name, Attributes attrs, VarianceDecl variance)
421 : base (null, name, attrs)
423 var var = variance == null ? Variance.None : variance.Variance;
424 this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, var, null);
425 this.VarianceDecl = variance;
428 public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
429 : base (null, name, attrs)
431 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
432 BaseType = spec.BaseType,
433 InterfacesDefined = spec.InterfacesDefined,
434 TypeArguments = spec.TypeArguments
440 public override AttributeTargets AttributeTargets {
442 return AttributeTargets.GenericParameter;
446 public Constraints Constraints {
455 public IAssemblyDefinition DeclaringAssembly {
457 return Module.DeclaringAssembly;
461 public override string DocCommentHeader {
463 throw new InvalidOperationException (
464 "Unexpected attempt to get doc comment from " + this.GetType ());
468 bool ITypeDefinition.IsComImport {
474 bool ITypeDefinition.IsPartial {
480 public bool IsMethodTypeParameter {
482 return spec.IsMethodOwned;
486 bool ITypeDefinition.IsTypeForwarder {
492 bool ITypeDefinition.IsCyclicTypeForwarder {
500 return MemberName.Name;
504 public string Namespace {
510 public TypeParameterSpec Type {
516 public int TypeParametersCount {
522 public TypeParameterSpec[] TypeParameters {
528 public override string[] ValidAttributeTargets {
530 return attribute_target;
534 public Variance Variance {
536 return spec.Variance;
540 public VarianceDecl VarianceDecl { get; private set; }
545 // This is called for each part of a partial generic type definition.
547 // If partial type parameters constraints are not null and we don't
548 // already have constraints they become our constraints. If we already
549 // have constraints, we must check that they're same.
551 public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
554 throw new InvalidOperationException ();
556 var new_constraints = tp.constraints;
557 if (new_constraints == null)
560 // TODO: could create spec only
561 //tp.Define (null, -1, part.Definition);
562 tp.spec.DeclaringType = part.Definition;
563 if (!tp.ResolveConstraints (part))
566 if (constraints != null)
567 return spec.HasSameConstraintsDefinition (tp.Type);
569 // Copy constraint from resolved part to partial container
570 spec.SpecialConstraint = tp.spec.SpecialConstraint;
571 spec.InterfacesDefined = tp.spec.InterfacesDefined;
572 spec.TypeArguments = tp.spec.TypeArguments;
573 spec.BaseType = tp.spec.BaseType;
578 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
580 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
583 public void CheckGenericConstraints (bool obsoleteCheck)
585 if (constraints != null)
586 constraints.CheckGenericConstraints (this, obsoleteCheck);
589 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
591 return new TypeParameter (spec, declaringSpec, MemberName, null);
594 public override bool Define ()
600 // This is the first method which is called during the resolving
601 // process; we're called immediately after creating the type parameters
602 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
605 public void Create (TypeSpec declaringType, TypeContainer parent)
608 throw new InternalErrorException ();
610 // Needed to get compiler reference
611 this.Parent = parent;
612 spec.DeclaringType = declaringType;
615 public void Define (GenericTypeParameterBuilder type)
618 spec.SetMetaInfo (type);
621 public void Define (TypeParameter tp)
623 builder = tp.builder;
626 public void EmitConstraints (GenericTypeParameterBuilder builder)
628 var attr = GenericParameterAttributes.None;
629 if (spec.Variance == Variance.Contravariant)
630 attr |= GenericParameterAttributes.Contravariant;
631 else if (spec.Variance == Variance.Covariant)
632 attr |= GenericParameterAttributes.Covariant;
634 if (spec.HasSpecialClass)
635 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
636 else if (spec.HasSpecialStruct)
637 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
639 if (spec.HasSpecialConstructor)
640 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
642 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
643 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
645 if (spec.InterfacesDefined != null)
646 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
648 if (spec.TypeArguments != null) {
649 var meta_constraints = new List<MetaType> (spec.TypeArguments.Length);
650 foreach (var c in spec.TypeArguments) {
652 // Inflated type parameters can collide with base type constraint, don't
653 // emit any such type parameter.
655 if (c.IsClass && spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
658 meta_constraints.Add (c.GetMetaInfo ());
661 builder.SetInterfaceConstraints (meta_constraints.ToArray ());
664 builder.SetGenericParameterAttributes (attr);
667 public override void Emit ()
669 EmitConstraints (builder);
671 if (OptAttributes != null)
672 OptAttributes.Emit ();
677 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
679 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
680 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
681 string gtype_variance;
683 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
684 case Variance.Covariant: gtype_variance = "covariantly"; break;
685 default: gtype_variance = "invariantly"; break;
688 Delegate d = mc as Delegate;
689 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
691 Report.Error (1961, Location,
692 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
693 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
696 public TypeSpec GetAttributeCoClass ()
701 public string GetAttributeDefaultMember ()
703 throw new NotSupportedException ();
706 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
708 throw new NotSupportedException ();
711 public override string GetSignatureForDocumentation ()
713 throw new NotImplementedException ();
716 public override string GetSignatureForError ()
718 return MemberName.Name;
721 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
723 return spec.MemberDefinition.DeclaringAssembly == assembly;
726 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
728 throw new NotSupportedException ("Not supported for compiled definition");
732 // Resolves all type parameter constraints
734 public bool ResolveConstraints (IMemberContext context)
736 if (constraints != null)
737 return constraints.Resolve (context, this);
739 if (spec.BaseType == null)
740 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
745 public override bool IsClsComplianceRequired ()
750 public new void VerifyClsCompliance ()
752 if (constraints != null)
753 constraints.VerifyClsCompliance (Report);
756 public void WarningParentNameConflict (TypeParameter conflict)
758 conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
759 conflict.Report.Warning (693, 3, Location,
760 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
761 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
765 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
766 public class TypeParameterSpec : TypeSpec
768 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
771 SpecialConstraint spec;
774 TypeSpec[] ifaces_defined;
775 TypeSpec effective_base;
778 // Creates type owned type parameter
780 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
781 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
783 this.variance = variance;
785 state &= ~StateFlags.Obsolete_Undetected;
790 // Creates method owned type parameter
792 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
793 : this (null, index, definition, spec, variance, info)
799 public int DeclaredPosition {
808 public bool HasSpecialConstructor {
810 return (spec & SpecialConstraint.Constructor) != 0;
814 public bool HasSpecialClass {
816 return (spec & SpecialConstraint.Class) != 0;
820 public bool HasSpecialStruct {
822 return (spec & SpecialConstraint.Struct) != 0;
826 public bool HasAnyTypeConstraint {
828 return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
832 public bool HasTypeConstraint {
834 var bt = BaseType.BuiltinType;
835 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
839 public override IList<TypeSpec> Interfaces {
841 if ((state & StateFlags.InterfacesExpanded) == 0) {
842 if (ifaces != null) {
843 if (ifaces_defined == null)
844 ifaces_defined = ifaces.ToArray ();
846 for (int i = 0; i < ifaces_defined.Length; ++i ) {
847 var iface_type = ifaces_defined[i];
848 var td = iface_type.MemberDefinition as TypeDefinition;
850 td.DoExpandBaseInterfaces ();
852 if (iface_type.Interfaces != null) {
853 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
854 var ii_iface_type = iface_type.Interfaces [ii];
855 AddInterface (ii_iface_type);
859 } else if (ifaces_defined == null) {
860 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
864 // Include all base type interfaces too, see ImportTypeBase for details
866 if (BaseType != null) {
867 var td = BaseType.MemberDefinition as TypeDefinition;
869 td.DoExpandBaseInterfaces ();
871 if (BaseType.Interfaces != null) {
872 foreach (var iface in BaseType.Interfaces) {
873 AddInterface (iface);
878 state |= StateFlags.InterfacesExpanded;
886 // Unexpanded interfaces list
888 public TypeSpec[] InterfacesDefined {
890 if (ifaces_defined == null) {
891 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
894 return ifaces_defined.Length == 0 ? null : ifaces_defined;
897 ifaces_defined = value;
898 if (value != null && value.Length != 0)
899 ifaces = new List<TypeSpec> (value);
903 public bool IsConstrained {
905 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
910 // Returns whether the type parameter is known to be a reference type
912 public new bool IsReferenceType {
914 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
915 return (spec & SpecialConstraint.Class) != 0;
918 // Full check is needed (see IsValueType for details)
920 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
924 foreach (var ta in targs) {
926 // Secondary special constraints are ignored (I am not sure why)
928 var tp = ta as TypeParameterSpec;
929 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
932 if (TypeSpec.IsReferenceType (ta))
942 // Returns whether the type parameter is known to be a value type
944 public new bool IsValueType {
947 // Even if structs/enums cannot be used directly as constraints
948 // they can apear as constraint type when inheriting base constraint
949 // which has dependant type parameter constraint which has been
950 // inflated using value type
952 // class A : B<int> { override void Foo<U> () {} }
953 // class B<T> { virtual void Foo<U> () where U : T {} }
955 if (HasSpecialStruct)
959 foreach (var ta in targs) {
960 if (TypeSpec.IsValueType (ta))
969 public override string Name {
971 return definition.Name;
975 public bool IsMethodOwned {
977 return DeclaringType == null;
981 public SpecialConstraint SpecialConstraint {
991 // Types used to inflate the generic type
993 public new TypeSpec[] TypeArguments {
1002 public Variance Variance {
1010 public string DisplayDebugInfo ()
1012 var s = GetSignatureForError ();
1013 return IsMethodOwned ? s + "!!" : s + "!";
1017 // Finds effective base class. The effective base class is always a class-type
1019 public TypeSpec GetEffectiveBase ()
1021 if (HasSpecialStruct)
1025 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
1027 if (BaseType != null && targs == null) {
1029 // 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.
1031 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
1033 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
1034 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
1036 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
1039 if (effective_base != null)
1040 return effective_base;
1042 var types = new TypeSpec [HasTypeConstraint ? targs.Length + 1 : targs.Length];
1044 for (int i = 0; i < targs.Length; ++i) {
1047 // Same issue as above, inherited constraints can be of struct type
1049 types [i] = t.BaseType;
1053 var tps = t as TypeParameterSpec;
1054 types [i] = tps != null ? tps.GetEffectiveBase () : t;
1057 if (HasTypeConstraint)
1058 types [types.Length - 1] = BaseType;
1060 return effective_base = Convert.FindMostEncompassedType (types);
1063 public override string GetSignatureForDocumentation (bool explicitName)
1068 var prefix = IsMethodOwned ? "``" : "`";
1069 return prefix + DeclaredPosition;
1072 public override string GetSignatureForError ()
1078 // Constraints have to match by definition but not position, used by
1079 // partial classes or methods
1081 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
1083 if (spec != other.spec)
1086 if (BaseType != other.BaseType)
1089 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
1092 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
1099 // Constraints have to match by using same set of types, used by
1100 // implicit interface implementation
1102 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
1104 if (spec != other.spec)
1108 // It can be same base type or inflated type parameter
1110 // interface I<T> { void Foo<U> where U : T; }
1111 // class A : I<int> { void Foo<X> where X : int {} }
1114 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
1116 if (other.targs != null) {
1117 foreach (var otarg in other.targs) {
1118 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1123 } else if (targs != null) {
1124 foreach (var targ in targs) {
1125 if (TypeSpecComparer.Override.IsEqual (targ, other.BaseType)) {
1136 // Check interfaces implementation -> definition
1137 if (InterfacesDefined != null) {
1139 // Iterate over inflated interfaces
1141 foreach (var iface in InterfacesDefined) {
1143 if (other.InterfacesDefined != null) {
1144 foreach (var oiface in other.Interfaces) {
1145 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1155 if (other.targs != null) {
1156 foreach (var otarg in other.targs) {
1157 if (TypeSpecComparer.Override.IsEqual (iface, otarg)) {
1169 // Check interfaces implementation <- definition
1170 if (other.InterfacesDefined != null) {
1172 // Iterate over inflated interfaces
1174 foreach (var oiface in other.InterfacesDefined) {
1177 if (InterfacesDefined != null) {
1178 foreach (var iface in Interfaces) {
1179 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1184 } else if (targs != null) {
1185 foreach (var targ in targs) {
1186 if (TypeSpecComparer.Override.IsEqual (targ, oiface)) {
1198 // Check type parameters implementation -> definition
1199 if (targs != null) {
1200 foreach (var targ in targs) {
1203 if (other.targs != null) {
1204 foreach (var otarg in other.targs) {
1205 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1212 if (other.InterfacesDefined != null && !found) {
1213 foreach (var iface in other.Interfaces) {
1214 if (TypeSpecComparer.Override.IsEqual (iface, targ)) {
1222 found = TypeSpecComparer.Override.IsEqual (targ, other.BaseType);
1229 // Check type parameters implementation <- definition
1230 if (other.targs != null) {
1231 foreach (var otarg in other.targs) {
1232 // Ignore inflated type arguments, were checked above
1233 if (!otarg.IsGenericParameter)
1240 foreach (var targ in targs) {
1241 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1255 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1257 return InflateConstraints (tparams, l => l, inflator);
1260 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1262 TypeParameterSpec[] constraints = null;
1263 TypeParameterInflator? inflator = null;
1265 for (int i = 0; i < tparams.Length; ++i) {
1266 var tp = tparams[i];
1267 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1268 if (constraints == null) {
1269 constraints = new TypeParameterSpec[tparams.Length];
1270 Array.Copy (tparams, constraints, constraints.Length);
1274 // Using a factory to avoid possibly expensive inflator build up
1276 if (inflator == null)
1277 inflator = inflatorFactory (arg);
1279 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1283 if (constraints == null)
1284 constraints = tparams;
1289 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1291 tps.BaseType = inflator.Inflate (BaseType);
1293 var defined = InterfacesDefined;
1294 if (defined != null) {
1295 tps.ifaces_defined = new TypeSpec[defined.Length];
1296 for (int i = 0; i < defined.Length; ++i)
1297 tps.ifaces_defined [i] = inflator.Inflate (defined[i]);
1298 } else if (ifaces_defined == TypeSpec.EmptyTypes) {
1299 tps.ifaces_defined = TypeSpec.EmptyTypes;
1302 var ifaces = Interfaces;
1303 if (ifaces != null) {
1304 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1305 for (int i = 0; i < ifaces.Count; ++i)
1306 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1307 tps.state |= StateFlags.InterfacesExpanded;
1310 if (targs != null) {
1311 tps.targs = new TypeSpec[targs.Length];
1312 for (int i = 0; i < targs.Length; ++i)
1313 tps.targs[i] = inflator.Inflate (targs[i]);
1317 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1319 var tps = (TypeParameterSpec) MemberwiseClone ();
1324 InflateConstraints (inflator, tps);
1329 // Populates type parameter members using type parameter constraints
1330 // The trick here is to be called late enough but not too late to
1331 // populate member cache with all members from other types
1333 protected override void InitializeMemberCache (bool onlyTypes)
1335 cache = new MemberCache ();
1337 if (targs != null) {
1338 foreach (var ta in targs) {
1339 var tps = ta as TypeParameterSpec;
1340 var b_type = tps == null ? ta : tps.GetEffectiveBase ();
1343 // Find the most specific type when base type was inflated from base constraints
1345 if (b_type != null && !b_type.IsStructOrEnum && TypeSpec.IsBaseClass (b_type, BaseType, false))
1351 // For a type parameter the membercache is the union of the sets of members of the types
1352 // specified as a primary constraint or secondary constraint
1354 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType) {
1355 cache.AddBaseType (BaseType);
1358 if (InterfacesDefined != null) {
1359 foreach (var iface_type in InterfacesDefined) {
1360 cache.AddInterface (iface_type);
1365 // Import interfaces after base type to match behavior from ordinary classes
1367 if (targs != null) {
1368 foreach (var ta in targs) {
1369 var tps = ta as TypeParameterSpec;
1370 var ifaces = tps == null ? ta.Interfaces : tps.InterfacesDefined;
1372 if (ifaces != null) {
1373 foreach (var iface_type in ifaces) {
1374 cache.AddInterface (iface_type);
1381 public bool IsConvertibleToInterface (TypeSpec iface)
1383 if (Interfaces != null) {
1384 foreach (var t in Interfaces) {
1390 if (TypeArguments != null) {
1391 foreach (var t in TypeArguments) {
1392 var tps = t as TypeParameterSpec;
1394 if (tps.IsConvertibleToInterface (iface))
1400 if (t.ImplementsInterface (iface, false))
1408 public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
1410 var tps = md.TypeParameters;
1411 for (int i = 0; i < md.TypeParametersCount; ++i) {
1412 if (tps[i].HasAnyTypeConstraint) {
1420 public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
1422 var tps = md.TypeParameters;
1423 for (int i = 0; i < md.TypeParametersCount; ++i) {
1424 if (tps[i].IsConstrained) {
1432 public bool HasDependencyOn (TypeSpec type)
1434 if (TypeArguments != null) {
1435 foreach (var targ in TypeArguments) {
1436 if (TypeSpecComparer.Override.IsEqual (targ, type))
1439 var tps = targ as TypeParameterSpec;
1440 if (tps != null && tps.HasDependencyOn (type))
1448 public override TypeSpec Mutate (TypeParameterMutator mutator)
1450 return mutator.Mutate (this);
1454 public struct TypeParameterInflator
1456 readonly TypeSpec type;
1457 readonly TypeParameterSpec[] tparams;
1458 readonly TypeSpec[] targs;
1459 readonly IModuleContext context;
1461 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1462 : this (nested.context, type, nested.tparams, nested.targs)
1466 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1468 if (tparams.Length != targs.Length)
1469 throw new ArgumentException ("Invalid arguments");
1471 this.context = context;
1472 this.tparams = tparams;
1479 public IModuleContext Context {
1485 public TypeSpec TypeInstance {
1492 // Type parameters to inflate
1494 public TypeParameterSpec[] TypeParameters {
1502 public TypeSpec Inflate (TypeSpec type)
1504 var tp = type as TypeParameterSpec;
1506 return Inflate (tp);
1508 var ec = type as ElementTypeSpec;
1510 var et = Inflate (ec.Element);
1511 if (et != ec.Element) {
1512 var ac = ec as ArrayContainer;
1514 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1516 if (ec is PointerContainer)
1517 return PointerContainer.MakeType (context.Module, et);
1519 throw new NotImplementedException ();
1525 if (type.Kind == MemberKind.MissingType)
1529 // When inflating a nested type, inflate its parent first
1530 // in case it's using same type parameters (was inflated within the type)
1534 if (type.IsNested) {
1535 var parent = Inflate (type.DeclaringType);
1538 // Keep the inflated type arguments
1540 targs = type.TypeArguments;
1543 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1544 // because the import cache helps us to catch it. However, that means we have to look at
1545 // type definition to get type argument (they are in fact type parameter in this case)
1547 if (targs.Length == 0 && type.Arity > 0)
1548 targs = type.MemberDefinition.TypeParameters;
1551 // Parent was inflated, find the same type on inflated type
1552 // to use same cache for nested types on same generic parent
1554 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1557 // Handle the tricky case where parent shares local type arguments
1558 // which means inflating inflated type
1561 // public static Nested<T> Foo () { return null; }
1563 // public class Nested<U> {}
1566 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1568 if (targs.Length > 0) {
1569 var inflated_targs = new TypeSpec[targs.Length];
1570 for (; i < targs.Length; ++i)
1571 inflated_targs[i] = Inflate (targs[i]);
1573 type = type.MakeGenericType (context, inflated_targs);
1579 // Nothing to do for non-generic type
1580 if (type.Arity == 0)
1583 targs = new TypeSpec[type.Arity];
1586 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1588 if (type is InflatedTypeSpec) {
1589 for (; i < targs.Length; ++i)
1590 targs[i] = Inflate (type.TypeArguments[i]);
1592 type = type.GetDefinition ();
1595 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1597 var args = type.MemberDefinition.TypeParameters;
1598 foreach (var ds_tp in args)
1599 targs[i++] = Inflate (ds_tp);
1602 return type.MakeGenericType (context, targs);
1605 public TypeSpec Inflate (TypeParameterSpec tp)
1607 for (int i = 0; i < tparams.Length; ++i)
1608 if (tparams [i] == tp)
1611 // This can happen when inflating nested types
1612 // without type arguments specified
1618 // Before emitting any code we have to change all MVAR references to VAR
1619 // when the method is of generic type and has hoisted variables
1621 public class TypeParameterMutator
1623 readonly TypeParameters mvar;
1624 readonly TypeParameters var;
1625 readonly TypeParameterSpec[] src;
1626 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1628 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1630 if (mvar.Count != var.Count)
1631 throw new ArgumentException ();
1637 public TypeParameterMutator (TypeParameterSpec[] srcVar, TypeParameters destVar)
1639 if (srcVar.Length != destVar.Count)
1640 throw new ArgumentException ();
1648 public TypeParameters MethodTypeParameters {
1656 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1658 if (type is InflatedTypeSpec) {
1659 if (type.DeclaringType == null)
1660 return type.GetDefinition ();
1662 var parent = GetMemberDeclaringType (type.DeclaringType);
1663 type = MemberCache.GetMember<TypeSpec> (parent, type);
1669 public TypeSpec Mutate (TypeSpec ts)
1672 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1675 value = ts.Mutate (this);
1676 if (mutated_typespec == null)
1677 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1679 mutated_typespec.Add (ts, value);
1683 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1686 for (int i = 0; i < mvar.Count; ++i) {
1687 if (mvar[i].Type == tp)
1691 for (int i = 0; i < src.Length; ++i) {
1700 public TypeSpec[] Mutate (TypeSpec[] targs)
1702 TypeSpec[] mutated = new TypeSpec[targs.Length];
1703 bool changed = false;
1704 for (int i = 0; i < targs.Length; ++i) {
1705 mutated[i] = Mutate (targs[i]);
1706 changed |= targs[i] != mutated[i];
1709 return changed ? mutated : targs;
1714 /// A TypeExpr which already resolved to a type parameter.
1716 public class TypeParameterExpr : TypeExpression
1718 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1719 : base (type_parameter.Type, loc)
1721 this.eclass = ExprClass.TypeParameter;
1725 public class InflatedTypeSpec : TypeSpec
1728 TypeParameterSpec[] constraints;
1729 readonly TypeSpec open_type;
1730 readonly IModuleContext context;
1732 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1733 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1736 throw new ArgumentNullException ("targs");
1738 this.state &= ~SharedStateFlags;
1739 this.state |= (openType.state & SharedStateFlags);
1741 this.context = context;
1742 this.open_type = openType;
1745 foreach (var arg in targs) {
1746 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1747 state |= StateFlags.HasDynamicElement;
1752 if (open_type.Kind == MemberKind.MissingType)
1753 MemberCache = MemberCache.Empty;
1755 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1756 state |= StateFlags.ConstraintsChecked;
1761 public override TypeSpec BaseType {
1763 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1764 InitializeMemberCache (true);
1766 return base.BaseType;
1771 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1773 public TypeParameterSpec[] Constraints {
1775 if (constraints == null) {
1776 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1784 // Used to cache expensive constraints validation on constructed types
1786 public bool HasConstraintsChecked {
1788 return (state & StateFlags.ConstraintsChecked) != 0;
1791 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1795 public override IList<TypeSpec> Interfaces {
1798 InitializeMemberCache (true);
1800 return base.Interfaces;
1804 public override bool IsExpressionTreeType {
1806 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1810 public override bool IsArrayGenericInterface {
1812 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1816 public override bool IsGenericTask {
1818 return (open_type.state & StateFlags.GenericTask) != 0;
1822 public override bool IsNullableType {
1824 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1829 // Types used to inflate the generic type
1831 public override TypeSpec[] TypeArguments {
1839 public override bool AddInterface (TypeSpec iface)
1841 var inflator = CreateLocalInflator (context);
1842 iface = inflator.Inflate (iface);
1846 return base.AddInterface (iface);
1849 public static bool ContainsTypeParameter (TypeSpec type)
1851 if (type.Kind == MemberKind.TypeParameter)
1854 var element_container = type as ElementTypeSpec;
1855 if (element_container != null)
1856 return ContainsTypeParameter (element_container.Element);
1858 foreach (var t in type.TypeArguments) {
1859 if (ContainsTypeParameter (t)) {
1867 public TypeParameterInflator CreateLocalInflator (IModuleContext context)
1869 TypeParameterSpec[] tparams_full;
1870 TypeSpec[] targs_full = targs;
1873 // Special case is needed when we are inflating an open type (nested type definition)
1874 // on inflated parent. Consider following case
1876 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1878 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1880 List<TypeSpec> merged_targs = null;
1881 List<TypeParameterSpec> merged_tparams = null;
1883 var type = DeclaringType;
1886 if (type.TypeArguments.Length > 0) {
1887 if (merged_targs == null) {
1888 merged_targs = new List<TypeSpec> ();
1889 merged_tparams = new List<TypeParameterSpec> ();
1890 if (targs.Length > 0) {
1891 merged_targs.AddRange (targs);
1892 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1895 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1896 merged_targs.AddRange (type.TypeArguments);
1898 type = type.DeclaringType;
1899 } while (type != null);
1901 if (merged_targs != null) {
1902 // Type arguments are not in the right order but it should not matter in this case
1903 targs_full = merged_targs.ToArray ();
1904 tparams_full = merged_tparams.ToArray ();
1905 } else if (targs.Length == 0) {
1906 tparams_full = TypeParameterSpec.EmptyTypes;
1908 tparams_full = open_type.MemberDefinition.TypeParameters;
1910 } else if (targs.Length == 0) {
1911 tparams_full = TypeParameterSpec.EmptyTypes;
1913 tparams_full = open_type.MemberDefinition.TypeParameters;
1916 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1919 MetaType CreateMetaInfo ()
1922 // Converts nested type arguments into right order
1923 // Foo<string, bool>.Bar<int> => string, bool, int
1925 var all = new List<MetaType> ();
1926 TypeSpec type = this;
1927 TypeSpec definition = type;
1929 if (type.GetDefinition().IsGeneric) {
1931 type.TypeArguments != TypeSpec.EmptyTypes ?
1932 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1933 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1936 definition = definition.GetDefinition ();
1937 type = type.DeclaringType;
1938 } while (type != null);
1940 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1943 public override void CheckObsoleteness (IMemberContext mc, Location loc)
1945 base.CheckObsoleteness (mc, loc);
1947 foreach (var ta in TypeArguments)
1948 ta.CheckObsoleteness (mc, loc);
1951 public override ObsoleteAttribute GetAttributeObsolete ()
1953 return open_type.GetAttributeObsolete ();
1956 protected override bool IsNotCLSCompliant (out bool attrValue)
1958 if (base.IsNotCLSCompliant (out attrValue))
1961 foreach (var ta in TypeArguments) {
1962 if (ta.MemberDefinition.CLSAttributeValue == false)
1969 public override TypeSpec GetDefinition ()
1974 public override MetaType GetMetaInfo ()
1977 info = CreateMetaInfo ();
1982 public override string GetSignatureForError ()
1985 return targs[0].GetSignatureForError () + "?";
1987 return base.GetSignatureForError ();
1990 protected override string GetTypeNameSignature ()
1992 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1995 return "<" + TypeManager.CSharpName (targs) + ">";
1998 public bool HasDynamicArgument ()
2000 for (int i = 0; i < targs.Length; ++i) {
2001 var item = targs[i];
2003 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2006 if (item is InflatedTypeSpec) {
2007 if (((InflatedTypeSpec) item).HasDynamicArgument ())
2014 while (item.IsArray) {
2015 item = ((ArrayContainer) item).Element;
2018 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2026 protected override void InitializeMemberCache (bool onlyTypes)
2028 if (cache == null) {
2029 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
2031 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
2032 // for imported type parameter constraints referencing nested type of this declaration
2034 cache = new MemberCache (open_cache);
2037 var inflator = CreateLocalInflator (context);
2040 // Two stage inflate due to possible nested types recursive
2050 // When resolving type of `b' members of `B' cannot be
2051 // inflated because are not yet available in membercache
2053 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
2054 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
2057 // Inflate any implemented interfaces
2059 if (open_type.Interfaces != null) {
2060 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
2061 foreach (var iface in open_type.Interfaces) {
2062 var iface_inflated = inflator.Inflate (iface);
2063 if (iface_inflated == null)
2066 base.AddInterface (iface_inflated);
2071 // Handles the tricky case of recursive nested base generic type
2073 // class A<T> : Base<A<T>.Nested> {
2077 // When inflating A<T>. base type is not yet known, secondary
2078 // inflation is required (not common case) once base scope
2081 if (open_type.BaseType == null) {
2083 state |= StateFlags.PendingBaseTypeInflate;
2085 BaseType = inflator.Inflate (open_type.BaseType);
2087 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2089 // It can happen when resolving base type without being defined
2090 // which is not allowed to happen and will always lead to an error
2092 // class B { class N {} }
2093 // class A<T> : A<B.N> {}
2095 if (open_type.BaseType == null)
2098 BaseType = inflator.Inflate (open_type.BaseType);
2099 state &= ~StateFlags.PendingBaseTypeInflate;
2103 state |= StateFlags.PendingMemberCacheMembers;
2107 var tc = open_type.MemberDefinition as TypeDefinition;
2108 if (tc != null && !tc.HasMembersDefined) {
2110 // Inflating MemberCache with undefined members
2115 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2116 BaseType = inflator.Inflate (open_type.BaseType);
2117 state &= ~StateFlags.PendingBaseTypeInflate;
2120 state &= ~StateFlags.PendingMemberCacheMembers;
2121 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
2124 public override TypeSpec Mutate (TypeParameterMutator mutator)
2126 var targs = TypeArguments;
2128 targs = mutator.Mutate (targs);
2130 var decl = DeclaringType;
2131 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
2132 decl = mutator.Mutate (decl);
2134 if (targs == TypeArguments && decl == DeclaringType)
2137 var mutated = (InflatedTypeSpec) MemberwiseClone ();
2138 if (decl != DeclaringType) {
2139 // Gets back MethodInfo in case of metaInfo was inflated
2140 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
2142 mutated.declaringType = decl;
2143 mutated.state |= StateFlags.PendingMetaInflate;
2146 if (targs != null) {
2147 mutated.targs = targs;
2148 mutated.info = null;
2157 // Tracks the type arguments when instantiating a generic type. It's used
2158 // by both type arguments and type parameters
2160 public class TypeArguments
2162 List<FullNamedExpression> args;
2165 public TypeArguments (params FullNamedExpression[] types)
2167 this.args = new List<FullNamedExpression> (types);
2170 public void Add (FullNamedExpression type)
2176 /// We may only be used after Resolve() is called and return the fully
2179 // TODO: Not needed, just return type from resolve
2180 public TypeSpec[] Arguments {
2195 public virtual bool IsEmpty {
2201 public List<FullNamedExpression> TypeExpressions {
2207 public string GetSignatureForError()
2209 StringBuilder sb = new StringBuilder ();
2210 for (int i = 0; i < Count; ++i) {
2213 sb.Append (expr.GetSignatureForError ());
2219 return sb.ToString ();
2223 /// Resolve the type arguments.
2225 public virtual bool Resolve (IMemberContext ec, bool allowUnbound)
2230 int count = args.Count;
2233 atypes = new TypeSpec [count];
2235 var errors = ec.Module.Compiler.Report.Errors;
2237 for (int i = 0; i < count; i++){
2238 var te = args[i].ResolveAsType (ec);
2247 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
2248 te.GetSignatureForError ());
2252 if (te.IsPointer || te.IsSpecialRuntimeType) {
2253 ec.Module.Compiler.Report.Error (306, args[i].Location,
2254 "The type `{0}' may not be used as a type argument",
2255 te.GetSignatureForError ());
2260 if (!ok || errors != ec.Module.Compiler.Report.Errors)
2266 public TypeArguments Clone ()
2268 TypeArguments copy = new TypeArguments ();
2269 foreach (var ta in args)
2276 public class UnboundTypeArguments : TypeArguments
2280 public UnboundTypeArguments (int arity, Location loc)
2281 : base (new FullNamedExpression[arity])
2286 public override bool IsEmpty {
2292 public override bool Resolve (IMemberContext mc, bool allowUnbound)
2294 if (!allowUnbound) {
2295 mc.Module.Compiler.Report.Error (7003, loc, "Unbound generic name is not valid in this context");
2298 // Nothing to be resolved
2303 public class TypeParameters
2305 List<TypeParameter> names;
2306 TypeParameterSpec[] types;
2308 public TypeParameters ()
2310 names = new List<TypeParameter> ();
2313 public TypeParameters (int count)
2315 names = new List<TypeParameter> (count);
2326 public TypeParameterSpec[] Types {
2334 public void Add (TypeParameter tparam)
2339 public void Add (TypeParameters tparams)
2341 names.AddRange (tparams.names);
2344 public void Create (TypeSpec declaringType, int parentOffset, TypeContainer parent)
2346 types = new TypeParameterSpec[Count];
2347 for (int i = 0; i < types.Length; ++i) {
2350 tp.Create (declaringType, parent);
2352 types[i].DeclaredPosition = i + parentOffset;
2354 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2355 parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2360 public void Define (GenericTypeParameterBuilder[] builders)
2362 for (int i = 0; i < types.Length; ++i) {
2364 tp.Define (builders [types [i].DeclaredPosition]);
2368 public TypeParameter this[int index] {
2370 return names [index];
2373 names[index] = value;
2377 public TypeParameter Find (string name)
2379 foreach (var tp in names) {
2380 if (tp.Name == name)
2387 public string[] GetAllNames ()
2389 return names.Select (l => l.Name).ToArray ();
2392 public string GetSignatureForError ()
2394 StringBuilder sb = new StringBuilder ();
2395 for (int i = 0; i < Count; ++i) {
2399 var name = names[i];
2401 sb.Append (name.GetSignatureForError ());
2404 return sb.ToString ();
2408 public void CheckPartialConstraints (Method part)
2410 var partTypeParameters = part.CurrentTypeParameters;
2412 for (int i = 0; i < Count; i++) {
2413 var tp_a = names[i];
2414 var tp_b = partTypeParameters [i];
2415 if (tp_a.Constraints == null) {
2416 if (tp_b.Constraints == null)
2418 } else if (tp_b.Constraints != null && tp_a.Type.HasSameConstraintsDefinition (tp_b.Type)) {
2422 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition.Location, "");
2423 part.Compiler.Report.Error (761, part.Location,
2424 "Partial method declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2425 part.GetSignatureForError (), partTypeParameters[i].GetSignatureForError ());
2429 public void UpdateConstraints (TypeDefinition part)
2431 var partTypeParameters = part.MemberName.TypeParameters;
2433 for (int i = 0; i < Count; i++) {
2435 if (tp.AddPartialConstraints (part, partTypeParameters [i]))
2438 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition);
2439 part.Compiler.Report.Error (265, part.Location,
2440 "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2441 part.GetSignatureForError (), tp.GetSignatureForError ());
2445 public void VerifyClsCompliance ()
2447 foreach (var tp in names) {
2448 tp.VerifyClsCompliance ();
2454 // A type expression of generic type with type arguments
2456 class GenericTypeExpr : TypeExpr
2462 /// Instantiate the generic type `t' with the type arguments `args'.
2463 /// Use this constructor if you already know the fully resolved
2466 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2468 this.open_type = open_type;
2473 public override string GetSignatureForError ()
2475 return type.GetSignatureForError ();
2478 public override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments = false)
2480 if (eclass != ExprClass.Unresolved)
2483 if (!args.Resolve (mc, allowUnboundTypeArguments))
2486 TypeSpec[] atypes = args.Arguments;
2491 // Now bind the parameters
2493 var inflated = open_type.MakeGenericType (mc, atypes);
2495 eclass = ExprClass.Type;
2498 // The constraints can be checked only when full type hierarchy is known
2500 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2501 var constraints = inflated.Constraints;
2502 if (constraints != null) {
2503 var cc = new ConstraintChecker (mc);
2504 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2505 inflated.HasConstraintsChecked = true;
2513 public override bool Equals (object obj)
2515 GenericTypeExpr cobj = obj as GenericTypeExpr;
2519 if ((type == null) || (cobj.type == null))
2522 return type == cobj.type;
2525 public override int GetHashCode ()
2527 return base.GetHashCode ();
2532 // Generic type with unbound type arguments, used for typeof (G<,,>)
2534 class GenericOpenTypeExpr : TypeExpression
2536 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2537 : base (type.GetDefinition (), loc)
2542 struct ConstraintChecker
2545 bool recursive_checks;
2547 public ConstraintChecker (IMemberContext ctx)
2550 recursive_checks = false;
2554 // Checks the constraints of open generic type against type
2555 // arguments. This version is used for types which could not be
2556 // checked immediatelly during construction because the type
2557 // hierarchy was not yet fully setup (before Emit phase)
2559 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2562 // Check declaring type first if there is any
2564 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2567 while (type is ElementTypeSpec)
2568 type = ((ElementTypeSpec) type).Element;
2570 if (type.Arity == 0)
2573 var gtype = type as InflatedTypeSpec;
2577 var constraints = gtype.Constraints;
2578 if (constraints == null)
2581 if (gtype.HasConstraintsChecked)
2584 var cc = new ConstraintChecker (mc);
2585 cc.recursive_checks = true;
2587 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2588 gtype.HasConstraintsChecked = true;
2596 // Checks all type arguments againts type parameters constraints
2597 // NOTE: It can run in probing mode when `this.mc' is null
2599 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2604 for (int i = 0; i < tparams.Length; i++) {
2605 var targ = targs[i];
2606 if (!CheckConstraint (context, targ, tparams [i], loc))
2609 if (!recursive_checks)
2612 if (!Check (mc, targ, loc))
2619 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2622 // First, check the `class' and `struct' constraints.
2624 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2626 mc.Module.Compiler.Report.Error (452, loc,
2627 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2628 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2634 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2636 mc.Module.Compiler.Report.Error (453, loc,
2637 "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}'",
2638 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2647 // Check the class constraint
2649 if (tparam.HasTypeConstraint) {
2650 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2659 // Check the interfaces constraints
2661 if (tparam.InterfacesDefined != null) {
2662 foreach (TypeSpec iface in tparam.InterfacesDefined) {
2663 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2674 // Check the type parameter constraint
2676 if (tparam.TypeArguments != null) {
2677 foreach (var ta in tparam.TypeArguments) {
2678 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2689 // Finally, check the constructor constraint.
2691 if (!tparam.HasSpecialConstructor)
2694 if (!HasDefaultConstructor (atype)) {
2696 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2697 mc.Module.Compiler.Report.Error (310, loc,
2698 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2699 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2707 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2709 for (int i = 0; i < targs.Length; ++i) {
2710 var targ = targs [i];
2711 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2714 if (HasDynamicTypeArgument (targ.TypeArguments))
2721 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2726 if (atype.IsGenericParameter) {
2727 var tps = (TypeParameterSpec) atype;
2728 if (tps.HasDependencyOn (ttype))
2731 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2734 } else if (TypeSpec.IsValueType (atype)) {
2735 if (atype.IsNullableType) {
2737 // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2739 if (TypeSpec.IsBaseClass (atype, ttype, false))
2742 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2746 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2751 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2752 if (atype.IsGenericParameter) {
2753 mc.Module.Compiler.Report.Error (314, loc,
2754 "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}'",
2755 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2756 } else if (TypeSpec.IsValueType (atype)) {
2757 if (atype.IsNullableType) {
2758 if (ttype.IsInterface) {
2759 mc.Module.Compiler.Report.Error (313, loc,
2760 "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}'",
2761 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2763 mc.Module.Compiler.Report.Error (312, loc,
2764 "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}'",
2765 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2768 mc.Module.Compiler.Report.Error (315, loc,
2769 "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}'",
2770 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2773 mc.Module.Compiler.Report.Error (311, loc,
2774 "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}'",
2775 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2782 static bool HasDefaultConstructor (TypeSpec atype)
2784 var tp = atype as TypeParameterSpec;
2786 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2789 if (atype.IsStruct || atype.IsEnum)
2792 if (atype.IsAbstract)
2795 var tdef = atype.GetDefinition ();
2797 var found = MemberCache.FindMember (tdef,
2798 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2799 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2801 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2806 // Implements C# type inference
2811 // Tracks successful rate of type inference
2814 readonly Arguments arguments;
2815 readonly int arg_count;
2817 public TypeInference (Arguments arguments)
2819 this.arguments = arguments;
2820 if (arguments != null)
2821 arg_count = arguments.Count;
2824 public int InferenceScore {
2830 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2832 var method_generic_args = method.GenericDefinition.TypeParameters;
2833 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2834 if (!context.UnfixedVariableExists)
2835 return TypeSpec.EmptyTypes;
2837 AParametersCollection pd = method.Parameters;
2838 if (!InferInPhases (ec, context, pd))
2841 return context.InferredTypeArguments;
2845 // Implements method type arguments inference
2847 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2849 int params_arguments_start;
2850 if (methodParameters.HasParams) {
2851 params_arguments_start = methodParameters.Count - 1;
2853 params_arguments_start = arg_count;
2856 TypeSpec [] ptypes = methodParameters.Types;
2859 // The first inference phase
2861 TypeSpec method_parameter = null;
2862 for (int i = 0; i < arg_count; i++) {
2863 Argument a = arguments [i];
2867 if (i < params_arguments_start) {
2868 method_parameter = methodParameters.Types [i];
2869 } else if (i == params_arguments_start) {
2870 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2871 method_parameter = methodParameters.Types [params_arguments_start];
2873 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2875 ptypes = (TypeSpec[]) ptypes.Clone ();
2876 ptypes [i] = method_parameter;
2880 // When a lambda expression, an anonymous method
2881 // is used an explicit argument type inference takes a place
2883 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2885 if (am.ExplicitTypeInference (tic, method_parameter))
2891 score += tic.ExactInference (a.Type, method_parameter);
2895 if (a.Expr.Type == InternalType.NullLiteral)
2898 if (TypeSpec.IsValueType (method_parameter)) {
2899 score += tic.LowerBoundInference (a.Type, method_parameter);
2904 // Otherwise an output type inference is made
2906 score += tic.OutputTypeInference (ec, a.Expr, method_parameter);
2910 // Part of the second phase but because it happens only once
2911 // we don't need to call it in cycle
2913 bool fixed_any = false;
2914 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2917 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2920 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2922 bool fixed_any = false;
2923 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2926 // If no further unfixed type variables exist, type inference succeeds
2927 if (!tic.UnfixedVariableExists)
2930 if (!fixed_any && fixDependent)
2933 // For all arguments where the corresponding argument output types
2934 // contain unfixed type variables but the input types do not,
2935 // an output type inference is made
2936 for (int i = 0; i < arg_count; i++) {
2938 // Align params arguments
2939 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2941 if (!t_i.IsDelegate) {
2942 if (!t_i.IsExpressionTreeType)
2945 t_i = TypeManager.GetTypeArguments (t_i) [0];
2948 var mi = Delegate.GetInvokeMethod (t_i);
2949 TypeSpec rtype = mi.ReturnType;
2951 if (tic.IsReturnTypeNonDependent (mi, rtype)) {
2952 // It can be null for default arguments
2953 if (arguments[i] == null)
2956 score += tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2961 return DoSecondPhase (ec, tic, methodParameters, true);
2965 public class TypeInferenceContext
2967 protected enum BoundKind
2974 struct BoundInfo : IEquatable<BoundInfo>
2976 public readonly TypeSpec Type;
2977 public readonly BoundKind Kind;
2979 public BoundInfo (TypeSpec type, BoundKind kind)
2985 public override int GetHashCode ()
2987 return Type.GetHashCode ();
2990 public Expression GetTypeExpression ()
2992 return new TypeExpression (Type, Location.Null);
2995 #region IEquatable<BoundInfo> Members
2997 public bool Equals (BoundInfo other)
2999 return Type == other.Type && Kind == other.Kind;
3005 readonly TypeSpec[] tp_args;
3006 readonly TypeSpec[] fixed_types;
3007 readonly List<BoundInfo>[] bounds;
3009 // TODO MemberCache: Could it be TypeParameterSpec[] ??
3010 public TypeInferenceContext (TypeSpec[] typeArguments)
3012 if (typeArguments.Length == 0)
3013 throw new ArgumentException ("Empty generic arguments");
3015 fixed_types = new TypeSpec [typeArguments.Length];
3016 for (int i = 0; i < typeArguments.Length; ++i) {
3017 if (typeArguments [i].IsGenericParameter) {
3018 if (bounds == null) {
3019 bounds = new List<BoundInfo> [typeArguments.Length];
3020 tp_args = new TypeSpec [typeArguments.Length];
3022 tp_args [i] = typeArguments [i];
3024 fixed_types [i] = typeArguments [i];
3030 // Used together with AddCommonTypeBound fo implement
3031 // 7.4.2.13 Finding the best common type of a set of expressions
3033 public TypeInferenceContext ()
3035 fixed_types = new TypeSpec [1];
3036 tp_args = new TypeSpec [1];
3037 tp_args[0] = InternalType.Arglist; // it can be any internal type
3038 bounds = new List<BoundInfo> [1];
3041 public TypeSpec[] InferredTypeArguments {
3047 public void AddCommonTypeBound (TypeSpec type)
3049 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, false);
3052 public void AddCommonTypeBoundAsync (TypeSpec type)
3054 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, true);
3057 void AddToBounds (BoundInfo bound, int index, bool voidAllowed)
3060 // Some types cannot be used as type arguments
3062 if ((bound.Type.Kind == MemberKind.Void && !voidAllowed) || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
3063 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod || bound.Type == InternalType.VarOutType)
3066 var a = bounds [index];
3068 a = new List<BoundInfo> (2);
3074 if (a.Contains (bound))
3080 bool AllTypesAreFixed (TypeSpec[] types)
3082 foreach (TypeSpec t in types) {
3083 if (t.IsGenericParameter) {
3089 if (t.IsGeneric && !AllTypesAreFixed (t.TypeArguments))
3097 // 26.3.3.8 Exact Inference
3099 public int ExactInference (TypeSpec u, TypeSpec v)
3101 // If V is an array type
3106 var ac_u = (ArrayContainer) u;
3107 var ac_v = (ArrayContainer) v;
3108 if (ac_u.Rank != ac_v.Rank)
3111 return ExactInference (ac_u.Element, ac_v.Element);
3115 // If V is constructed type and U is constructed type or dynamic
3117 if (TypeManager.IsGenericType (v)) {
3118 if (u.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3120 var ga_v = v.TypeArguments;
3123 for (int i = 0; i < ga_v.Length; ++i)
3124 score += ExactInference (u, ga_v [i]);
3126 return System.Math.Min (1, score);
3129 if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
3132 var ga_u = u.TypeArguments;
3133 var ga_v = v.TypeArguments;
3135 if (u.TypeArguments.Length != u.TypeArguments.Length)
3139 for (int i = 0; i < ga_v.Length; ++i)
3140 score += ExactInference (ga_u [i], ga_v [i]);
3142 return System.Math.Min (1, score);
3146 // If V is one of the unfixed type arguments
3147 int pos = IsUnfixed (v);
3151 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos, false);
3155 public bool FixAllTypes (ResolveContext ec)
3157 for (int i = 0; i < tp_args.Length; ++i) {
3158 if (!FixType (ec, i))
3165 // All unfixed type variables Xi are fixed for which all of the following hold:
3166 // a, There is at least one type variable Xj that depends on Xi
3167 // b, Xi has a non-empty set of bounds
3169 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
3171 for (int i = 0; i < tp_args.Length; ++i) {
3172 if (fixed_types[i] != null)
3175 if (bounds[i] == null)
3178 if (!FixType (ec, i))
3188 // All unfixed type variables Xi which depend on no Xj are fixed
3190 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
3192 var types_to_fix = new List<TypeSpec> (tp_args);
3193 for (int i = 0; i < methodParameters.Length; ++i) {
3194 TypeSpec t = methodParameters[i];
3196 if (!t.IsDelegate) {
3197 if (!t.IsExpressionTreeType)
3200 t = TypeManager.GetTypeArguments (t) [0];
3203 if (t.IsGenericParameter)
3206 var invoke = Delegate.GetInvokeMethod (t);
3207 TypeSpec rtype = invoke.ReturnType;
3208 while (rtype.IsArray)
3209 rtype = ((ArrayContainer) rtype).Element;
3211 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3214 // Remove dependent types, they cannot be fixed yet
3215 RemoveDependentTypes (types_to_fix, rtype);
3218 foreach (TypeSpec t in types_to_fix) {
3222 int idx = IsUnfixed (t);
3223 if (idx >= 0 && !FixType (ec, idx)) {
3228 fixed_any = types_to_fix.Count > 0;
3235 public bool FixType (ResolveContext ec, int i)
3237 // It's already fixed
3238 if (fixed_types[i] != null)
3239 throw new InternalErrorException ("Type argument has been already fixed");
3241 var candidates = bounds [i];
3242 if (candidates == null)
3245 if (candidates.Count == 1) {
3246 TypeSpec t = candidates[0].Type;
3247 if (t == InternalType.NullLiteral)
3250 fixed_types [i] = t;
3255 // The set of candidate types Uj starts out as the set of
3256 // all types in the set of bounds for Xi
3258 var applicable = new bool [candidates.Count];
3259 for (int ci = 0; ci < applicable.Length; ++ci)
3260 applicable [ci] = true;
3262 for (int ci = 0; ci < applicable.Length; ++ci) {
3263 var bound = candidates [ci];
3266 switch (bound.Kind) {
3267 case BoundKind.Exact:
3268 for (; cii != applicable.Length; ++cii) {
3272 if (!applicable[cii])
3276 // For each exact bound U of Xi all types Uj which are not identical
3277 // to U are removed from the candidate set
3279 if (candidates [cii].Type != bound.Type)
3280 applicable[cii] = false;
3284 case BoundKind.Lower:
3285 for (; cii != applicable.Length; ++cii) {
3289 if (!applicable[cii])
3293 // For each lower bound U of Xi all types Uj to which there is not an implicit conversion
3294 // from U are removed from the candidate set
3296 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), candidates [cii].Type)) {
3297 applicable[cii] = false;
3303 case BoundKind.Upper:
3304 for (; cii != applicable.Length; ++cii) {
3308 if (!applicable[cii])
3312 // For each upper bound U of Xi all types Uj from which there is not an implicit conversion
3313 // to U are removed from the candidate set
3315 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3316 applicable[cii] = false;
3323 TypeSpec best_candidate = null;
3324 for (int ci = 0; ci < applicable.Length; ++ci) {
3325 if (!applicable[ci])
3328 var bound = candidates [ci];
3329 if (bound.Type == best_candidate)
3333 for (; cii < applicable.Length; ++cii) {
3337 if (!applicable[cii])
3340 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3344 if (cii != applicable.Length)
3348 // We already have the best candidate, break if it's different (non-unique)
3350 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3352 if (best_candidate != null) {
3354 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3357 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3361 best_candidate = bound.Type;
3364 if (best_candidate == null)
3367 fixed_types[i] = best_candidate;
3371 public bool HasBounds (int pos)
3373 return bounds[pos] != null;
3377 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3378 // null when type parameter has not been fixed
3380 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3382 var tp = parameter as TypeParameterSpec;
3385 // Type inference works on generic arguments (MVAR) only
3387 if (!tp.IsMethodOwned)
3391 // Ensure the type parameter belongs to same container
3393 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3394 return fixed_types[tp.DeclaredPosition] ?? parameter;
3399 var gt = parameter as InflatedTypeSpec;
3401 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3402 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3403 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3404 if (inflated == null)
3407 inflated_targs[ii] = inflated;
3410 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3413 var ac = parameter as ArrayContainer;
3415 var inflated = InflateGenericArgument (context, ac.Element);
3416 if (inflated != ac.Element)
3417 return ArrayContainer.MakeType (context.Module, inflated);
3424 // Tests whether all delegate input arguments are fixed and generic output type
3425 // requires output type inference
3427 public bool IsReturnTypeNonDependent (MethodSpec invoke, TypeSpec returnType)
3429 AParametersCollection d_parameters = invoke.Parameters;
3431 if (d_parameters.IsEmpty)
3434 while (returnType.IsArray)
3435 returnType = ((ArrayContainer) returnType).Element;
3437 if (returnType.IsGenericParameter) {
3438 if (IsFixed (returnType))
3440 } else if (TypeManager.IsGenericType (returnType)) {
3441 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3443 // At least one unfixed return type has to exist
3444 if (AllTypesAreFixed (g_args))
3450 // All generic input arguments have to be fixed
3451 return AllTypesAreFixed (d_parameters.Types);
3454 bool IsFixed (TypeSpec type)
3456 return IsUnfixed (type) == -1;
3459 int IsUnfixed (TypeSpec type)
3461 if (!type.IsGenericParameter)
3464 for (int i = 0; i < tp_args.Length; ++i) {
3465 if (tp_args[i] == type) {
3466 if (fixed_types[i] != null)
3477 // 26.3.3.9 Lower-bound Inference
3479 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3481 return LowerBoundInference (u, v, false);
3485 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3487 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3489 // If V is one of the unfixed type arguments
3490 int pos = IsUnfixed (v);
3492 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos, false);
3496 // If U is an array type
3497 var u_ac = u as ArrayContainer;
3499 var v_ac = v as ArrayContainer;
3501 if (u_ac.Rank != v_ac.Rank)
3504 if (TypeSpec.IsValueType (u_ac.Element))
3505 return ExactInference (u_ac.Element, v_ac.Element);
3507 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3510 if (u_ac.Rank != 1 || !v.IsArrayGenericInterface)
3513 var v_i = TypeManager.GetTypeArguments (v) [0];
3514 if (TypeSpec.IsValueType (u_ac.Element))
3515 return ExactInference (u_ac.Element, v_i);
3517 return LowerBoundInference (u_ac.Element, v_i);
3520 if (v.IsGenericOrParentIsGeneric) {
3522 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3523 // such that U is identical to, inherits from (directly or indirectly),
3524 // or implements (directly or indirectly) C<U1..Uk>
3526 var u_candidates = new List<TypeSpec> ();
3527 var open_v = v.MemberDefinition;
3529 for (TypeSpec t = u; t != null; t = t.BaseType) {
3530 if (open_v == t.MemberDefinition)
3531 u_candidates.Add (t);
3534 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3535 // that would complicate the process a lot, instead I treat them as dynamic
3537 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3538 u_candidates.Add (t);
3541 if (u.Interfaces != null) {
3542 foreach (var iface in u.Interfaces) {
3543 if (open_v == iface.MemberDefinition)
3544 u_candidates.Add (iface);
3548 TypeSpec[] unique_candidate_targs = null;
3549 var ga_v = TypeSpec.GetAllTypeArguments (v);
3550 foreach (TypeSpec u_candidate in u_candidates) {
3552 // The unique set of types U1..Uk means that if we have an interface I<T>,
3553 // class U : I<int>, I<long> then no type inference is made when inferring
3554 // type I<T> by applying type U because T could be int or long
3556 if (unique_candidate_targs != null) {
3557 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3558 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3559 unique_candidate_targs = second_unique_candidate_targs;
3564 // Break when candidate arguments are ambiguous
3570 // A candidate is dynamic type expression, to simplify things use dynamic
3571 // for all type parameter of this type. For methods like this one
3573 // void M<T, U> (IList<T>, IList<U[]>)
3575 // dynamic becomes both T and U when the arguments are of dynamic type
3577 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3578 unique_candidate_targs = new TypeSpec[ga_v.Length];
3579 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3580 unique_candidate_targs[i] = u_candidate;
3582 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3586 if (unique_candidate_targs != null) {
3589 TypeParameterSpec[] tps = null;
3591 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3593 while (v.Arity == 0)
3594 v = v.DeclaringType;
3596 tps = v.MemberDefinition.TypeParameters;
3597 tp_index = tps.Length - 1;
3600 Variance variance = tps [tp_index--].Variance;
3602 TypeSpec u_i = unique_candidate_targs [i];
3603 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3604 if (ExactInference (u_i, ga_v [i]) == 0)
3607 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3608 (variance == Variance.Covariant && inversed);
3610 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3623 // 26.3.3.6 Output Type Inference
3625 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3627 // If e is a lambda or anonymous method with inferred return type
3628 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3630 TypeSpec rt = ame.InferReturnType (ec, this, t);
3631 var invoke = Delegate.GetInvokeMethod (t);
3634 AParametersCollection pd = invoke.Parameters;
3635 return ame.Parameters.Count == pd.Count ? 1 : 0;
3638 TypeSpec rtype = invoke.ReturnType;
3639 return LowerBoundInference (rt, rtype) + 1;
3643 // if E is a method group and T is a delegate type or expression tree type
3644 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3645 // resolution of E with the types T1..Tk yields a single method with return type U,
3646 // then a lower-bound inference is made from U for Tb.
3648 if (e is MethodGroupExpr) {
3649 if (!t.IsDelegate) {
3650 if (!t.IsExpressionTreeType)
3653 t = TypeManager.GetTypeArguments (t)[0];
3656 var invoke = Delegate.GetInvokeMethod (t);
3657 TypeSpec rtype = invoke.ReturnType;
3659 if (!IsReturnTypeNonDependent (invoke, rtype))
3662 // LAMESPEC: Standard does not specify that all methodgroup arguments
3663 // has to be fixed but it does not specify how to do recursive type inference
3664 // either. We choose the simple option and infer return type only
3665 // if all delegate generic arguments are fixed.
3666 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3667 for (int i = 0; i < param_types.Length; ++i) {
3668 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3669 if (inflated == null)
3672 param_types[i] = inflated;
3675 MethodGroupExpr mg = (MethodGroupExpr) e;
3676 Arguments args = DelegateCreation.CreateDelegateMethodArguments (ec, invoke.Parameters, param_types, e.Location);
3677 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3681 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3685 // if e is an expression with type U, then
3686 // a lower-bound inference is made from U for T
3688 return LowerBoundInference (e.Type, t) * 2;
3691 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3693 int idx = IsUnfixed (returnType);
3699 if (TypeManager.IsGenericType (returnType)) {
3700 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3701 RemoveDependentTypes (types, t);
3706 public bool UnfixedVariableExists {
3708 foreach (TypeSpec ut in fixed_types) {