2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
16 using System.Collections.Generic;
21 using MetaType = IKVM.Reflection.Type;
22 using IKVM.Reflection;
23 using IKVM.Reflection.Emit;
25 using MetaType = System.Type;
26 using System.Reflection;
27 using System.Reflection.Emit;
30 namespace Mono.CSharp {
34 // Don't add or modify internal values, they are used as -/+ calculation signs
42 public enum SpecialConstraint
50 public class SpecialContraintExpr : FullNamedExpression
52 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
55 this.Constraint = constraint;
58 public SpecialConstraint Constraint { get; private set; }
60 protected override Expression DoResolve (ResolveContext rc)
62 throw new NotImplementedException ();
65 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
67 throw new NotImplementedException ();
72 // A set of parsed constraints for a type parameter
74 public class Constraints
76 SimpleMemberName tparam;
77 List<FullNamedExpression> constraints;
82 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
85 this.constraints = constraints;
91 public List<FullNamedExpression> TypeExpressions {
97 public Location Location {
103 public SimpleMemberName TypeParameter {
111 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
113 if (spec.HasSpecialClass && bb.IsStruct) {
114 context.Module.Compiler.Report.Error (455, loc,
115 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
116 spec.Name, "class", bb.GetSignatureForError ());
121 return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
124 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
129 if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
132 Error_ConflictingConstraints (context, spec, ba, bb, loc);
136 public static void Error_ConflictingConstraints (IMemberContext context, TypeParameterSpec tp, TypeSpec ba, TypeSpec bb, Location loc)
138 context.Module.Compiler.Report.Error (455, loc,
139 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
140 tp.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
143 public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
145 foreach (var c in constraints) {
154 ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
155 if (obsolete_attr != null)
156 AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
159 ConstraintChecker.Check (context, t, c.Location);
164 // Resolve the constraints types with only possible early checks, return
165 // value `false' is reserved for recursive failure
167 public bool Resolve (IMemberContext context, TypeParameter tp)
177 List<TypeParameterSpec> tparam_types = null;
178 bool iface_found = false;
180 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
182 for (int i = 0; i < constraints.Count; ++i) {
183 var constraint = constraints[i];
185 if (constraint is SpecialContraintExpr) {
186 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
187 if (spec.HasSpecialStruct)
188 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
190 // Set to null as it does not have a type
191 constraints[i] = null;
195 var type = constraint.ResolveAsType (context);
199 if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
200 context.Module.Compiler.Report.Error (1968, constraint.Location,
201 "A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
205 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
206 context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
207 context.Module.Compiler.Report.Error (703, loc,
208 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
209 type.GetSignatureForError (), context.GetSignatureForError ());
212 if (type.IsInterface) {
213 if (!spec.AddInterface (type)) {
214 context.Module.Compiler.Report.Error (405, constraint.Location,
215 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
223 var constraint_tp = type as TypeParameterSpec;
224 if (constraint_tp != null) {
225 if (tparam_types == null) {
226 tparam_types = new List<TypeParameterSpec> (2);
227 } else if (tparam_types.Contains (constraint_tp)) {
228 context.Module.Compiler.Report.Error (405, constraint.Location,
229 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
234 // Checks whether each generic method parameter constraint type
235 // is valid with respect to T
237 if (tp.IsMethodTypeParameter) {
238 TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
241 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
242 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
243 context.Module.Compiler.Report.Error (454, constraint.Location,
244 "Circular constraint dependency involving `{0}' and `{1}'",
245 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
250 // Checks whether there are no conflicts between type parameter constraints
256 // A and B are not convertible and only 1 class constraint is allowed
258 if (constraint_tp.HasTypeConstraint) {
259 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
260 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
263 for (int ii = 0; ii < tparam_types.Count; ++ii) {
264 if (!tparam_types[ii].HasTypeConstraint)
267 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
273 if (constraint_tp.HasSpecialStruct) {
274 context.Module.Compiler.Report.Error (456, constraint.Location,
275 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
276 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
280 tparam_types.Add (constraint_tp);
284 if (iface_found || spec.HasTypeConstraint) {
285 context.Module.Compiler.Report.Error (406, constraint.Location,
286 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
287 type.GetSignatureForError ());
290 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
291 context.Module.Compiler.Report.Error (450, constraint.Location,
292 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
293 type.GetSignatureForError ());
296 switch (type.BuiltinType) {
297 case BuiltinTypeSpec.Type.Array:
298 case BuiltinTypeSpec.Type.Delegate:
299 case BuiltinTypeSpec.Type.MulticastDelegate:
300 case BuiltinTypeSpec.Type.Enum:
301 case BuiltinTypeSpec.Type.ValueType:
302 case BuiltinTypeSpec.Type.Object:
303 context.Module.Compiler.Report.Error (702, constraint.Location,
304 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
306 case BuiltinTypeSpec.Type.Dynamic:
307 context.Module.Compiler.Report.Error (1967, constraint.Location,
308 "A constraint cannot be the dynamic type");
312 if (type.IsSealed || !type.IsClass) {
313 context.Module.Compiler.Report.Error (701, loc,
314 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
315 TypeManager.CSharpName (type));
320 context.Module.Compiler.Report.Error (717, constraint.Location,
321 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
322 type.GetSignatureForError ());
325 spec.BaseType = type;
328 if (tparam_types != null)
329 spec.TypeArguments = tparam_types.ToArray ();
336 public void VerifyClsCompliance (Report report)
338 foreach (var c in constraints)
343 if (!c.Type.IsCLSCompliant ()) {
344 report.SymbolRelatedToPreviousError (c.Type);
345 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
346 c.Type.GetSignatureForError ());
353 // A type parameter for a generic type or generic method definition
355 public class TypeParameter : MemberCore, ITypeDefinition
357 static readonly string[] attribute_target = new string [] { "type parameter" };
359 Constraints constraints;
360 GenericTypeParameterBuilder builder;
361 TypeParameterSpec spec;
363 public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
364 : base (null, name, attrs)
366 this.constraints = constraints;
367 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
373 public TypeParameter (MemberName name, Attributes attrs, Variance variance)
374 : base (null, name, attrs)
376 this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, variance, null);
379 public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
380 : base (null, name, attrs)
382 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
383 BaseType = spec.BaseType,
384 InterfacesDefined = spec.InterfacesDefined,
385 TypeArguments = spec.TypeArguments
391 public override AttributeTargets AttributeTargets {
393 return AttributeTargets.GenericParameter;
397 public Constraints Constraints {
406 public IAssemblyDefinition DeclaringAssembly {
408 return Module.DeclaringAssembly;
412 public override string DocCommentHeader {
414 throw new InvalidOperationException (
415 "Unexpected attempt to get doc comment from " + this.GetType ());
419 bool ITypeDefinition.IsPartial {
425 public bool IsMethodTypeParameter {
427 return spec.IsMethodOwned;
433 return MemberName.Name;
437 public string Namespace {
443 public TypeParameterSpec Type {
449 public int TypeParametersCount {
455 public TypeParameterSpec[] TypeParameters {
461 public override string[] ValidAttributeTargets {
463 return attribute_target;
467 public Variance Variance {
469 return spec.Variance;
476 // This is called for each part of a partial generic type definition.
478 // If partial type parameters constraints are not null and we don't
479 // already have constraints they become our constraints. If we already
480 // have constraints, we must check that they're the same.
482 public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
485 throw new InvalidOperationException ();
487 var new_constraints = tp.constraints;
488 if (new_constraints == null)
491 // TODO: could create spec only
492 //tp.Define (null, -1, part.Definition);
493 tp.spec.DeclaringType = part.Definition;
494 if (!tp.ResolveConstraints (part))
497 if (constraints != null)
498 return spec.HasSameConstraintsDefinition (tp.Type);
500 // Copy constraint from resolved part to partial container
501 spec.SpecialConstraint = tp.spec.SpecialConstraint;
502 spec.Interfaces = tp.spec.Interfaces;
503 spec.TypeArguments = tp.spec.TypeArguments;
504 spec.BaseType = tp.spec.BaseType;
509 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
511 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
514 public void CheckGenericConstraints (bool obsoleteCheck)
516 if (constraints != null)
517 constraints.CheckGenericConstraints (this, obsoleteCheck);
520 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
522 return new TypeParameter (spec, declaringSpec, MemberName, null);
525 public override bool Define ()
531 // This is the first method which is called during the resolving
532 // process; we're called immediately after creating the type parameters
533 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
536 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType, TypeContainer parent)
539 throw new InternalErrorException ();
541 // Needed to get compiler reference
542 this.Parent = parent;
544 spec.DeclaringType = declaringType;
545 spec.SetMetaInfo (type);
548 public void EmitConstraints (GenericTypeParameterBuilder builder)
550 var attr = GenericParameterAttributes.None;
551 if (spec.Variance == Variance.Contravariant)
552 attr |= GenericParameterAttributes.Contravariant;
553 else if (spec.Variance == Variance.Covariant)
554 attr |= GenericParameterAttributes.Covariant;
556 if (spec.HasSpecialClass)
557 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
558 else if (spec.HasSpecialStruct)
559 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
561 if (spec.HasSpecialConstructor)
562 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
564 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
565 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
567 if (spec.InterfacesDefined != null)
568 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
570 if (spec.TypeArguments != null)
571 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
573 builder.SetGenericParameterAttributes (attr);
576 public override void Emit ()
578 EmitConstraints (builder);
580 if (OptAttributes != null)
581 OptAttributes.Emit ();
586 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
588 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
589 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
590 string gtype_variance;
592 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
593 case Variance.Covariant: gtype_variance = "covariantly"; break;
594 default: gtype_variance = "invariantly"; break;
597 Delegate d = mc as Delegate;
598 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
600 Report.Error (1961, Location,
601 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
602 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
605 public TypeSpec GetAttributeCoClass ()
610 public string GetAttributeDefaultMember ()
612 throw new NotSupportedException ();
615 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
617 throw new NotSupportedException ();
620 public override string GetSignatureForDocumentation ()
622 throw new NotImplementedException ();
625 public override string GetSignatureForError ()
627 return MemberName.Name;
630 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
632 return spec.MemberDefinition.DeclaringAssembly == assembly;
635 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
637 throw new NotSupportedException ("Not supported for compiled definition");
641 // Resolves all type parameter constraints
643 public bool ResolveConstraints (IMemberContext context)
645 if (constraints != null)
646 return constraints.Resolve (context, this);
648 if (spec.BaseType == null)
649 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
654 public override bool IsClsComplianceRequired ()
659 public new void VerifyClsCompliance ()
661 if (constraints != null)
662 constraints.VerifyClsCompliance (Report);
665 public void WarningParentNameConflict (TypeParameter conflict)
667 conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
668 conflict.Report.Warning (693, 3, Location,
669 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
670 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
674 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
675 public class TypeParameterSpec : TypeSpec
677 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
680 SpecialConstraint spec;
683 TypeSpec[] ifaces_defined;
686 // Creates type owned type parameter
688 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
689 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
691 this.variance = variance;
693 state &= ~StateFlags.Obsolete_Undetected;
698 // Creates method owned type parameter
700 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
701 : this (null, index, definition, spec, variance, info)
707 public int DeclaredPosition {
716 public bool HasSpecialConstructor {
718 return (spec & SpecialConstraint.Constructor) != 0;
722 public bool HasSpecialClass {
724 return (spec & SpecialConstraint.Class) != 0;
728 public bool HasSpecialStruct {
730 return (spec & SpecialConstraint.Struct) != 0;
734 public bool HasAnyTypeConstraint {
736 return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
740 public bool HasTypeConstraint {
742 var bt = BaseType.BuiltinType;
743 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
747 public override IList<TypeSpec> Interfaces {
749 if ((state & StateFlags.InterfacesExpanded) == 0) {
750 if (ifaces != null) {
751 for (int i = 0; i < ifaces.Count; ++i ) {
752 var iface_type = ifaces[i];
753 if (iface_type.Interfaces != null) {
754 if (ifaces_defined == null)
755 ifaces_defined = ifaces.ToArray ();
757 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
758 var ii_iface_type = iface_type.Interfaces [ii];
760 AddInterface (ii_iface_type);
766 if (ifaces_defined == null)
767 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
769 state |= StateFlags.InterfacesExpanded;
777 // Unexpanded interfaces list
779 public TypeSpec[] InterfacesDefined {
781 if (ifaces_defined == null) {
785 ifaces_defined = ifaces.ToArray ();
788 return ifaces_defined.Length == 0 ? null : ifaces_defined;
791 ifaces_defined = value;
792 if (value != null && value.Length != 0)
797 public bool IsConstrained {
799 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
804 // Returns whether the type parameter is known to be a reference type
806 public new bool IsReferenceType {
808 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
809 return (spec & SpecialConstraint.Class) != 0;
812 // Full check is needed (see IsValueType for details)
814 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
818 foreach (var ta in targs) {
820 // Secondary special constraints are ignored (I am not sure why)
822 var tp = ta as TypeParameterSpec;
823 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
826 if (TypeSpec.IsReferenceType (ta))
836 // Returns whether the type parameter is known to be a value type
838 public new bool IsValueType {
841 // Even if structs/enums cannot be used directly as constraints
842 // they can apear as constraint type when inheriting base constraint
843 // which has dependant type parameter constraint which has been
844 // inflated using value type
846 // class A : B<int> { override void Foo<U> () {} }
847 // class B<T> { virtual void Foo<U> () where U : T {} }
849 if (HasSpecialStruct)
853 foreach (var ta in targs) {
854 if (TypeSpec.IsValueType (ta))
863 public override string Name {
865 return definition.Name;
869 public bool IsMethodOwned {
871 return DeclaringType == null;
875 public SpecialConstraint SpecialConstraint {
885 // Types used to inflate the generic type
887 public new TypeSpec[] TypeArguments {
896 public Variance Variance {
904 public string DisplayDebugInfo ()
906 var s = GetSignatureForError ();
907 return IsMethodOwned ? s + "!!" : s + "!";
911 // Finds effective base class. The effective base class is always a class-type
913 public TypeSpec GetEffectiveBase ()
915 if (HasSpecialStruct)
919 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
921 if (BaseType != null && targs == null) {
923 // 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.
925 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
927 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
928 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
930 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
934 if (HasTypeConstraint) {
935 Array.Resize (ref types, types.Length + 1);
937 for (int i = 0; i < types.Length - 1; ++i) {
938 types[i] = types[i].BaseType;
941 types[types.Length - 1] = BaseType;
943 types = types.Select (l => l.BaseType).ToArray ();
947 return Convert.FindMostEncompassedType (types);
952 public override string GetSignatureForDocumentation ()
954 var prefix = IsMethodOwned ? "``" : "`";
955 return prefix + DeclaredPosition;
958 public override string GetSignatureForError ()
964 // Constraints have to match by definition but not position, used by
965 // partial classes or methods
967 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
969 if (spec != other.spec)
972 if (BaseType != other.BaseType)
975 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
978 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
985 // Constraints have to match by using same set of types, used by
986 // implicit interface implementation
988 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
990 if (spec != other.spec)
994 // It can be same base type or inflated type parameter
996 // interface I<T> { void Foo<U> where U : T; }
997 // class A : I<int> { void Foo<X> where X : int {} }
1000 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
1001 if (other.targs == null)
1005 foreach (var otarg in other.targs) {
1006 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1016 // Check interfaces implementation -> definition
1017 if (InterfacesDefined != null) {
1019 // Iterate over inflated interfaces
1021 foreach (var iface in Interfaces) {
1023 if (other.InterfacesDefined != null) {
1024 foreach (var oiface in other.Interfaces) {
1025 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1035 if (other.targs != null) {
1036 foreach (var otarg in other.targs) {
1037 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1049 // Check interfaces implementation <- definition
1050 if (other.InterfacesDefined != null) {
1051 if (InterfacesDefined == null)
1055 // Iterate over inflated interfaces
1057 foreach (var oiface in other.Interfaces) {
1059 foreach (var iface in Interfaces) {
1060 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1071 // Check type parameters implementation -> definition
1072 if (targs != null) {
1073 if (other.targs == null)
1076 foreach (var targ in targs) {
1078 foreach (var otarg in other.targs) {
1079 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1090 // Check type parameters implementation <- definition
1091 if (other.targs != null) {
1092 foreach (var otarg in other.targs) {
1093 // Ignore inflated type arguments, were checked above
1094 if (!otarg.IsGenericParameter)
1101 foreach (var targ in targs) {
1102 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1116 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1118 return InflateConstraints (tparams, l => l, inflator);
1121 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1123 TypeParameterSpec[] constraints = null;
1124 TypeParameterInflator? inflator = null;
1126 for (int i = 0; i < tparams.Length; ++i) {
1127 var tp = tparams[i];
1128 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1129 if (constraints == null) {
1130 constraints = new TypeParameterSpec[tparams.Length];
1131 Array.Copy (tparams, constraints, constraints.Length);
1135 // Using a factory to avoid possibly expensive inflator build up
1137 if (inflator == null)
1138 inflator = inflatorFactory (arg);
1140 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1144 if (constraints == null)
1145 constraints = tparams;
1150 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1152 tps.BaseType = inflator.Inflate (BaseType);
1153 if (ifaces != null) {
1154 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1155 for (int i = 0; i < ifaces.Count; ++i)
1156 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1159 if (targs != null) {
1160 tps.targs = new TypeSpec[targs.Length];
1161 for (int i = 0; i < targs.Length; ++i)
1162 tps.targs[i] = inflator.Inflate (targs[i]);
1166 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1168 var tps = (TypeParameterSpec) MemberwiseClone ();
1169 InflateConstraints (inflator, tps);
1174 // Populates type parameter members using type parameter constraints
1175 // The trick here is to be called late enough but not too late to
1176 // populate member cache with all members from other types
1178 protected override void InitializeMemberCache (bool onlyTypes)
1180 cache = new MemberCache ();
1183 // For a type parameter the membercache is the union of the sets of members of the types
1184 // specified as a primary constraint or secondary constraint
1186 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1187 cache.AddBaseType (BaseType);
1189 if (ifaces != null) {
1190 foreach (var iface_type in Interfaces) {
1191 cache.AddInterface (iface_type);
1195 if (targs != null) {
1196 foreach (var ta in targs) {
1197 var b_type = ta.BaseType;
1198 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1199 cache.AddBaseType (b_type);
1201 if (ta.Interfaces != null) {
1202 foreach (var iface_type in ta.Interfaces) {
1203 cache.AddInterface (iface_type);
1210 public bool IsConvertibleToInterface (TypeSpec iface)
1212 if (Interfaces != null) {
1213 foreach (var t in Interfaces) {
1219 if (TypeArguments != null) {
1220 foreach (var t in TypeArguments) {
1221 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1229 public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
1231 var tps = md.TypeParameters;
1232 for (int i = 0; i < md.TypeParametersCount; ++i) {
1233 if (tps[i].HasAnyTypeConstraint) {
1241 public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
1243 var tps = md.TypeParameters;
1244 for (int i = 0; i < md.TypeParametersCount; ++i) {
1245 if (tps[i].IsConstrained) {
1253 public bool HasDependencyOn (TypeSpec type)
1255 if (TypeArguments != null) {
1256 foreach (var targ in TypeArguments) {
1257 if (TypeSpecComparer.Override.IsEqual (targ, type))
1260 var tps = targ as TypeParameterSpec;
1261 if (tps != null && tps.HasDependencyOn (type))
1269 public override TypeSpec Mutate (TypeParameterMutator mutator)
1271 return mutator.Mutate (this);
1275 public struct TypeParameterInflator
1277 readonly TypeSpec type;
1278 readonly TypeParameterSpec[] tparams;
1279 readonly TypeSpec[] targs;
1280 readonly IModuleContext context;
1282 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1283 : this (nested.context, type, nested.tparams, nested.targs)
1287 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1289 if (tparams.Length != targs.Length)
1290 throw new ArgumentException ("Invalid arguments");
1292 this.context = context;
1293 this.tparams = tparams;
1300 public IModuleContext Context {
1306 public TypeSpec TypeInstance {
1313 // Type parameters to inflate
1315 public TypeParameterSpec[] TypeParameters {
1323 public TypeSpec Inflate (TypeSpec type)
1325 var tp = type as TypeParameterSpec;
1327 return Inflate (tp);
1329 var ac = type as ArrayContainer;
1331 var et = Inflate (ac.Element);
1332 if (et != ac.Element)
1333 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1339 // When inflating a nested type, inflate its parent first
1340 // in case it's using same type parameters (was inflated within the type)
1344 if (type.IsNested) {
1345 var parent = Inflate (type.DeclaringType);
1348 // Keep the inflated type arguments
1350 targs = type.TypeArguments;
1353 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1354 // because the import cache helps us to catch it. However, that means we have to look at
1355 // type definition to get type argument (they are in fact type parameter in this case)
1357 if (targs.Length == 0 && type.Arity > 0)
1358 targs = type.MemberDefinition.TypeParameters;
1361 // Parent was inflated, find the same type on inflated type
1362 // to use same cache for nested types on same generic parent
1364 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1367 // Handle the tricky case where parent shares local type arguments
1368 // which means inflating inflated type
1371 // public static Nested<T> Foo () { return null; }
1373 // public class Nested<U> {}
1376 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1378 if (targs.Length > 0) {
1379 var inflated_targs = new TypeSpec[targs.Length];
1380 for (; i < targs.Length; ++i)
1381 inflated_targs[i] = Inflate (targs[i]);
1383 type = type.MakeGenericType (context, inflated_targs);
1389 // Nothing to do for non-generic type
1390 if (type.Arity == 0)
1393 targs = new TypeSpec[type.Arity];
1396 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1398 if (type is InflatedTypeSpec) {
1399 for (; i < targs.Length; ++i)
1400 targs[i] = Inflate (type.TypeArguments[i]);
1402 type = type.GetDefinition ();
1405 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1407 var args = type.MemberDefinition.TypeParameters;
1408 foreach (var ds_tp in args)
1409 targs[i++] = Inflate (ds_tp);
1412 return type.MakeGenericType (context, targs);
1415 public TypeSpec Inflate (TypeParameterSpec tp)
1417 for (int i = 0; i < tparams.Length; ++i)
1418 if (tparams [i] == tp)
1421 // This can happen when inflating nested types
1422 // without type arguments specified
1428 // Before emitting any code we have to change all MVAR references to VAR
1429 // when the method is of generic type and has hoisted variables
1431 public class TypeParameterMutator
1433 readonly TypeParameters mvar;
1434 readonly TypeParameters var;
1435 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1437 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1439 if (mvar.Count != var.Count)
1440 throw new ArgumentException ();
1448 public TypeParameters MethodTypeParameters {
1456 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1458 if (type is InflatedTypeSpec) {
1459 if (type.DeclaringType == null)
1460 return type.GetDefinition ();
1462 var parent = GetMemberDeclaringType (type.DeclaringType);
1463 type = MemberCache.GetMember<TypeSpec> (parent, type);
1469 public TypeSpec Mutate (TypeSpec ts)
1472 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1475 value = ts.Mutate (this);
1476 if (mutated_typespec == null)
1477 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1479 mutated_typespec.Add (ts, value);
1483 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1485 for (int i = 0; i < mvar.Count; ++i) {
1486 if (mvar[i].Type == tp)
1493 public TypeSpec[] Mutate (TypeSpec[] targs)
1495 TypeSpec[] mutated = new TypeSpec[targs.Length];
1496 bool changed = false;
1497 for (int i = 0; i < targs.Length; ++i) {
1498 mutated[i] = Mutate (targs[i]);
1499 changed |= targs[i] != mutated[i];
1502 return changed ? mutated : targs;
1507 /// A TypeExpr which already resolved to a type parameter.
1509 public class TypeParameterExpr : TypeExpression
1511 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1512 : base (type_parameter.Type, loc)
1514 this.eclass = ExprClass.TypeParameter;
1518 public class InflatedTypeSpec : TypeSpec
1521 TypeParameterSpec[] constraints;
1522 readonly TypeSpec open_type;
1523 readonly IModuleContext context;
1525 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1526 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1529 throw new ArgumentNullException ("targs");
1531 this.state &= ~SharedStateFlags;
1532 this.state |= (openType.state & SharedStateFlags);
1534 this.context = context;
1535 this.open_type = openType;
1538 foreach (var arg in targs) {
1539 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1540 state |= StateFlags.HasDynamicElement;
1545 if (open_type.Kind == MemberKind.MissingType)
1546 MemberCache = MemberCache.Empty;
1548 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1549 state |= StateFlags.ConstraintsChecked;
1554 public override TypeSpec BaseType {
1556 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1557 InitializeMemberCache (true);
1559 return base.BaseType;
1564 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1566 public TypeParameterSpec[] Constraints {
1568 if (constraints == null) {
1569 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1577 // Used to cache expensive constraints validation on constructed types
1579 public bool HasConstraintsChecked {
1581 return (state & StateFlags.ConstraintsChecked) != 0;
1584 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1588 public override IList<TypeSpec> Interfaces {
1591 InitializeMemberCache (true);
1593 return base.Interfaces;
1597 public override bool IsExpressionTreeType {
1599 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1603 public override bool IsGenericIterateInterface {
1605 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1609 public override bool IsGenericTask {
1611 return (open_type.state & StateFlags.GenericTask) != 0;
1615 public override bool IsNullableType {
1617 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1622 // Types used to inflate the generic type
1624 public override TypeSpec[] TypeArguments {
1632 public static bool ContainsTypeParameter (TypeSpec type)
1634 if (type.Kind == MemberKind.TypeParameter)
1637 var element_container = type as ElementTypeSpec;
1638 if (element_container != null)
1639 return ContainsTypeParameter (element_container.Element);
1641 foreach (var t in type.TypeArguments) {
1642 if (ContainsTypeParameter (t)) {
1650 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1652 TypeParameterSpec[] tparams_full;
1653 TypeSpec[] targs_full = targs;
1656 // Special case is needed when we are inflating an open type (nested type definition)
1657 // on inflated parent. Consider following case
1659 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1661 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1663 List<TypeSpec> merged_targs = null;
1664 List<TypeParameterSpec> merged_tparams = null;
1666 var type = DeclaringType;
1669 if (type.TypeArguments.Length > 0) {
1670 if (merged_targs == null) {
1671 merged_targs = new List<TypeSpec> ();
1672 merged_tparams = new List<TypeParameterSpec> ();
1673 if (targs.Length > 0) {
1674 merged_targs.AddRange (targs);
1675 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1678 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1679 merged_targs.AddRange (type.TypeArguments);
1681 type = type.DeclaringType;
1682 } while (type != null);
1684 if (merged_targs != null) {
1685 // Type arguments are not in the right order but it should not matter in this case
1686 targs_full = merged_targs.ToArray ();
1687 tparams_full = merged_tparams.ToArray ();
1688 } else if (targs.Length == 0) {
1689 tparams_full = TypeParameterSpec.EmptyTypes;
1691 tparams_full = open_type.MemberDefinition.TypeParameters;
1693 } else if (targs.Length == 0) {
1694 tparams_full = TypeParameterSpec.EmptyTypes;
1696 tparams_full = open_type.MemberDefinition.TypeParameters;
1699 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1702 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1705 // Converts nested type arguments into right order
1706 // Foo<string, bool>.Bar<int> => string, bool, int
1708 var all = new List<MetaType> ();
1709 TypeSpec type = this;
1710 TypeSpec definition = type;
1712 if (type.GetDefinition().IsGeneric) {
1714 type.TypeArguments != TypeSpec.EmptyTypes ?
1715 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1716 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1719 definition = definition.GetDefinition ();
1720 type = type.DeclaringType;
1721 } while (type != null);
1723 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1726 public override ObsoleteAttribute GetAttributeObsolete ()
1728 return open_type.GetAttributeObsolete ();
1731 protected override bool IsNotCLSCompliant (out bool attrValue)
1733 if (base.IsNotCLSCompliant (out attrValue))
1736 foreach (var ta in TypeArguments) {
1737 if (ta.MemberDefinition.CLSAttributeValue == false)
1744 public override TypeSpec GetDefinition ()
1749 public override MetaType GetMetaInfo ()
1752 info = CreateMetaInfo (null);
1757 public override string GetSignatureForError ()
1760 return targs[0].GetSignatureForError () + "?";
1762 return base.GetSignatureForError ();
1765 protected override string GetTypeNameSignature ()
1767 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1770 return "<" + TypeManager.CSharpName (targs) + ">";
1773 public bool HasDynamicArgument ()
1775 for (int i = 0; i < targs.Length; ++i) {
1776 var item = targs[i];
1778 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1781 if (item is InflatedTypeSpec) {
1782 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1789 while (item.IsArray) {
1790 item = ((ArrayContainer) item).Element;
1793 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1801 protected override void InitializeMemberCache (bool onlyTypes)
1803 if (cache == null) {
1804 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1806 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1807 // for imported type parameter constraints referencing nested type of this declaration
1809 cache = new MemberCache (open_cache);
1812 var inflator = CreateLocalInflator (context);
1815 // Two stage inflate due to possible nested types recursive
1825 // When resolving type of `b' members of `B' cannot be
1826 // inflated because are not yet available in membercache
1828 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1829 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1832 // Inflate any implemented interfaces
1834 if (open_type.Interfaces != null) {
1835 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1836 foreach (var iface in open_type.Interfaces) {
1837 var iface_inflated = inflator.Inflate (iface);
1838 if (iface_inflated == null)
1841 AddInterface (iface_inflated);
1846 // Handles the tricky case of recursive nested base generic type
1848 // class A<T> : Base<A<T>.Nested> {
1852 // When inflating A<T>. base type is not yet known, secondary
1853 // inflation is required (not common case) once base scope
1856 if (open_type.BaseType == null) {
1858 state |= StateFlags.PendingBaseTypeInflate;
1860 BaseType = inflator.Inflate (open_type.BaseType);
1862 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1864 // It can happen when resolving base type without being defined
1865 // which is not allowed to happen and will always lead to an error
1867 // class B { class N {} }
1868 // class A<T> : A<B.N> {}
1870 if (open_type.BaseType == null)
1873 BaseType = inflator.Inflate (open_type.BaseType);
1874 state &= ~StateFlags.PendingBaseTypeInflate;
1878 state |= StateFlags.PendingMemberCacheMembers;
1882 var tc = open_type.MemberDefinition as TypeDefinition;
1883 if (tc != null && !tc.HasMembersDefined) {
1885 // Inflating MemberCache with undefined members
1890 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1891 BaseType = inflator.Inflate (open_type.BaseType);
1892 state &= ~StateFlags.PendingBaseTypeInflate;
1895 state &= ~StateFlags.PendingMemberCacheMembers;
1896 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1899 public override TypeSpec Mutate (TypeParameterMutator mutator)
1901 var targs = TypeArguments;
1903 targs = mutator.Mutate (targs);
1905 var decl = DeclaringType;
1906 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1907 decl = mutator.Mutate (decl);
1909 if (targs == TypeArguments && decl == DeclaringType)
1912 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1913 if (decl != DeclaringType) {
1914 // Gets back MethodInfo in case of metaInfo was inflated
1915 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1917 mutated.declaringType = decl;
1918 mutated.state |= StateFlags.PendingMetaInflate;
1921 if (targs != null) {
1922 mutated.targs = targs;
1923 mutated.info = null;
1932 // Tracks the type arguments when instantiating a generic type. It's used
1933 // by both type arguments and type parameters
1935 public class TypeArguments
1937 List<FullNamedExpression> args;
1940 public TypeArguments (params FullNamedExpression[] types)
1942 this.args = new List<FullNamedExpression> (types);
1945 public void Add (FullNamedExpression type)
1951 /// We may only be used after Resolve() is called and return the fully
1954 // TODO: Not needed, just return type from resolve
1955 public TypeSpec[] Arguments {
1970 public virtual bool IsEmpty {
1976 public List<FullNamedExpression> TypeExpressions {
1982 public string GetSignatureForError()
1984 StringBuilder sb = new StringBuilder ();
1985 for (int i = 0; i < Count; ++i) {
1988 sb.Append (expr.GetSignatureForError ());
1994 return sb.ToString ();
1998 /// Resolve the type arguments.
2000 public virtual bool Resolve (IMemberContext ec)
2003 return atypes.Length != 0;
2005 int count = args.Count;
2008 atypes = new TypeSpec [count];
2010 for (int i = 0; i < count; i++){
2011 var te = args[i].ResolveAsType (ec);
2020 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
2021 te.GetSignatureForError ());
2025 if (te.IsPointer || te.IsSpecialRuntimeType) {
2026 ec.Module.Compiler.Report.Error (306, args[i].Location,
2027 "The type `{0}' may not be used as a type argument",
2028 te.GetSignatureForError ());
2034 atypes = TypeSpec.EmptyTypes;
2039 public TypeArguments Clone ()
2041 TypeArguments copy = new TypeArguments ();
2042 foreach (var ta in args)
2049 public class UnboundTypeArguments : TypeArguments
2051 public UnboundTypeArguments (int arity)
2052 : base (new FullNamedExpression[arity])
2056 public override bool IsEmpty {
2062 public override bool Resolve (IMemberContext ec)
2064 // Nothing to be resolved
2069 public class TypeParameters
2071 List<TypeParameter> names;
2072 TypeParameterSpec[] types;
2074 public TypeParameters ()
2076 names = new List<TypeParameter> ();
2079 public TypeParameters (int count)
2081 names = new List<TypeParameter> (count);
2092 public TypeParameterSpec[] Types {
2100 public void Add (TypeParameter tparam)
2105 public void Add (TypeParameters tparams)
2107 names.AddRange (tparams.names);
2110 public void Define (GenericTypeParameterBuilder[] buiders, TypeSpec declaringType, int parentOffset, TypeContainer parent)
2112 types = new TypeParameterSpec[Count];
2113 for (int i = 0; i < types.Length; ++i) {
2116 tp.Define (buiders[i + parentOffset], declaringType, parent);
2118 types[i].DeclaredPosition = i + parentOffset;
2120 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2121 parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2126 public TypeParameter this[int index] {
2128 return names [index];
2131 names[index] = value;
2135 public TypeParameter Find (string name)
2137 foreach (var tp in names) {
2138 if (tp.Name == name)
2145 public string[] GetAllNames ()
2147 return names.Select (l => l.Name).ToArray ();
2150 public string GetSignatureForError ()
2152 StringBuilder sb = new StringBuilder ();
2153 for (int i = 0; i < Count; ++i) {
2157 var name = names[i];
2159 sb.Append (name.GetSignatureForError ());
2162 return sb.ToString ();
2165 public void VerifyClsCompliance ()
2167 foreach (var tp in names) {
2168 tp.VerifyClsCompliance ();
2174 // A type expression of generic type with type arguments
2176 class GenericTypeExpr : TypeExpr
2182 /// Instantiate the generic type `t' with the type arguments `args'.
2183 /// Use this constructor if you already know the fully resolved
2186 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2188 this.open_type = open_type;
2193 public override string GetSignatureForError ()
2195 return TypeManager.CSharpName (type);
2198 public override TypeSpec ResolveAsType (IMemberContext mc)
2200 if (eclass != ExprClass.Unresolved)
2203 if (!args.Resolve (mc))
2206 TypeSpec[] atypes = args.Arguments;
2209 // Now bind the parameters
2211 var inflated = open_type.MakeGenericType (mc, atypes);
2213 eclass = ExprClass.Type;
2216 // The constraints can be checked only when full type hierarchy is known
2218 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2219 var constraints = inflated.Constraints;
2220 if (constraints != null) {
2221 var cc = new ConstraintChecker (mc);
2222 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2223 inflated.HasConstraintsChecked = true;
2231 public override bool Equals (object obj)
2233 GenericTypeExpr cobj = obj as GenericTypeExpr;
2237 if ((type == null) || (cobj.type == null))
2240 return type == cobj.type;
2243 public override int GetHashCode ()
2245 return base.GetHashCode ();
2250 // Generic type with unbound type arguments, used for typeof (G<,,>)
2252 class GenericOpenTypeExpr : TypeExpression
2254 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2255 : base (type.GetDefinition (), loc)
2260 struct ConstraintChecker
2263 bool recursive_checks;
2265 public ConstraintChecker (IMemberContext ctx)
2268 recursive_checks = false;
2272 // Checks the constraints of open generic type against type
2273 // arguments. This version is used for types which could not be
2274 // checked immediatelly during construction because the type
2275 // hierarchy was not yet fully setup (before Emit phase)
2277 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2280 // Check declaring type first if there is any
2282 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2285 while (type is ElementTypeSpec)
2286 type = ((ElementTypeSpec) type).Element;
2288 if (type.Arity == 0)
2291 var gtype = type as InflatedTypeSpec;
2295 var constraints = gtype.Constraints;
2296 if (constraints == null)
2299 if (gtype.HasConstraintsChecked)
2302 var cc = new ConstraintChecker (mc);
2303 cc.recursive_checks = true;
2305 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2306 gtype.HasConstraintsChecked = true;
2314 // Checks all type arguments againts type parameters constraints
2315 // NOTE: It can run in probing mode when `this.mc' is null
2317 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2319 for (int i = 0; i < tparams.Length; i++) {
2320 var targ = targs[i];
2321 if (!CheckConstraint (context, targ, tparams [i], loc))
2324 if (!recursive_checks)
2327 if (!Check (mc, targ, loc))
2334 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2337 // First, check the `class' and `struct' constraints.
2339 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2341 mc.Module.Compiler.Report.Error (452, loc,
2342 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2343 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2349 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2351 mc.Module.Compiler.Report.Error (453, loc,
2352 "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}'",
2353 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2362 // Check the class constraint
2364 if (tparam.HasTypeConstraint) {
2365 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2374 // Check the interfaces constraints
2376 if (tparam.Interfaces != null) {
2377 foreach (TypeSpec iface in tparam.Interfaces) {
2378 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2388 // Check the type parameter constraint
2390 if (tparam.TypeArguments != null) {
2391 foreach (var ta in tparam.TypeArguments) {
2392 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2402 // Finally, check the constructor constraint.
2404 if (!tparam.HasSpecialConstructor)
2407 if (!HasDefaultConstructor (atype)) {
2409 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2410 mc.Module.Compiler.Report.Error (310, loc,
2411 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2412 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2420 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2422 for (int i = 0; i < targs.Length; ++i) {
2423 var targ = targs [i];
2424 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2427 if (HasDynamicTypeArgument (targ.TypeArguments))
2434 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2439 if (atype.IsGenericParameter) {
2440 var tps = (TypeParameterSpec) atype;
2441 if (tps.HasDependencyOn (ttype))
2444 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2447 } else if (TypeSpec.IsValueType (atype)) {
2448 if (atype.IsNullableType) {
2450 // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2452 if (TypeSpec.IsBaseClass (atype, ttype, false))
2455 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2459 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2464 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2465 if (atype.IsGenericParameter) {
2466 mc.Module.Compiler.Report.Error (314, loc,
2467 "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}'",
2468 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2469 } else if (TypeSpec.IsValueType (atype)) {
2470 if (atype.IsNullableType) {
2471 if (ttype.IsInterface) {
2472 mc.Module.Compiler.Report.Error (313, loc,
2473 "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}'",
2474 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2476 mc.Module.Compiler.Report.Error (312, loc,
2477 "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}'",
2478 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2481 mc.Module.Compiler.Report.Error (315, loc,
2482 "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}'",
2483 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2486 mc.Module.Compiler.Report.Error (311, loc,
2487 "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}'",
2488 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2495 static bool HasDefaultConstructor (TypeSpec atype)
2497 var tp = atype as TypeParameterSpec;
2499 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2502 if (atype.IsStruct || atype.IsEnum)
2505 if (atype.IsAbstract)
2508 var tdef = atype.GetDefinition ();
2510 var found = MemberCache.FindMember (tdef,
2511 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2512 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2514 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2518 public partial class TypeManager
2520 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2522 var tp = t as TypeParameterSpec;
2524 Variance v = tp.Variance;
2525 if (expected == Variance.None && v != expected ||
2526 expected == Variance.Covariant && v == Variance.Contravariant ||
2527 expected == Variance.Contravariant && v == Variance.Covariant) {
2528 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2534 if (t.TypeArguments.Length > 0) {
2535 var targs_definition = t.MemberDefinition.TypeParameters;
2536 TypeSpec[] targs = GetTypeArguments (t);
2537 for (int i = 0; i < targs.Length; ++i) {
2538 Variance v = targs_definition[i].Variance;
2539 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2546 return CheckTypeVariance (GetElementType (t), expected, member);
2548 return Variance.None;
2553 // Implements C# type inference
2558 // Tracks successful rate of type inference
2560 int score = int.MaxValue;
2561 readonly Arguments arguments;
2562 readonly int arg_count;
2564 public TypeInference (Arguments arguments)
2566 this.arguments = arguments;
2567 if (arguments != null)
2568 arg_count = arguments.Count;
2571 public int InferenceScore {
2577 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2579 var method_generic_args = method.GenericDefinition.TypeParameters;
2580 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2581 if (!context.UnfixedVariableExists)
2582 return TypeSpec.EmptyTypes;
2584 AParametersCollection pd = method.Parameters;
2585 if (!InferInPhases (ec, context, pd))
2588 return context.InferredTypeArguments;
2592 // Implements method type arguments inference
2594 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2596 int params_arguments_start;
2597 if (methodParameters.HasParams) {
2598 params_arguments_start = methodParameters.Count - 1;
2600 params_arguments_start = arg_count;
2603 TypeSpec [] ptypes = methodParameters.Types;
2606 // The first inference phase
2608 TypeSpec method_parameter = null;
2609 for (int i = 0; i < arg_count; i++) {
2610 Argument a = arguments [i];
2614 if (i < params_arguments_start) {
2615 method_parameter = methodParameters.Types [i];
2616 } else if (i == params_arguments_start) {
2617 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2618 method_parameter = methodParameters.Types [params_arguments_start];
2620 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2622 ptypes = (TypeSpec[]) ptypes.Clone ();
2623 ptypes [i] = method_parameter;
2627 // When a lambda expression, an anonymous method
2628 // is used an explicit argument type inference takes a place
2630 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2632 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2638 score -= tic.ExactInference (a.Type, method_parameter);
2642 if (a.Expr.Type == InternalType.NullLiteral)
2645 if (TypeSpec.IsValueType (method_parameter)) {
2646 score -= tic.LowerBoundInference (a.Type, method_parameter);
2651 // Otherwise an output type inference is made
2653 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2657 // Part of the second phase but because it happens only once
2658 // we don't need to call it in cycle
2660 bool fixed_any = false;
2661 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2664 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2667 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2669 bool fixed_any = false;
2670 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2673 // If no further unfixed type variables exist, type inference succeeds
2674 if (!tic.UnfixedVariableExists)
2677 if (!fixed_any && fixDependent)
2680 // For all arguments where the corresponding argument output types
2681 // contain unfixed type variables but the input types do not,
2682 // an output type inference is made
2683 for (int i = 0; i < arg_count; i++) {
2685 // Align params arguments
2686 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2688 if (!t_i.IsDelegate) {
2689 if (!t_i.IsExpressionTreeType)
2692 t_i = TypeManager.GetTypeArguments (t_i) [0];
2695 var mi = Delegate.GetInvokeMethod (t_i);
2696 TypeSpec rtype = mi.ReturnType;
2698 if (tic.IsReturnTypeNonDependent (ec, mi, rtype)) {
2699 // It can be null for default arguments
2700 if (arguments[i] == null)
2703 score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2708 return DoSecondPhase (ec, tic, methodParameters, true);
2712 public class TypeInferenceContext
2714 protected enum BoundKind
2721 struct BoundInfo : IEquatable<BoundInfo>
2723 public readonly TypeSpec Type;
2724 public readonly BoundKind Kind;
2726 public BoundInfo (TypeSpec type, BoundKind kind)
2732 public override int GetHashCode ()
2734 return Type.GetHashCode ();
2737 public Expression GetTypeExpression ()
2739 return new TypeExpression (Type, Location.Null);
2742 #region IEquatable<BoundInfo> Members
2744 public bool Equals (BoundInfo other)
2746 return Type == other.Type && Kind == other.Kind;
2752 readonly TypeSpec[] tp_args;
2753 readonly TypeSpec[] fixed_types;
2754 readonly List<BoundInfo>[] bounds;
2757 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2758 public TypeInferenceContext (TypeSpec[] typeArguments)
2760 if (typeArguments.Length == 0)
2761 throw new ArgumentException ("Empty generic arguments");
2763 fixed_types = new TypeSpec [typeArguments.Length];
2764 for (int i = 0; i < typeArguments.Length; ++i) {
2765 if (typeArguments [i].IsGenericParameter) {
2766 if (bounds == null) {
2767 bounds = new List<BoundInfo> [typeArguments.Length];
2768 tp_args = new TypeSpec [typeArguments.Length];
2770 tp_args [i] = typeArguments [i];
2772 fixed_types [i] = typeArguments [i];
2778 // Used together with AddCommonTypeBound fo implement
2779 // 7.4.2.13 Finding the best common type of a set of expressions
2781 public TypeInferenceContext ()
2783 fixed_types = new TypeSpec [1];
2784 tp_args = new TypeSpec [1];
2785 tp_args[0] = InternalType.Arglist; // it can be any internal type
2786 bounds = new List<BoundInfo> [1];
2789 public TypeSpec[] InferredTypeArguments {
2795 public void AddCommonTypeBound (TypeSpec type)
2797 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2800 void AddToBounds (BoundInfo bound, int index)
2803 // Some types cannot be used as type arguments
2805 if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2806 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
2809 var a = bounds [index];
2811 a = new List<BoundInfo> (2);
2817 if (a.Contains (bound))
2823 bool AllTypesAreFixed (TypeSpec[] types)
2825 foreach (TypeSpec t in types) {
2826 if (t.IsGenericParameter) {
2832 if (TypeManager.IsGenericType (t))
2833 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2840 // 26.3.3.8 Exact Inference
2842 public int ExactInference (TypeSpec u, TypeSpec v)
2844 // If V is an array type
2849 var ac_u = (ArrayContainer) u;
2850 var ac_v = (ArrayContainer) v;
2851 if (ac_u.Rank != ac_v.Rank)
2854 return ExactInference (ac_u.Element, ac_v.Element);
2857 // If V is constructed type and U is constructed type
2858 if (TypeManager.IsGenericType (v)) {
2859 if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
2862 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2863 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2864 if (ga_u.Length != ga_v.Length)
2868 for (int i = 0; i < ga_u.Length; ++i)
2869 score += ExactInference (ga_u [i], ga_v [i]);
2871 return System.Math.Min (1, score);
2874 // If V is one of the unfixed type arguments
2875 int pos = IsUnfixed (v);
2879 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2883 public bool FixAllTypes (ResolveContext ec)
2885 for (int i = 0; i < tp_args.Length; ++i) {
2886 if (!FixType (ec, i))
2893 // All unfixed type variables Xi are fixed for which all of the following hold:
2894 // a, There is at least one type variable Xj that depends on Xi
2895 // b, Xi has a non-empty set of bounds
2897 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2899 for (int i = 0; i < tp_args.Length; ++i) {
2900 if (fixed_types[i] != null)
2903 if (bounds[i] == null)
2906 if (!FixType (ec, i))
2916 // All unfixed type variables Xi which depend on no Xj are fixed
2918 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2920 var types_to_fix = new List<TypeSpec> (tp_args);
2921 for (int i = 0; i < methodParameters.Length; ++i) {
2922 TypeSpec t = methodParameters[i];
2924 if (!t.IsDelegate) {
2925 if (!t.IsExpressionTreeType)
2928 t = TypeManager.GetTypeArguments (t) [0];
2931 if (t.IsGenericParameter)
2934 var invoke = Delegate.GetInvokeMethod (t);
2935 TypeSpec rtype = invoke.ReturnType;
2936 while (rtype.IsArray)
2937 rtype = ((ArrayContainer) rtype).Element;
2939 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2942 // Remove dependent types, they cannot be fixed yet
2943 RemoveDependentTypes (types_to_fix, rtype);
2946 foreach (TypeSpec t in types_to_fix) {
2950 int idx = IsUnfixed (t);
2951 if (idx >= 0 && !FixType (ec, idx)) {
2956 fixed_any = types_to_fix.Count > 0;
2963 public bool FixType (ResolveContext ec, int i)
2965 // It's already fixed
2966 if (fixed_types[i] != null)
2967 throw new InternalErrorException ("Type argument has been already fixed");
2972 var candidates = bounds [i];
2973 if (candidates == null)
2976 if (candidates.Count == 1) {
2977 TypeSpec t = candidates[0].Type;
2978 if (t == InternalType.NullLiteral)
2981 fixed_types [i] = t;
2986 // Determines a unique type from which there is
2987 // a standard implicit conversion to all the other
2990 TypeSpec best_candidate = null;
2992 int candidates_count = candidates.Count;
2993 for (int ci = 0; ci < candidates_count; ++ci) {
2994 BoundInfo bound = candidates [ci];
2995 for (cii = 0; cii < candidates_count; ++cii) {
2999 BoundInfo cbound = candidates[cii];
3001 // Same type parameters with different bounds
3002 if (cbound.Type == bound.Type) {
3003 if (bound.Kind != BoundKind.Exact)
3009 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
3010 if (cbound.Kind == BoundKind.Lower) {
3011 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3017 if (cbound.Kind == BoundKind.Upper) {
3018 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3025 if (bound.Kind != BoundKind.Exact) {
3026 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3037 if (bound.Kind == BoundKind.Lower) {
3038 if (cbound.Kind == BoundKind.Lower) {
3039 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3043 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3053 if (bound.Kind == BoundKind.Upper) {
3054 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3058 throw new NotImplementedException ("variance conversion");
3062 if (cii != candidates_count)
3066 // We already have the best candidate, break if thet are different
3068 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3070 if (best_candidate != null) {
3072 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3075 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3079 best_candidate = bound.Type;
3082 if (best_candidate == null)
3085 fixed_types[i] = best_candidate;
3089 public bool HasBounds (int pos)
3091 return bounds[pos] != null;
3095 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3096 // null when type parameter has not been fixed
3098 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3100 var tp = parameter as TypeParameterSpec;
3103 // Type inference works on generic arguments (MVAR) only
3105 if (!tp.IsMethodOwned)
3109 // Ensure the type parameter belongs to same container
3111 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3112 return fixed_types[tp.DeclaredPosition] ?? parameter;
3117 var gt = parameter as InflatedTypeSpec;
3119 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3120 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3121 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3122 if (inflated == null)
3125 inflated_targs[ii] = inflated;
3128 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3131 var ac = parameter as ArrayContainer;
3133 var inflated = InflateGenericArgument (context, ac.Element);
3134 if (inflated != ac.Element)
3135 return ArrayContainer.MakeType (context.Module, inflated);
3142 // Tests whether all delegate input arguments are fixed and generic output type
3143 // requires output type inference
3145 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3147 while (returnType.IsArray)
3148 returnType = ((ArrayContainer) returnType).Element;
3150 if (returnType.IsGenericParameter) {
3151 if (IsFixed (returnType))
3153 } else if (TypeManager.IsGenericType (returnType)) {
3154 if (returnType.IsDelegate) {
3155 invoke = Delegate.GetInvokeMethod (returnType);
3156 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3159 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3161 // At least one unfixed return type has to exist
3162 if (AllTypesAreFixed (g_args))
3168 // All generic input arguments have to be fixed
3169 AParametersCollection d_parameters = invoke.Parameters;
3170 return AllTypesAreFixed (d_parameters.Types);
3173 bool IsFixed (TypeSpec type)
3175 return IsUnfixed (type) == -1;
3178 int IsUnfixed (TypeSpec type)
3180 if (!type.IsGenericParameter)
3183 for (int i = 0; i < tp_args.Length; ++i) {
3184 if (tp_args[i] == type) {
3185 if (fixed_types[i] != null)
3196 // 26.3.3.9 Lower-bound Inference
3198 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3200 return LowerBoundInference (u, v, false);
3204 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3206 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3208 // If V is one of the unfixed type arguments
3209 int pos = IsUnfixed (v);
3211 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3215 // If U is an array type
3216 var u_ac = u as ArrayContainer;
3218 var v_ac = v as ArrayContainer;
3220 if (u_ac.Rank != v_ac.Rank)
3223 if (TypeSpec.IsValueType (u_ac.Element))
3224 return ExactInference (u_ac.Element, v_ac.Element);
3226 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3229 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3232 var v_i = TypeManager.GetTypeArguments (v) [0];
3233 if (TypeSpec.IsValueType (u_ac.Element))
3234 return ExactInference (u_ac.Element, v_i);
3236 return LowerBoundInference (u_ac.Element, v_i);
3239 if (v.IsGenericOrParentIsGeneric) {
3241 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3242 // such that U is identical to, inherits from (directly or indirectly),
3243 // or implements (directly or indirectly) C<U1..Uk>
3245 var u_candidates = new List<TypeSpec> ();
3246 var open_v = v.MemberDefinition;
3248 for (TypeSpec t = u; t != null; t = t.BaseType) {
3249 if (open_v == t.MemberDefinition)
3250 u_candidates.Add (t);
3253 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3254 // that would complicate the process a lot, instead I treat them as dynamic
3256 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3257 u_candidates.Add (t);
3259 if (t.Interfaces != null) {
3260 foreach (var iface in t.Interfaces) {
3261 if (open_v == iface.MemberDefinition)
3262 u_candidates.Add (iface);
3267 TypeSpec[] unique_candidate_targs = null;
3268 var ga_v = TypeSpec.GetAllTypeArguments (v);
3269 foreach (TypeSpec u_candidate in u_candidates) {
3271 // The unique set of types U1..Uk means that if we have an interface I<T>,
3272 // class U : I<int>, I<long> then no type inference is made when inferring
3273 // type I<T> by applying type U because T could be int or long
3275 if (unique_candidate_targs != null) {
3276 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3277 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3278 unique_candidate_targs = second_unique_candidate_targs;
3283 // This should always cause type inference failure
3290 // A candidate is dynamic type expression, to simplify things use dynamic
3291 // for all type parameter of this type. For methods like this one
3293 // void M<T, U> (IList<T>, IList<U[]>)
3295 // dynamic becomes both T and U when the arguments are of dynamic type
3297 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3298 unique_candidate_targs = new TypeSpec[ga_v.Length];
3299 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3300 unique_candidate_targs[i] = u_candidate;
3302 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3306 if (unique_candidate_targs != null) {
3309 TypeParameterSpec[] tps = null;
3311 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3313 while (v.Arity == 0)
3314 v = v.DeclaringType;
3316 tps = v.MemberDefinition.TypeParameters;
3317 tp_index = tps.Length - 1;
3320 Variance variance = tps [tp_index--].Variance;
3322 TypeSpec u_i = unique_candidate_targs [i];
3323 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3324 if (ExactInference (u_i, ga_v [i]) == 0)
3327 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3328 (variance == Variance.Covariant && inversed);
3330 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3343 // 26.3.3.6 Output Type Inference
3345 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3347 // If e is a lambda or anonymous method with inferred return type
3348 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3350 TypeSpec rt = ame.InferReturnType (ec, this, t);
3351 var invoke = Delegate.GetInvokeMethod (t);
3354 AParametersCollection pd = invoke.Parameters;
3355 return ame.Parameters.Count == pd.Count ? 1 : 0;
3358 TypeSpec rtype = invoke.ReturnType;
3359 return LowerBoundInference (rt, rtype) + 1;
3363 // if E is a method group and T is a delegate type or expression tree type
3364 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3365 // resolution of E with the types T1..Tk yields a single method with return type U,
3366 // then a lower-bound inference is made from U for Tb.
3368 if (e is MethodGroupExpr) {
3369 if (!t.IsDelegate) {
3370 if (!t.IsExpressionTreeType)
3373 t = TypeManager.GetTypeArguments (t)[0];
3376 var invoke = Delegate.GetInvokeMethod (t);
3377 TypeSpec rtype = invoke.ReturnType;
3379 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3382 // LAMESPEC: Standard does not specify that all methodgroup arguments
3383 // has to be fixed but it does not specify how to do recursive type inference
3384 // either. We choose the simple option and infer return type only
3385 // if all delegate generic arguments are fixed.
3386 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3387 for (int i = 0; i < param_types.Length; ++i) {
3388 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3389 if (inflated == null)
3392 if (IsUnfixed (inflated) >= 0)
3395 param_types[i] = inflated;
3398 MethodGroupExpr mg = (MethodGroupExpr) e;
3399 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3400 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3404 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3408 // if e is an expression with type U, then
3409 // a lower-bound inference is made from U for T
3411 return LowerBoundInference (e.Type, t) * 2;
3414 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3416 int idx = IsUnfixed (returnType);
3422 if (TypeManager.IsGenericType (returnType)) {
3423 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3424 RemoveDependentTypes (types, t);
3429 public bool UnfixedVariableExists {
3431 foreach (TypeSpec ut in fixed_types) {