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
14 using System.Collections.Generic;
19 using MetaType = IKVM.Reflection.Type;
20 using IKVM.Reflection;
21 using IKVM.Reflection.Emit;
23 using MetaType = System.Type;
24 using System.Reflection;
25 using System.Reflection.Emit;
28 namespace Mono.CSharp {
32 // Don't add or modify internal values, they are used as -/+ calculation signs
40 public enum SpecialConstraint
48 public class SpecialContraintExpr : FullNamedExpression
50 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
53 this.Constraint = constraint;
56 public SpecialConstraint Constraint { get; private set; }
58 protected override Expression DoResolve (ResolveContext rc)
60 throw new NotImplementedException ();
65 // A set of parsed constraints for a type parameter
67 public class Constraints
69 SimpleMemberName tparam;
70 List<FullNamedExpression> constraints;
75 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
78 this.constraints = constraints;
84 public Location Location {
90 public SimpleMemberName TypeParameter {
98 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
100 if (spec.HasSpecialClass && bb.IsStruct) {
101 context.Module.Compiler.Report.Error (455, loc,
102 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
103 spec.Name, "class", bb.GetSignatureForError ());
108 return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
111 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
116 if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
119 context.Module.Compiler.Report.Error (455, loc,
120 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
121 spec.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
125 public void CheckGenericConstraints (IMemberContext context)
127 foreach (var c in constraints) {
128 var ge = c as GenericTypeExpr;
130 ge.CheckConstraints (context);
135 // Resolve the constraints types with only possible early checks, return
136 // value `false' is reserved for recursive failure
138 public bool Resolve (IMemberContext context, TypeParameter tp)
148 List<TypeParameterSpec> tparam_types = null;
149 bool iface_found = false;
151 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
153 for (int i = 0; i < constraints.Count; ++i) {
154 var constraint = constraints[i];
156 if (constraint is SpecialContraintExpr) {
157 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
158 if (spec.HasSpecialStruct)
159 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
161 // Set to null as it does not have a type
162 constraints[i] = null;
166 var type_expr = constraints[i] = constraint.ResolveAsTypeTerminal (context, false);
167 if (type_expr == null)
170 var gexpr = type_expr as GenericTypeExpr;
171 if (gexpr != null && gexpr.HasDynamicArguments ()) {
172 context.Module.Compiler.Report.Error (1968, constraint.Location,
173 "A constraint cannot be the dynamic type `{0}'", gexpr.GetSignatureForError ());
177 var type = type_expr.Type;
179 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
180 context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
181 context.Module.Compiler.Report.Error (703, loc,
182 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
183 type.GetSignatureForError (), context.GetSignatureForError ());
186 if (type.IsInterface) {
187 if (!spec.AddInterface (type)) {
188 context.Module.Compiler.Report.Error (405, constraint.Location,
189 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
197 var constraint_tp = type as TypeParameterSpec;
198 if (constraint_tp != null) {
199 if (tparam_types == null) {
200 tparam_types = new List<TypeParameterSpec> (2);
201 } else if (tparam_types.Contains (constraint_tp)) {
202 context.Module.Compiler.Report.Error (405, constraint.Location,
203 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
208 // Checks whether each generic method parameter constraint type
209 // is valid with respect to T
211 if (tp.IsMethodTypeParameter) {
212 TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
215 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
216 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
217 context.Module.Compiler.Report.Error (454, constraint.Location,
218 "Circular constraint dependency involving `{0}' and `{1}'",
219 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
224 // Checks whether there are no conflicts between type parameter constraints
230 // A and B are not convertible and only 1 class constraint is allowed
232 if (constraint_tp.HasTypeConstraint) {
233 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
234 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
237 for (int ii = 0; ii < tparam_types.Count; ++ii) {
238 if (!tparam_types[ii].HasTypeConstraint)
241 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
247 if (constraint_tp.HasSpecialStruct) {
248 context.Module.Compiler.Report.Error (456, constraint.Location,
249 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
250 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
254 tparam_types.Add (constraint_tp);
258 if (iface_found || spec.HasTypeConstraint) {
259 context.Module.Compiler.Report.Error (406, constraint.Location,
260 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
261 type.GetSignatureForError ());
264 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
265 context.Module.Compiler.Report.Error (450, type_expr.Location,
266 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
267 type.GetSignatureForError ());
270 switch (type.BuiltinType) {
271 case BuiltinTypeSpec.Type.Array:
272 case BuiltinTypeSpec.Type.Delegate:
273 case BuiltinTypeSpec.Type.MulticastDelegate:
274 case BuiltinTypeSpec.Type.Enum:
275 case BuiltinTypeSpec.Type.ValueType:
276 case BuiltinTypeSpec.Type.Object:
277 context.Module.Compiler.Report.Error (702, constraint.Location,
278 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
280 case BuiltinTypeSpec.Type.Dynamic:
281 context.Module.Compiler.Report.Error (1967, constraint.Location,
282 "A constraint cannot be the dynamic type");
286 if (type.IsSealed || !type.IsClass) {
287 context.Module.Compiler.Report.Error (701, loc,
288 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
289 TypeManager.CSharpName (type));
294 context.Module.Compiler.Report.Error (717, constraint.Location,
295 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
296 type.GetSignatureForError ());
299 spec.BaseType = type;
302 if (tparam_types != null)
303 spec.TypeArguments = tparam_types.ToArray ();
310 public void VerifyClsCompliance (Report report)
312 foreach (var c in constraints)
317 if (!c.Type.IsCLSCompliant ()) {
318 report.SymbolRelatedToPreviousError (c.Type);
319 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
320 c.Type.GetSignatureForError ());
327 // A type parameter for a generic type or generic method definition
329 public class TypeParameter : MemberCore, ITypeDefinition
331 static readonly string[] attribute_target = new string [] { "type parameter" };
333 Constraints constraints;
334 GenericTypeParameterBuilder builder;
335 TypeParameterSpec spec;
337 public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
338 : base (parent, name, attrs)
340 this.constraints = constraints;
341 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
344 public TypeParameter (TypeParameterSpec spec, DeclSpace parent, TypeSpec parentSpec, MemberName name, Attributes attrs)
345 : base (parent, name, attrs)
347 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
348 BaseType = spec.BaseType,
349 InterfacesDefined = spec.InterfacesDefined,
350 TypeArguments = spec.TypeArguments
356 public override AttributeTargets AttributeTargets {
358 return AttributeTargets.GenericParameter;
362 public IAssemblyDefinition DeclaringAssembly {
364 return Module.DeclaringAssembly;
368 public override string DocCommentHeader {
370 throw new InvalidOperationException (
371 "Unexpected attempt to get doc comment from " + this.GetType ());
375 public bool IsMethodTypeParameter {
377 return spec.IsMethodOwned;
381 public string Namespace {
387 public TypeParameterSpec Type {
393 public int TypeParametersCount {
399 public TypeParameterSpec[] TypeParameters {
405 public override string[] ValidAttributeTargets {
407 return attribute_target;
411 public Variance Variance {
413 return spec.Variance;
420 // This is called for each part of a partial generic type definition.
422 // If partial type parameters constraints are not null and we don't
423 // already have constraints they become our constraints. If we already
424 // have constraints, we must check that they're the same.
426 public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
429 throw new InvalidOperationException ();
431 var new_constraints = tp.constraints;
432 if (new_constraints == null)
435 // TODO: could create spec only
436 //tp.Define (null, -1, part.Definition);
437 tp.spec.DeclaringType = part.Definition;
438 if (!tp.ResolveConstraints (part))
441 if (constraints != null)
442 return spec.HasSameConstraintsDefinition (tp.Type);
444 // Copy constraint from resolved part to partial container
445 spec.SpecialConstraint = tp.spec.SpecialConstraint;
446 spec.InterfacesDefined = tp.spec.InterfacesDefined;
447 spec.TypeArguments = tp.spec.TypeArguments;
448 spec.BaseType = tp.spec.BaseType;
453 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
455 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
458 public void CheckGenericConstraints ()
460 if (constraints != null)
461 constraints.CheckGenericConstraints (this);
464 public TypeParameter CreateHoistedCopy (TypeContainer declaringType, TypeSpec declaringSpec)
466 return new TypeParameter (spec, declaringType, declaringSpec, MemberName, null);
469 public override bool Define ()
475 // This is the first method which is called during the resolving
476 // process; we're called immediately after creating the type parameters
477 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
480 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
483 throw new InternalErrorException ();
486 spec.DeclaringType = declaringType;
487 spec.SetMetaInfo (type);
490 public void EmitConstraints (GenericTypeParameterBuilder builder)
492 var attr = GenericParameterAttributes.None;
493 if (spec.Variance == Variance.Contravariant)
494 attr |= GenericParameterAttributes.Contravariant;
495 else if (spec.Variance == Variance.Covariant)
496 attr |= GenericParameterAttributes.Covariant;
498 if (spec.HasSpecialClass)
499 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
500 else if (spec.HasSpecialStruct)
501 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
503 if (spec.HasSpecialConstructor)
504 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
506 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
507 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
509 if (spec.InterfacesDefined != null)
510 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
512 if (spec.TypeArguments != null)
513 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
515 builder.SetGenericParameterAttributes (attr);
518 public override void Emit ()
520 EmitConstraints (builder);
522 if (OptAttributes != null)
523 OptAttributes.Emit ();
528 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
530 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
531 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
532 string gtype_variance;
534 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
535 case Variance.Covariant: gtype_variance = "covariantly"; break;
536 default: gtype_variance = "invariantly"; break;
539 Delegate d = mc as Delegate;
540 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
542 Report.Error (1961, Location,
543 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
544 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
547 public TypeSpec GetAttributeCoClass ()
552 public string GetAttributeDefaultMember ()
554 throw new NotSupportedException ();
557 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
559 throw new NotSupportedException ();
562 public override string GetSignatureForDocumentation ()
564 throw new NotImplementedException ();
567 public override string GetSignatureForError ()
569 return MemberName.Name;
572 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
574 return spec.GetEffectiveBase ().MemberDefinition.DeclaringAssembly == assembly;
577 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
579 throw new NotSupportedException ("Not supported for compiled definition");
583 // Resolves all type parameter constraints
585 public bool ResolveConstraints (IMemberContext context)
587 if (constraints != null)
588 return constraints.Resolve (context, this);
590 if (spec.BaseType == null)
591 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
596 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
598 foreach (var tp in tparams) {
606 public override bool IsClsComplianceRequired ()
611 public new void VerifyClsCompliance ()
613 if (constraints != null)
614 constraints.VerifyClsCompliance (Report);
618 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
619 public class TypeParameterSpec : TypeSpec
621 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
624 SpecialConstraint spec;
627 TypeSpec[] ifaces_defined;
630 // Creates type owned type parameter
632 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
633 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
635 this.variance = variance;
637 state &= ~StateFlags.Obsolete_Undetected;
642 // Creates method owned type parameter
644 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
645 : this (null, index, definition, spec, variance, info)
651 public int DeclaredPosition {
657 public bool HasSpecialConstructor {
659 return (spec & SpecialConstraint.Constructor) != 0;
663 public bool HasSpecialClass {
665 return (spec & SpecialConstraint.Class) != 0;
669 public bool HasSpecialStruct {
671 return (spec & SpecialConstraint.Struct) != 0;
675 public bool HasTypeConstraint {
677 var bt = BaseType.BuiltinType;
678 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
682 public override IList<TypeSpec> Interfaces {
684 if ((state & StateFlags.InterfacesExpanded) == 0) {
685 if (ifaces != null) {
686 for (int i = 0; i < ifaces.Count; ++i ) {
687 var iface_type = ifaces[i];
688 if (iface_type.Interfaces != null) {
689 if (ifaces_defined == null)
690 ifaces_defined = ifaces.ToArray ();
692 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
693 var ii_iface_type = iface_type.Interfaces [ii];
695 AddInterface (ii_iface_type);
701 if (ifaces_defined == null && ifaces != null)
702 ifaces_defined = ifaces.ToArray ();
704 state |= StateFlags.InterfacesExpanded;
712 // Unexpanded interfaces list
714 public TypeSpec[] InterfacesDefined {
716 if (ifaces_defined == null && ifaces != null)
717 ifaces_defined = ifaces.ToArray ();
719 return ifaces_defined;
722 ifaces = ifaces_defined = value;
726 public bool IsConstrained {
728 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
733 // Returns whether the type parameter is "known to be a reference type"
735 public bool IsReferenceType {
737 if ((spec & SpecialConstraint.Class) != 0 || HasTypeConstraint)
741 foreach (var ta in targs) {
742 if (TypeManager.IsReferenceType (ta))
751 public bool IsValueType { // TODO: Do I need this ?
753 // TODO MemberCache: probably wrong
754 return HasSpecialStruct;
758 public override string Name {
760 return definition.Name;
764 public bool IsMethodOwned {
766 return DeclaringType == null;
770 public SpecialConstraint SpecialConstraint {
780 // Types used to inflate the generic type
782 public new TypeSpec[] TypeArguments {
791 public Variance Variance {
799 public void ChangeTypeArgumentToBaseType (int index)
801 BaseType = targs [index];
802 if (targs.Length == 1) {
805 var copy = new TypeSpec[targs.Length - 1];
807 Array.Copy (targs, copy, index);
809 Array.Copy (targs, index + 1, copy, index, targs.Length - index - 1);
814 public string DisplayDebugInfo ()
816 var s = GetSignatureForError ();
817 return IsMethodOwned ? s + "!!" : s + "!";
821 // Finds effective base class
823 public TypeSpec GetEffectiveBase ()
825 if (HasSpecialStruct)
828 if (BaseType != null && targs == null)
832 if (HasTypeConstraint) {
833 Array.Resize (ref types, types.Length + 1);
834 types[types.Length - 1] = BaseType;
838 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
843 public override string GetSignatureForDocumentation ()
846 var type = DeclaringType;
847 while (type != null && type.DeclaringType != null) {
848 type = type.DeclaringType;
849 c += type.MemberDefinition.TypeParametersCount;
852 var prefix = IsMethodOwned ? "``" : "`";
853 return prefix + (c + DeclaredPosition);
856 public override string GetSignatureForError ()
862 // Constraints have to match by definition but not position, used by
863 // partial classes or methods
865 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
867 if (spec != other.spec)
870 if (BaseType != other.BaseType)
873 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
876 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
883 // Constraints have to match by using same set of types, used by
884 // implicit interface implementation
886 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
888 if (spec != other.spec)
892 // It can be same base type or inflated type parameter
894 // interface I<T> { void Foo<U> where U : T; }
895 // class A : I<int> { void Foo<X> where X : int {} }
898 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
899 if (other.targs == null)
903 foreach (var otarg in other.targs) {
904 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
914 // Check interfaces implementation -> definition
915 if (InterfacesDefined != null) {
916 foreach (var iface in InterfacesDefined) {
918 if (other.InterfacesDefined != null) {
919 foreach (var oiface in other.InterfacesDefined) {
920 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
930 if (other.targs != null) {
931 foreach (var otarg in other.targs) {
932 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
944 // Check interfaces implementation <- definition
945 if (other.InterfacesDefined != null) {
946 if (InterfacesDefined == null)
949 foreach (var oiface in other.InterfacesDefined) {
951 foreach (var iface in InterfacesDefined) {
952 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
963 // Check type parameters implementation -> definition
965 if (other.targs == null)
968 foreach (var targ in targs) {
970 foreach (var otarg in other.targs) {
971 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
982 // Check type parameters implementation <- definition
983 if (other.targs != null) {
984 foreach (var otarg in other.targs) {
985 // Ignore inflated type arguments, were checked above
986 if (!otarg.IsGenericParameter)
993 foreach (var targ in targs) {
994 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1008 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1010 return InflateConstraints (tparams, l => l, inflator);
1013 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1015 TypeParameterSpec[] constraints = null;
1016 TypeParameterInflator? inflator = null;
1018 for (int i = 0; i < tparams.Length; ++i) {
1019 var tp = tparams[i];
1020 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1021 if (constraints == null) {
1022 constraints = new TypeParameterSpec[tparams.Length];
1023 Array.Copy (tparams, constraints, constraints.Length);
1027 // Using a factory to avoid possibly expensive inflator build up
1029 if (inflator == null)
1030 inflator = inflatorFactory (arg);
1032 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1036 if (constraints == null)
1037 constraints = tparams;
1042 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1044 tps.BaseType = inflator.Inflate (BaseType);
1045 if (ifaces != null) {
1046 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1047 for (int i = 0; i < ifaces.Count; ++i)
1048 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1051 if (targs != null) {
1052 tps.targs = new TypeSpec[targs.Length];
1053 for (int i = 0; i < targs.Length; ++i)
1054 tps.targs[i] = inflator.Inflate (targs[i]);
1058 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1060 var tps = (TypeParameterSpec) MemberwiseClone ();
1061 InflateConstraints (inflator, tps);
1066 // Populates type parameter members using type parameter constraints
1067 // The trick here is to be called late enough but not too late to
1068 // populate member cache with all members from other types
1070 protected override void InitializeMemberCache (bool onlyTypes)
1072 cache = new MemberCache ();
1075 // For a type parameter the membercache is the union of the sets of members of the types
1076 // specified as a primary constraint or secondary constraint
1078 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1079 cache.AddBaseType (BaseType);
1081 if (ifaces != null) {
1082 foreach (var iface_type in Interfaces) {
1083 cache.AddInterface (iface_type);
1087 if (targs != null) {
1088 foreach (var ta in targs) {
1089 var b_type = ta.BaseType;
1090 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1091 cache.AddBaseType (b_type);
1093 if (ta.Interfaces != null) {
1094 foreach (var iface_type in ta.Interfaces) {
1095 cache.AddInterface (iface_type);
1102 public bool IsConvertibleToInterface (TypeSpec iface)
1104 if (Interfaces != null) {
1105 foreach (var t in Interfaces) {
1111 if (TypeArguments != null) {
1112 foreach (var t in TypeArguments) {
1113 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1121 public override TypeSpec Mutate (TypeParameterMutator mutator)
1123 return mutator.Mutate (this);
1127 public struct TypeParameterInflator
1129 readonly TypeSpec type;
1130 readonly TypeParameterSpec[] tparams;
1131 readonly TypeSpec[] targs;
1132 readonly IModuleContext context;
1134 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1135 : this (nested.context, type, nested.tparams, nested.targs)
1139 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1141 if (tparams.Length != targs.Length)
1142 throw new ArgumentException ("Invalid arguments");
1144 this.context = context;
1145 this.tparams = tparams;
1152 public IModuleContext Context {
1158 public TypeSpec TypeInstance {
1165 // Type parameters to inflate
1167 public TypeParameterSpec[] TypeParameters {
1175 public TypeSpec Inflate (TypeSpec type)
1177 var tp = type as TypeParameterSpec;
1179 return Inflate (tp);
1181 var ac = type as ArrayContainer;
1183 var et = Inflate (ac.Element);
1184 if (et != ac.Element)
1185 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1191 // When inflating a nested type, inflate its parent first
1192 // in case it's using same type parameters (was inflated within the type)
1196 if (type.IsNested) {
1197 var parent = Inflate (type.DeclaringType);
1200 // Keep the inflated type arguments
1202 targs = type.TypeArguments;
1205 // Parent was inflated, find the same type on inflated type
1206 // to use same cache for nested types on same generic parent
1208 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1211 // Handle the tricky case where parent shares local type arguments
1212 // which means inflating inflated type
1215 // public static Nested<T> Foo () { return null; }
1217 // public class Nested<U> {}
1220 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1222 if (targs.Length > 0) {
1223 var inflated_targs = new TypeSpec[targs.Length];
1224 for (; i < targs.Length; ++i)
1225 inflated_targs[i] = Inflate (targs[i]);
1227 type = type.MakeGenericType (context, inflated_targs);
1233 // Nothing to do for non-generic type
1234 if (type.Arity == 0)
1237 targs = new TypeSpec[type.Arity];
1240 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1242 if (type is InflatedTypeSpec) {
1243 for (; i < targs.Length; ++i)
1244 targs[i] = Inflate (type.TypeArguments[i]);
1246 type = type.GetDefinition ();
1249 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1251 var args = type.MemberDefinition.TypeParameters;
1252 foreach (var ds_tp in args)
1253 targs[i++] = Inflate (ds_tp);
1256 return type.MakeGenericType (context, targs);
1259 public TypeSpec Inflate (TypeParameterSpec tp)
1261 for (int i = 0; i < tparams.Length; ++i)
1262 if (tparams [i] == tp)
1265 // This can happen when inflating nested types
1266 // without type arguments specified
1272 // Before emitting any code we have to change all MVAR references to VAR
1273 // when the method is of generic type and has hoisted variables
1275 public class TypeParameterMutator
1277 readonly TypeParameter[] mvar;
1278 readonly TypeParameter[] var;
1279 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1281 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1283 if (mvar.Length != var.Length)
1284 throw new ArgumentException ();
1292 public TypeParameter[] MethodTypeParameters {
1300 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1302 if (type is InflatedTypeSpec) {
1303 if (type.DeclaringType == null)
1304 return type.GetDefinition ();
1306 var parent = GetMemberDeclaringType (type.DeclaringType);
1307 type = MemberCache.GetMember<TypeSpec> (parent, type);
1313 public TypeSpec Mutate (TypeSpec ts)
1316 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1319 value = ts.Mutate (this);
1320 if (mutated_typespec == null)
1321 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1323 mutated_typespec.Add (ts, value);
1327 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1329 for (int i = 0; i < mvar.Length; ++i) {
1330 if (mvar[i].Type == tp)
1337 public TypeSpec[] Mutate (TypeSpec[] targs)
1339 TypeSpec[] mutated = new TypeSpec[targs.Length];
1340 bool changed = false;
1341 for (int i = 0; i < targs.Length; ++i) {
1342 mutated[i] = Mutate (targs[i]);
1343 changed |= targs[i] != mutated[i];
1346 return changed ? mutated : targs;
1351 /// A TypeExpr which already resolved to a type parameter.
1353 public class TypeParameterExpr : TypeExpr {
1355 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1357 this.type = type_parameter.Type;
1358 this.eclass = ExprClass.TypeParameter;
1362 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1364 throw new NotSupportedException ();
1367 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1373 public class InflatedTypeSpec : TypeSpec
1376 TypeParameterSpec[] constraints;
1377 readonly TypeSpec open_type;
1378 readonly IModuleContext context;
1380 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1381 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1384 throw new ArgumentNullException ("targs");
1386 // this.state = openType.state;
1387 this.context = context;
1388 this.open_type = openType;
1391 foreach (var arg in targs) {
1392 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1393 state |= StateFlags.HasDynamicElement;
1398 if (open_type.Kind == MemberKind.MissingType)
1399 MemberCache = MemberCache.Empty;
1404 public override TypeSpec BaseType {
1406 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1407 InitializeMemberCache (true);
1409 return base.BaseType;
1414 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1416 public TypeParameterSpec[] Constraints {
1418 if (constraints == null) {
1419 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1426 public override IList<TypeSpec> Interfaces {
1429 InitializeMemberCache (true);
1431 return base.Interfaces;
1435 public override bool IsExpressionTreeType {
1437 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1441 public override bool IsGenericIterateInterface {
1443 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1447 public override bool IsNullableType {
1449 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1454 // Types used to inflate the generic type
1456 public override TypeSpec[] TypeArguments {
1464 public static bool ContainsTypeParameter (TypeSpec type)
1466 if (type.Kind == MemberKind.TypeParameter)
1469 var element_container = type as ElementTypeSpec;
1470 if (element_container != null)
1471 return ContainsTypeParameter (element_container.Element);
1473 foreach (var t in type.TypeArguments) {
1474 if (ContainsTypeParameter (t)) {
1482 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1484 TypeParameterSpec[] tparams_full;
1485 TypeSpec[] targs_full = targs;
1488 // Special case is needed when we are inflating an open type (nested type definition)
1489 // on inflated parent. Consider following case
1491 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1493 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1495 List<TypeSpec> merged_targs = null;
1496 List<TypeParameterSpec> merged_tparams = null;
1498 var type = DeclaringType;
1501 if (type.TypeArguments.Length > 0) {
1502 if (merged_targs == null) {
1503 merged_targs = new List<TypeSpec> ();
1504 merged_tparams = new List<TypeParameterSpec> ();
1505 if (targs.Length > 0) {
1506 merged_targs.AddRange (targs);
1507 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1510 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1511 merged_targs.AddRange (type.TypeArguments);
1513 type = type.DeclaringType;
1514 } while (type != null);
1516 if (merged_targs != null) {
1517 // Type arguments are not in the right order but it should not matter in this case
1518 targs_full = merged_targs.ToArray ();
1519 tparams_full = merged_tparams.ToArray ();
1520 } else if (targs.Length == 0) {
1521 tparams_full = TypeParameterSpec.EmptyTypes;
1523 tparams_full = open_type.MemberDefinition.TypeParameters;
1525 } else if (targs.Length == 0) {
1526 tparams_full = TypeParameterSpec.EmptyTypes;
1528 tparams_full = open_type.MemberDefinition.TypeParameters;
1531 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1534 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1537 // Converts nested type arguments into right order
1538 // Foo<string, bool>.Bar<int> => string, bool, int
1540 var all = new List<MetaType> ();
1541 TypeSpec type = this;
1542 TypeSpec definition = type;
1544 if (type.GetDefinition().IsGeneric) {
1546 type.TypeArguments != TypeSpec.EmptyTypes ?
1547 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1548 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1551 definition = definition.GetDefinition ();
1552 type = type.DeclaringType;
1553 } while (type != null);
1555 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1558 public override ObsoleteAttribute GetAttributeObsolete ()
1560 return open_type.GetAttributeObsolete ();
1563 protected override bool IsNotCLSCompliant (out bool attrValue)
1565 if (base.IsNotCLSCompliant (out attrValue))
1568 foreach (var ta in TypeArguments) {
1569 if (ta.MemberDefinition.CLSAttributeValue == false)
1576 public override TypeSpec GetDefinition ()
1581 public override MetaType GetMetaInfo ()
1584 info = CreateMetaInfo (null);
1589 public override string GetSignatureForError ()
1592 return targs[0].GetSignatureForError () + "?";
1594 return base.GetSignatureForError ();
1597 protected override string GetTypeNameSignature ()
1599 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1602 return "<" + TypeManager.CSharpName (targs) + ">";
1605 protected override void InitializeMemberCache (bool onlyTypes)
1607 if (cache == null) {
1608 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1610 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1611 // for imported type parameter constraints referencing nested type of this declaration
1613 cache = new MemberCache (open_cache);
1616 var inflator = CreateLocalInflator (context);
1619 // Two stage inflate due to possible nested types recursive
1629 // When resolving type of `b' members of `B' cannot be
1630 // inflated because are not yet available in membercache
1632 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1633 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1636 // Inflate any implemented interfaces
1638 if (open_type.Interfaces != null) {
1639 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1640 foreach (var iface in open_type.Interfaces) {
1641 var iface_inflated = inflator.Inflate (iface);
1642 if (iface_inflated == null)
1645 AddInterface (iface_inflated);
1650 // Handles the tricky case of recursive nested base generic type
1652 // class A<T> : Base<A<T>.Nested> {
1656 // When inflating A<T>. base type is not yet known, secondary
1657 // inflation is required (not common case) once base scope
1660 if (open_type.BaseType == null) {
1662 state |= StateFlags.PendingBaseTypeInflate;
1664 BaseType = inflator.Inflate (open_type.BaseType);
1666 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1667 BaseType = inflator.Inflate (open_type.BaseType);
1668 state &= ~StateFlags.PendingBaseTypeInflate;
1672 state |= StateFlags.PendingMemberCacheMembers;
1676 var tc = open_type.MemberDefinition as TypeContainer;
1677 if (tc != null && !tc.HasMembersDefined)
1678 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1680 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1681 BaseType = inflator.Inflate (open_type.BaseType);
1682 state &= ~StateFlags.PendingBaseTypeInflate;
1685 state &= ~StateFlags.PendingMemberCacheMembers;
1686 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1689 public override TypeSpec Mutate (TypeParameterMutator mutator)
1691 var targs = TypeArguments;
1693 targs = mutator.Mutate (targs);
1695 var decl = DeclaringType;
1696 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1697 decl = mutator.Mutate (decl);
1699 if (targs == TypeArguments && decl == DeclaringType)
1702 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1703 if (decl != DeclaringType) {
1704 // Gets back MethodInfo in case of metaInfo was inflated
1705 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1707 mutated.declaringType = decl;
1708 mutated.state |= StateFlags.PendingMetaInflate;
1711 if (targs != null) {
1712 mutated.targs = targs;
1713 mutated.info = null;
1722 // Tracks the type arguments when instantiating a generic type. It's used
1723 // by both type arguments and type parameters
1725 public class TypeArguments
1727 List<FullNamedExpression> args;
1730 public TypeArguments (params FullNamedExpression[] types)
1732 this.args = new List<FullNamedExpression> (types);
1735 public void Add (FullNamedExpression type)
1740 // TODO: Kill this monster
1741 public TypeParameterName[] GetDeclarations ()
1743 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1747 /// We may only be used after Resolve() is called and return the fully
1750 // TODO: Not needed, just return type from resolve
1751 public TypeSpec[] Arguments {
1763 public virtual bool IsEmpty {
1769 public string GetSignatureForError()
1771 StringBuilder sb = new StringBuilder ();
1772 for (int i = 0; i < Count; ++i) {
1775 sb.Append (expr.GetSignatureForError ());
1781 return sb.ToString ();
1785 /// Resolve the type arguments.
1787 public virtual bool Resolve (IMemberContext ec)
1790 return atypes.Length != 0;
1792 int count = args.Count;
1795 atypes = new TypeSpec [count];
1797 for (int i = 0; i < count; i++){
1798 TypeExpr te = args[i].ResolveAsTypeTerminal (ec, false);
1804 atypes[i] = te.Type;
1806 if (te.Type.IsStatic) {
1807 ec.Module.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1808 te.GetSignatureForError ());
1812 if (te.Type.IsPointer || te.Type.IsSpecialRuntimeType) {
1813 ec.Module.Compiler.Report.Error (306, te.Location,
1814 "The type `{0}' may not be used as a type argument",
1815 te.GetSignatureForError ());
1821 atypes = TypeSpec.EmptyTypes;
1826 public TypeArguments Clone ()
1828 TypeArguments copy = new TypeArguments ();
1829 foreach (var ta in args)
1836 public class UnboundTypeArguments : TypeArguments
1838 public UnboundTypeArguments (int arity)
1839 : base (new FullNamedExpression[arity])
1843 public override bool IsEmpty {
1849 public override bool Resolve (IMemberContext ec)
1851 // Nothing to be resolved
1856 public class TypeParameterName : SimpleName
1858 Attributes attributes;
1861 public TypeParameterName (string name, Attributes attrs, Location loc)
1862 : this (name, attrs, Variance.None, loc)
1866 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1870 this.variance = variance;
1873 public Attributes OptAttributes {
1879 public Variance Variance {
1887 // A type expression of generic type with type arguments
1889 class GenericTypeExpr : TypeExpr
1893 bool constraints_checked;
1896 /// Instantiate the generic type `t' with the type arguments `args'.
1897 /// Use this constructor if you already know the fully resolved
1900 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1902 this.open_type = open_type;
1907 public TypeArguments TypeArguments {
1908 get { return args; }
1911 public override string GetSignatureForError ()
1913 return TypeManager.CSharpName (type);
1916 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1918 if (!args.Resolve (ec))
1921 TypeSpec[] atypes = args.Arguments;
1924 // Now bind the parameters
1926 type = open_type.MakeGenericType (ec, atypes);
1929 // Check constraints when context is not method/base type
1931 if (!ec.HasUnresolvedConstraints)
1932 CheckConstraints (ec);
1938 // Checks the constraints of open generic type against type
1939 // arguments. Has to be called after all members have been defined
1941 public bool CheckConstraints (IMemberContext ec)
1943 if (constraints_checked)
1946 constraints_checked = true;
1948 if ((type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1951 var gtype = (InflatedTypeSpec) type;
1952 var constraints = gtype.Constraints;
1953 if (constraints == null)
1956 return new ConstraintChecker(ec).CheckAll (open_type, args.Arguments, constraints, loc);
1959 public bool HasDynamicArguments ()
1961 return HasDynamicArguments (args.Arguments);
1964 static bool HasDynamicArguments (TypeSpec[] args)
1966 for (int i = 0; i < args.Length; ++i) {
1969 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1972 if (TypeManager.IsGenericType (item))
1973 return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1976 while (item.IsArray) {
1977 item = ((ArrayContainer) item).Element;
1980 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1988 public override bool Equals (object obj)
1990 GenericTypeExpr cobj = obj as GenericTypeExpr;
1994 if ((type == null) || (cobj.type == null))
1997 return type == cobj.type;
2000 public override int GetHashCode ()
2002 return base.GetHashCode ();
2007 // Generic type with unbound type arguments, used for typeof (G<,,>)
2009 class GenericOpenTypeExpr : TypeExpr
2011 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2013 this.type = type.GetDefinition ();
2017 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
2023 struct ConstraintChecker
2026 bool ignore_inferred_dynamic;
2028 public ConstraintChecker (IMemberContext ctx)
2031 ignore_inferred_dynamic = false;
2036 public bool IgnoreInferredDynamic {
2038 return ignore_inferred_dynamic;
2041 ignore_inferred_dynamic = value;
2048 // Checks all type arguments againts type parameters constraints
2049 // NOTE: It can run in probing mode when `mc' is null
2051 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2053 for (int i = 0; i < tparams.Length; i++) {
2054 if (ignore_inferred_dynamic && targs[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2057 if (!CheckConstraint (context, targs [i], tparams [i], loc))
2064 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2067 // First, check the `class' and `struct' constraints.
2069 if (tparam.HasSpecialClass && !TypeManager.IsReferenceType (atype)) {
2071 mc.Module.Compiler.Report.Error (452, loc,
2072 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2073 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2079 if (tparam.HasSpecialStruct && (!TypeManager.IsValueType (atype) || atype.IsNullableType)) {
2081 mc.Module.Compiler.Report.Error (453, loc,
2082 "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}'",
2083 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2092 // Check the class constraint
2094 if (tparam.HasTypeConstraint) {
2095 var dep = tparam.BaseType.GetMissingDependencies ();
2100 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2104 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2113 // Check the interfaces constraints
2115 if (tparam.Interfaces != null) {
2116 if (atype.IsNullableType) {
2120 mc.Module.Compiler.Report.Error (313, loc,
2121 "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",
2122 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2125 foreach (TypeSpec iface in tparam.Interfaces) {
2126 var dep = iface.GetMissingDependencies ();
2131 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2134 // return immediately to avoid duplicate errors because we are scanning
2135 // expanded interface list
2139 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2150 // Check the type parameter constraint
2152 if (tparam.TypeArguments != null) {
2153 foreach (var ta in tparam.TypeArguments) {
2154 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2164 // Finally, check the constructor constraint.
2166 if (!tparam.HasSpecialConstructor)
2169 if (!HasDefaultConstructor (atype)) {
2171 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2172 mc.Module.Compiler.Report.Error (310, loc,
2173 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2174 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2182 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2184 for (int i = 0; i < targs.Length; ++i) {
2185 var targ = targs [i];
2186 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2189 if (HasDynamicTypeArgument (targ.TypeArguments))
2196 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2198 if (TypeManager.IsValueType (atype)) {
2199 if (atype == ttype || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2202 if (atype.IsGenericParameter) {
2203 if (Convert.ImplicitTypeParameterConversion (null, (TypeParameterSpec) atype, ttype) != null)
2207 var expr = new EmptyExpression (atype);
2208 if (Convert.ImplicitStandardConversionExists (expr, ttype))
2213 // When partial/full type inference finds a dynamic type argument delay
2214 // the constraint check to runtime, it can succeed for real underlying
2217 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2221 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2222 if (TypeManager.IsValueType (atype)) {
2223 mc.Module.Compiler.Report.Error (315, loc,
2224 "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}'",
2225 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2226 } else if (atype.IsGenericParameter) {
2227 mc.Module.Compiler.Report.Error (314, loc,
2228 "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}'",
2229 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2231 mc.Module.Compiler.Report.Error (311, loc,
2232 "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}'",
2233 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2240 bool HasDefaultConstructor (TypeSpec atype)
2242 var tp = atype as TypeParameterSpec;
2244 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2247 if (atype.IsStruct || atype.IsEnum)
2250 if (atype.IsAbstract)
2253 var tdef = atype.GetDefinition ();
2256 // In some circumstances MemberCache is not yet populated and members
2257 // cannot be defined yet (recursive type new constraints)
2259 // class A<T> where T : B<T>, new () {}
2260 // class B<T> where T : A<T>, new () {}
2262 var tc = tdef.MemberDefinition as Class;
2264 if (tc.InstanceConstructors == null) {
2265 // Default ctor will be generated later
2269 foreach (var c in tc.InstanceConstructors) {
2270 if (c.ParameterInfo.IsEmpty) {
2271 if ((c.ModFlags & Modifiers.PUBLIC) != 0)
2279 var found = MemberCache.FindMember (tdef,
2280 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2281 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2283 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2288 /// A generic method definition.
2290 public class GenericMethod : DeclSpace
2292 ParametersCompiled parameters;
2294 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
2295 FullNamedExpression return_type, ParametersCompiled parameters)
2296 : base (ns, parent, name, null)
2298 this.parameters = parameters;
2301 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2302 FullNamedExpression return_type, ParametersCompiled parameters)
2303 : this (ns, parent, name, return_type, parameters)
2305 this.type_params = tparams;
2308 public override TypeParameter[] CurrentTypeParameters {
2310 return base.type_params;
2314 protected override TypeAttributes TypeAttr {
2316 throw new NotSupportedException ();
2320 public override void DefineType ()
2322 throw new Exception ();
2325 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2327 throw new NotSupportedException ();
2330 public override bool Define ()
2332 throw new NotSupportedException ();
2336 /// Define and resolve the type parameters.
2337 /// We're called from Method.Define().
2339 public bool Define (MethodOrOperator m)
2341 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2342 string[] snames = new string [names.Length];
2343 var block = m.Block;
2344 for (int i = 0; i < names.Length; i++) {
2345 string type_argument_name = names[i].Name;
2347 if (block == null) {
2348 int idx = parameters.GetParameterIndexByName (type_argument_name);
2352 b = new ToplevelBlock (Compiler, Location);
2354 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2357 INamedBlockVariable variable = null;
2358 block.GetLocalName (type_argument_name, m.Block, ref variable);
2359 if (variable != null)
2360 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2363 snames[i] = type_argument_name;
2366 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2367 for (int i = 0; i < TypeParameters.Length; i++)
2368 TypeParameters [i].Define (gen_params [i], null);
2373 public void EmitAttributes ()
2375 if (OptAttributes != null)
2376 OptAttributes.Emit ();
2379 public override string GetSignatureForError ()
2381 return base.GetSignatureForError () + parameters.GetSignatureForError ();
2384 public override AttributeTargets AttributeTargets {
2386 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2390 public override string DocCommentHeader {
2391 get { return "M:"; }
2394 public new void VerifyClsCompliance ()
2396 foreach (TypeParameter tp in TypeParameters) {
2397 tp.VerifyClsCompliance ();
2402 public partial class TypeManager
2404 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2406 var tp = t as TypeParameterSpec;
2408 Variance v = tp.Variance;
2409 if (expected == Variance.None && v != expected ||
2410 expected == Variance.Covariant && v == Variance.Contravariant ||
2411 expected == Variance.Contravariant && v == Variance.Covariant) {
2412 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2418 if (t.TypeArguments.Length > 0) {
2419 var targs_definition = t.MemberDefinition.TypeParameters;
2420 TypeSpec[] targs = GetTypeArguments (t);
2421 for (int i = 0; i < targs.Length; ++i) {
2422 Variance v = targs_definition[i].Variance;
2423 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2430 return CheckTypeVariance (GetElementType (t), expected, member);
2432 return Variance.None;
2437 // Implements C# type inference
2442 // Tracks successful rate of type inference
2444 int score = int.MaxValue;
2445 readonly Arguments arguments;
2446 readonly int arg_count;
2448 public TypeInference (Arguments arguments)
2450 this.arguments = arguments;
2451 if (arguments != null)
2452 arg_count = arguments.Count;
2455 public int InferenceScore {
2461 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2463 var method_generic_args = method.GenericDefinition.TypeParameters;
2464 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2465 if (!context.UnfixedVariableExists)
2466 return TypeSpec.EmptyTypes;
2468 AParametersCollection pd = method.Parameters;
2469 if (!InferInPhases (ec, context, pd))
2472 return context.InferredTypeArguments;
2476 // Implements method type arguments inference
2478 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2480 int params_arguments_start;
2481 if (methodParameters.HasParams) {
2482 params_arguments_start = methodParameters.Count - 1;
2484 params_arguments_start = arg_count;
2487 TypeSpec [] ptypes = methodParameters.Types;
2490 // The first inference phase
2492 TypeSpec method_parameter = null;
2493 for (int i = 0; i < arg_count; i++) {
2494 Argument a = arguments [i];
2498 if (i < params_arguments_start) {
2499 method_parameter = methodParameters.Types [i];
2500 } else if (i == params_arguments_start) {
2501 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2502 method_parameter = methodParameters.Types [params_arguments_start];
2504 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2506 ptypes = (TypeSpec[]) ptypes.Clone ();
2507 ptypes [i] = method_parameter;
2511 // When a lambda expression, an anonymous method
2512 // is used an explicit argument type inference takes a place
2514 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2516 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2522 score -= tic.ExactInference (a.Type, method_parameter);
2526 if (a.Expr.Type == InternalType.NullLiteral)
2529 if (TypeManager.IsValueType (method_parameter)) {
2530 score -= tic.LowerBoundInference (a.Type, method_parameter);
2535 // Otherwise an output type inference is made
2537 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2541 // Part of the second phase but because it happens only once
2542 // we don't need to call it in cycle
2544 bool fixed_any = false;
2545 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2548 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2551 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2553 bool fixed_any = false;
2554 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2557 // If no further unfixed type variables exist, type inference succeeds
2558 if (!tic.UnfixedVariableExists)
2561 if (!fixed_any && fixDependent)
2564 // For all arguments where the corresponding argument output types
2565 // contain unfixed type variables but the input types do not,
2566 // an output type inference is made
2567 for (int i = 0; i < arg_count; i++) {
2569 // Align params arguments
2570 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2572 if (!TypeManager.IsDelegateType (t_i)) {
2573 if (!t_i.IsExpressionTreeType)
2576 t_i = TypeManager.GetTypeArguments (t_i) [0];
2579 var mi = Delegate.GetInvokeMethod (t_i);
2580 TypeSpec rtype = mi.ReturnType;
2582 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2583 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2587 return DoSecondPhase (ec, tic, methodParameters, true);
2591 public class TypeInferenceContext
2593 protected enum BoundKind
2600 protected class BoundInfo : IEquatable<BoundInfo>
2602 public readonly TypeSpec Type;
2603 public readonly BoundKind Kind;
2605 public BoundInfo (TypeSpec type, BoundKind kind)
2611 public override int GetHashCode ()
2613 return Type.GetHashCode ();
2616 public virtual Expression GetTypeExpression ()
2618 return new TypeExpression (Type, Location.Null);
2621 #region IEquatable<BoundInfo> Members
2623 public virtual bool Equals (BoundInfo other)
2625 return Type == other.Type && Kind == other.Kind;
2631 readonly TypeSpec[] tp_args;
2632 readonly TypeSpec[] fixed_types;
2633 readonly List<BoundInfo>[] bounds;
2636 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2637 public TypeInferenceContext (TypeSpec[] typeArguments)
2639 if (typeArguments.Length == 0)
2640 throw new ArgumentException ("Empty generic arguments");
2642 fixed_types = new TypeSpec [typeArguments.Length];
2643 for (int i = 0; i < typeArguments.Length; ++i) {
2644 if (typeArguments [i].IsGenericParameter) {
2645 if (bounds == null) {
2646 bounds = new List<BoundInfo> [typeArguments.Length];
2647 tp_args = new TypeSpec [typeArguments.Length];
2649 tp_args [i] = typeArguments [i];
2651 fixed_types [i] = typeArguments [i];
2657 // Used together with AddCommonTypeBound fo implement
2658 // 7.4.2.13 Finding the best common type of a set of expressions
2660 public TypeInferenceContext ()
2662 fixed_types = new TypeSpec [1];
2663 tp_args = new TypeSpec [1];
2664 tp_args[0] = InternalType.Arglist; // it can be any internal type
2665 bounds = new List<BoundInfo> [1];
2668 public TypeSpec[] InferredTypeArguments {
2674 public void AddCommonTypeBound (TypeSpec type)
2676 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2679 protected void AddToBounds (BoundInfo bound, int index)
2682 // Some types cannot be used as type arguments
2684 if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer)
2687 var a = bounds [index];
2689 a = new List<BoundInfo> (2);
2695 if (a.Contains (bound))
2701 bool AllTypesAreFixed (TypeSpec[] types)
2703 foreach (TypeSpec t in types) {
2704 if (t.IsGenericParameter) {
2710 if (TypeManager.IsGenericType (t))
2711 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2718 // 26.3.3.8 Exact Inference
2720 public int ExactInference (TypeSpec u, TypeSpec v)
2722 // If V is an array type
2727 // TODO MemberCache: GetMetaInfo ()
2728 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2731 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2734 // If V is constructed type and U is constructed type
2735 if (TypeManager.IsGenericType (v)) {
2736 if (!TypeManager.IsGenericType (u))
2739 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2740 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2741 if (ga_u.Length != ga_v.Length)
2745 for (int i = 0; i < ga_u.Length; ++i)
2746 score += ExactInference (ga_u [i], ga_v [i]);
2748 return score > 0 ? 1 : 0;
2751 // If V is one of the unfixed type arguments
2752 int pos = IsUnfixed (v);
2756 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2760 public bool FixAllTypes (ResolveContext ec)
2762 for (int i = 0; i < tp_args.Length; ++i) {
2763 if (!FixType (ec, i))
2770 // All unfixed type variables Xi are fixed for which all of the following hold:
2771 // a, There is at least one type variable Xj that depends on Xi
2772 // b, Xi has a non-empty set of bounds
2774 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2776 for (int i = 0; i < tp_args.Length; ++i) {
2777 if (fixed_types[i] != null)
2780 if (bounds[i] == null)
2783 if (!FixType (ec, i))
2793 // All unfixed type variables Xi which depend on no Xj are fixed
2795 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2797 var types_to_fix = new List<TypeSpec> (tp_args);
2798 for (int i = 0; i < methodParameters.Length; ++i) {
2799 TypeSpec t = methodParameters[i];
2801 if (!TypeManager.IsDelegateType (t)) {
2802 if (!t.IsExpressionTreeType)
2805 t = TypeManager.GetTypeArguments (t) [0];
2808 if (t.IsGenericParameter)
2811 var invoke = Delegate.GetInvokeMethod (t);
2812 TypeSpec rtype = invoke.ReturnType;
2813 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2816 // Remove dependent types, they cannot be fixed yet
2817 RemoveDependentTypes (types_to_fix, rtype);
2820 foreach (TypeSpec t in types_to_fix) {
2824 int idx = IsUnfixed (t);
2825 if (idx >= 0 && !FixType (ec, idx)) {
2830 fixed_any = types_to_fix.Count > 0;
2837 public bool FixType (ResolveContext ec, int i)
2839 // It's already fixed
2840 if (fixed_types[i] != null)
2841 throw new InternalErrorException ("Type argument has been already fixed");
2846 var candidates = bounds [i];
2847 if (candidates == null)
2850 if (candidates.Count == 1) {
2851 TypeSpec t = candidates[0].Type;
2852 if (t == InternalType.NullLiteral)
2855 fixed_types [i] = t;
2860 // Determines a unique type from which there is
2861 // a standard implicit conversion to all the other
2864 TypeSpec best_candidate = null;
2866 int candidates_count = candidates.Count;
2867 for (int ci = 0; ci < candidates_count; ++ci) {
2868 BoundInfo bound = candidates [ci];
2869 for (cii = 0; cii < candidates_count; ++cii) {
2873 BoundInfo cbound = candidates[cii];
2875 // Same type parameters with different bounds
2876 if (cbound.Type == bound.Type) {
2877 if (bound.Kind != BoundKind.Exact)
2883 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2884 if (cbound.Kind == BoundKind.Lower) {
2885 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2891 if (cbound.Kind == BoundKind.Upper) {
2892 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2899 if (bound.Kind != BoundKind.Exact) {
2900 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2911 if (bound.Kind == BoundKind.Lower) {
2912 if (cbound.Kind == BoundKind.Lower) {
2913 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2917 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2927 if (bound.Kind == BoundKind.Upper) {
2928 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2932 throw new NotImplementedException ("variance conversion");
2936 if (cii != candidates_count)
2940 // We already have the best candidate, break if thet are different
2942 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
2944 if (best_candidate != null) {
2946 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2949 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
2953 best_candidate = bound.Type;
2956 if (best_candidate == null)
2959 fixed_types[i] = best_candidate;
2964 // Uses inferred or partially infered types to inflate delegate type argument. Returns
2965 // null when type parameter has not been fixed
2967 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
2969 var tp = parameter as TypeParameterSpec;
2972 // Type inference works on generic arguments (MVAR) only
2974 if (!tp.IsMethodOwned)
2978 // Ensure the type parameter belongs to same container
2980 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
2981 return fixed_types[tp.DeclaredPosition] ?? parameter;
2986 var gt = parameter as InflatedTypeSpec;
2988 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
2989 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
2990 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
2991 if (inflated == null)
2994 inflated_targs[ii] = inflated;
2997 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3004 // Tests whether all delegate input arguments are fixed and generic output type
3005 // requires output type inference
3007 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3009 if (returnType.IsGenericParameter) {
3010 if (IsFixed (returnType))
3012 } else if (TypeManager.IsGenericType (returnType)) {
3013 if (TypeManager.IsDelegateType (returnType)) {
3014 invoke = Delegate.GetInvokeMethod (returnType);
3015 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3018 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3020 // At least one unfixed return type has to exist
3021 if (AllTypesAreFixed (g_args))
3027 // All generic input arguments have to be fixed
3028 AParametersCollection d_parameters = invoke.Parameters;
3029 return AllTypesAreFixed (d_parameters.Types);
3032 bool IsFixed (TypeSpec type)
3034 return IsUnfixed (type) == -1;
3037 int IsUnfixed (TypeSpec type)
3039 if (!type.IsGenericParameter)
3042 for (int i = 0; i < tp_args.Length; ++i) {
3043 if (tp_args[i] == type) {
3044 if (fixed_types[i] != null)
3055 // 26.3.3.9 Lower-bound Inference
3057 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3059 return LowerBoundInference (u, v, false);
3063 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3065 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3067 // If V is one of the unfixed type arguments
3068 int pos = IsUnfixed (v);
3070 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3074 // If U is an array type
3075 var u_ac = u as ArrayContainer;
3077 var v_ac = v as ArrayContainer;
3079 if (u_ac.Rank != v_ac.Rank)
3082 if (TypeManager.IsValueType (u_ac.Element))
3083 return ExactInference (u_ac.Element, v_ac.Element);
3085 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3088 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3091 var v_i = TypeManager.GetTypeArguments (v) [0];
3092 if (TypeManager.IsValueType (u_ac.Element))
3093 return ExactInference (u_ac.Element, v_i);
3095 return LowerBoundInference (u_ac.Element, v_i);
3098 if (TypeManager.IsGenericType (v)) {
3100 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3101 // such that U is identical to, inherits from (directly or indirectly),
3102 // or implements (directly or indirectly) C<U1..Uk>
3104 var u_candidates = new List<TypeSpec> ();
3105 var open_v = v.MemberDefinition;
3107 for (TypeSpec t = u; t != null; t = t.BaseType) {
3108 if (open_v == t.MemberDefinition)
3109 u_candidates.Add (t);
3112 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3113 // that would complicate the process a lot, instead I treat them as dynamic
3115 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3116 u_candidates.Add (t);
3118 if (t.Interfaces != null) {
3119 foreach (var iface in t.Interfaces) {
3120 if (open_v == iface.MemberDefinition)
3121 u_candidates.Add (iface);
3126 TypeSpec [] unique_candidate_targs = null;
3127 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
3128 foreach (TypeSpec u_candidate in u_candidates) {
3130 // The unique set of types U1..Uk means that if we have an interface I<T>,
3131 // class U : I<int>, I<long> then no type inference is made when inferring
3132 // type I<T> by applying type U because T could be int or long
3134 if (unique_candidate_targs != null) {
3135 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3136 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3137 unique_candidate_targs = second_unique_candidate_targs;
3142 // This should always cause type inference failure
3149 // A candidate is dynamic type expression, to simplify things use dynamic
3150 // for all type parameter of this type. For methods like this one
3152 // void M<T, U> (IList<T>, IList<U[]>)
3154 // dynamic becomes both T and U when the arguments are of dynamic type
3156 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3157 unique_candidate_targs = new TypeSpec[ga_v.Length];
3158 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3159 unique_candidate_targs[i] = u_candidate;
3161 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3165 if (unique_candidate_targs != null) {
3166 var ga_open_v = open_v.TypeParameters;
3168 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3169 Variance variance = ga_open_v [i].Variance;
3171 TypeSpec u_i = unique_candidate_targs [i];
3172 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
3173 if (ExactInference (u_i, ga_v [i]) == 0)
3176 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3177 (variance == Variance.Covariant && inversed);
3179 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3191 // 26.3.3.6 Output Type Inference
3193 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3195 // If e is a lambda or anonymous method with inferred return type
3196 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3198 TypeSpec rt = ame.InferReturnType (ec, this, t);
3199 var invoke = Delegate.GetInvokeMethod (t);
3202 AParametersCollection pd = invoke.Parameters;
3203 return ame.Parameters.Count == pd.Count ? 1 : 0;
3206 TypeSpec rtype = invoke.ReturnType;
3207 return LowerBoundInference (rt, rtype) + 1;
3211 // if E is a method group and T is a delegate type or expression tree type
3212 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3213 // resolution of E with the types T1..Tk yields a single method with return type U,
3214 // then a lower-bound inference is made from U for Tb.
3216 if (e is MethodGroupExpr) {
3217 if (!TypeManager.IsDelegateType (t)) {
3218 if (!t.IsExpressionTreeType)
3221 t = TypeManager.GetTypeArguments (t)[0];
3224 var invoke = Delegate.GetInvokeMethod (t);
3225 TypeSpec rtype = invoke.ReturnType;
3227 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3230 // LAMESPEC: Standard does not specify that all methodgroup arguments
3231 // has to be fixed but it does not specify how to do recursive type inference
3232 // either. We choose the simple option and infer return type only
3233 // if all delegate generic arguments are fixed.
3234 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3235 for (int i = 0; i < param_types.Length; ++i) {
3236 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3237 if (inflated == null)
3240 if (IsUnfixed (inflated) >= 0)
3243 param_types[i] = inflated;
3246 MethodGroupExpr mg = (MethodGroupExpr) e;
3247 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3248 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3252 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3256 // if e is an expression with type U, then
3257 // a lower-bound inference is made from U for T
3259 return LowerBoundInference (e.Type, t) * 2;
3262 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3264 int idx = IsUnfixed (returnType);
3270 if (TypeManager.IsGenericType (returnType)) {
3271 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3272 RemoveDependentTypes (types, t);
3277 public bool UnfixedVariableExists {
3279 foreach (TypeSpec ut in fixed_types) {