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 = TypeManager.object_type;
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 = TypeManager.value_type;
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 if (type == InternalType.Dynamic) {
271 context.Module.Compiler.Report.Error (1967, constraint.Location, "A constraint cannot be the dynamic type");
275 if (type.IsSealed || !type.IsClass) {
276 context.Module.Compiler.Report.Error (701, loc,
277 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
278 TypeManager.CSharpName (type));
283 context.Module.Compiler.Report.Error (717, constraint.Location,
284 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
285 type.GetSignatureForError ());
286 } else if (type == TypeManager.array_type || type == TypeManager.delegate_type ||
287 type == TypeManager.enum_type || type == TypeManager.value_type ||
288 type == TypeManager.object_type || type == TypeManager.multicast_delegate_type) {
289 context.Module.Compiler.Report.Error (702, constraint.Location,
290 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
294 spec.BaseType = type;
297 if (tparam_types != null)
298 spec.TypeArguments = tparam_types.ToArray ();
305 public void VerifyClsCompliance (Report report)
307 foreach (var c in constraints)
312 if (!c.Type.IsCLSCompliant ()) {
313 report.SymbolRelatedToPreviousError (c.Type);
314 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
315 c.Type.GetSignatureForError ());
322 // A type parameter for a generic type or generic method definition
324 public class TypeParameter : MemberCore, ITypeDefinition
326 static readonly string[] attribute_target = new string [] { "type parameter" };
328 Constraints constraints;
329 GenericTypeParameterBuilder builder;
330 TypeParameterSpec spec;
332 public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
333 : base (parent, name, attrs)
335 this.constraints = constraints;
336 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
339 public TypeParameter (TypeParameterSpec spec, DeclSpace parent, TypeSpec parentSpec, MemberName name, Attributes attrs)
340 : base (parent, name, attrs)
342 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
343 BaseType = spec.BaseType,
344 InterfacesDefined = spec.InterfacesDefined,
345 TypeArguments = spec.TypeArguments
351 public override AttributeTargets AttributeTargets {
353 return AttributeTargets.GenericParameter;
357 public IAssemblyDefinition DeclaringAssembly {
359 return Module.DeclaringAssembly;
363 public override string DocCommentHeader {
365 throw new InvalidOperationException (
366 "Unexpected attempt to get doc comment from " + this.GetType ());
370 public bool IsMethodTypeParameter {
372 return spec.IsMethodOwned;
376 public string Namespace {
382 public TypeParameterSpec Type {
388 public int TypeParametersCount {
394 public TypeParameterSpec[] TypeParameters {
400 public override string[] ValidAttributeTargets {
402 return attribute_target;
406 public Variance Variance {
408 return spec.Variance;
415 // This is called for each part of a partial generic type definition.
417 // If partial type parameters constraints are not null and we don't
418 // already have constraints they become our constraints. If we already
419 // have constraints, we must check that they're the same.
421 public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
424 throw new InvalidOperationException ();
426 var new_constraints = tp.constraints;
427 if (new_constraints == null)
430 // TODO: could create spec only
431 //tp.Define (null, -1, part.Definition);
432 tp.spec.DeclaringType = part.Definition;
433 if (!tp.ResolveConstraints (part))
436 if (constraints != null)
437 return spec.HasSameConstraintsDefinition (tp.Type);
439 // Copy constraint from resolved part to partial container
440 spec.SpecialConstraint = tp.spec.SpecialConstraint;
441 spec.InterfacesDefined = tp.spec.InterfacesDefined;
442 spec.TypeArguments = tp.spec.TypeArguments;
443 spec.BaseType = tp.spec.BaseType;
448 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
450 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
453 public void CheckGenericConstraints ()
455 if (constraints != null)
456 constraints.CheckGenericConstraints (this);
459 public TypeParameter CreateHoistedCopy (TypeContainer declaringType, TypeSpec declaringSpec)
461 return new TypeParameter (spec, declaringType, declaringSpec, MemberName, null);
464 public override bool Define ()
470 // This is the first method which is called during the resolving
471 // process; we're called immediately after creating the type parameters
472 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
475 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
478 throw new InternalErrorException ();
481 spec.DeclaringType = declaringType;
482 spec.SetMetaInfo (type);
485 public void EmitConstraints (GenericTypeParameterBuilder builder)
487 var attr = GenericParameterAttributes.None;
488 if (spec.Variance == Variance.Contravariant)
489 attr |= GenericParameterAttributes.Contravariant;
490 else if (spec.Variance == Variance.Covariant)
491 attr |= GenericParameterAttributes.Covariant;
493 if (spec.HasSpecialClass)
494 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
495 else if (spec.HasSpecialStruct)
496 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
498 if (spec.HasSpecialConstructor)
499 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
501 if (spec.BaseType != TypeManager.object_type)
502 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
504 if (spec.InterfacesDefined != null)
505 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
507 if (spec.TypeArguments != null)
508 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
510 builder.SetGenericParameterAttributes (attr);
513 public override void Emit ()
515 EmitConstraints (builder);
517 if (OptAttributes != null)
518 OptAttributes.Emit ();
523 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
525 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
526 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
527 string gtype_variance;
529 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
530 case Variance.Covariant: gtype_variance = "covariantly"; break;
531 default: gtype_variance = "invariantly"; break;
534 Delegate d = mc as Delegate;
535 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
537 Report.Error (1961, Location,
538 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
539 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
542 public TypeSpec GetAttributeCoClass ()
547 public string GetAttributeDefaultMember ()
549 throw new NotSupportedException ();
552 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
554 throw new NotSupportedException ();
557 public override string GetSignatureForError ()
559 return MemberName.Name;
562 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
564 throw new NotImplementedException ();
567 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
569 throw new NotSupportedException ("Not supported for compiled definition");
573 // Resolves all type parameter constraints
575 public bool ResolveConstraints (IMemberContext context)
577 if (constraints != null)
578 return constraints.Resolve (context, this);
580 if (spec.BaseType == null)
581 spec.BaseType = TypeManager.object_type;
586 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
588 foreach (var tp in tparams) {
596 public override bool IsClsComplianceRequired ()
601 public new void VerifyClsCompliance ()
603 if (constraints != null)
604 constraints.VerifyClsCompliance (Report);
608 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
609 public class TypeParameterSpec : TypeSpec
611 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
614 SpecialConstraint spec;
617 TypeSpec[] ifaces_defined;
620 // Creates type owned type parameter
622 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
623 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
625 this.variance = variance;
627 state &= ~StateFlags.Obsolete_Undetected;
632 // Creates method owned type parameter
634 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
635 : this (null, index, definition, spec, variance, info)
641 public int DeclaredPosition {
647 public bool HasSpecialConstructor {
649 return (spec & SpecialConstraint.Constructor) != 0;
653 public bool HasSpecialClass {
655 return (spec & SpecialConstraint.Class) != 0;
659 public bool HasSpecialStruct {
661 return (spec & SpecialConstraint.Struct) != 0;
665 public bool HasTypeConstraint {
667 return BaseType != TypeManager.object_type && BaseType != TypeManager.value_type;
671 public override IList<TypeSpec> Interfaces {
673 if ((state & StateFlags.InterfacesExpanded) == 0) {
674 if (ifaces != null) {
675 for (int i = 0; i < ifaces.Count; ++i ) {
676 var iface_type = ifaces[i];
677 if (iface_type.Interfaces != null) {
678 if (ifaces_defined == null)
679 ifaces_defined = ifaces.ToArray ();
681 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
682 var ii_iface_type = iface_type.Interfaces [ii];
684 AddInterface (ii_iface_type);
690 if (ifaces_defined == null && ifaces != null)
691 ifaces_defined = ifaces.ToArray ();
693 state |= StateFlags.InterfacesExpanded;
701 // Unexpanded interfaces list
703 public TypeSpec[] InterfacesDefined {
705 if (ifaces_defined == null && ifaces != null)
706 ifaces_defined = ifaces.ToArray ();
708 return ifaces_defined;
711 ifaces_defined = value;
715 public bool IsConstrained {
717 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
722 // Returns whether the type parameter is "known to be a reference type"
724 public bool IsReferenceType {
726 if ((spec & SpecialConstraint.Class) != 0 || HasTypeConstraint)
730 foreach (var ta in targs) {
731 if (TypeManager.IsReferenceType (ta))
740 public bool IsValueType { // TODO: Do I need this ?
742 // TODO MemberCache: probably wrong
743 return HasSpecialStruct;
747 public override string Name {
749 return definition.Name;
753 public bool IsMethodOwned {
755 return DeclaringType == null;
759 public SpecialConstraint SpecialConstraint {
769 // Types used to inflate the generic type
771 public new TypeSpec[] TypeArguments {
780 public Variance Variance {
788 public void ChangeTypeArgumentToBaseType (int index)
790 BaseType = targs [index];
791 if (targs.Length == 1) {
794 var copy = new TypeSpec[targs.Length - 1];
796 Array.Copy (targs, copy, index);
798 Array.Copy (targs, index + 1, copy, index, targs.Length - index - 1);
803 public string DisplayDebugInfo ()
805 var s = GetSignatureForError ();
806 return IsMethodOwned ? s + "!!" : s + "!";
810 // Finds effective base class
812 public TypeSpec GetEffectiveBase ()
814 if (HasSpecialStruct) {
815 return TypeManager.value_type;
818 if (BaseType != null && targs == null)
822 if (HasTypeConstraint) {
823 Array.Resize (ref types, types.Length + 1);
824 types[types.Length - 1] = BaseType;
828 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
830 return TypeManager.object_type;
833 public override string GetSignatureForError ()
839 // Constraints have to match by definition but not position, used by
840 // partial classes or methods
842 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
844 if (spec != other.spec)
847 if (BaseType != other.BaseType)
850 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
853 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
860 // Constraints have to match by using same set of types, used by
861 // implicit interface implementation
863 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
865 if (spec != other.spec)
869 // It can be same base type or inflated type parameter
871 // interface I<T> { void Foo<U> where U : T; }
872 // class A : I<int> { void Foo<X> where X : int {} }
875 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
876 if (other.targs == null)
880 foreach (var otarg in other.targs) {
881 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
891 // Check interfaces implementation -> definition
892 if (InterfacesDefined != null) {
893 foreach (var iface in InterfacesDefined) {
895 if (other.InterfacesDefined != null) {
896 foreach (var oiface in other.InterfacesDefined) {
897 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
907 if (other.targs != null) {
908 foreach (var otarg in other.targs) {
909 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
921 // Check interfaces implementation <- definition
922 if (other.InterfacesDefined != null) {
923 if (InterfacesDefined == null)
926 foreach (var oiface in other.InterfacesDefined) {
928 foreach (var iface in InterfacesDefined) {
929 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
940 // Check type parameters implementation -> definition
942 if (other.targs == null)
945 foreach (var targ in targs) {
947 foreach (var otarg in other.targs) {
948 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
959 // Check type parameters implementation <- definition
960 if (other.targs != null) {
961 foreach (var otarg in other.targs) {
962 // Ignore inflated type arguments, were checked above
963 if (!otarg.IsGenericParameter)
970 foreach (var targ in targs) {
971 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
985 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
987 return InflateConstraints (tparams, l => l, inflator);
990 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
992 TypeParameterSpec[] constraints = null;
993 TypeParameterInflator? inflator = null;
995 for (int i = 0; i < tparams.Length; ++i) {
997 if (tp.HasTypeConstraint || tp.Interfaces != null || tp.TypeArguments != null) {
998 if (constraints == null) {
999 constraints = new TypeParameterSpec[tparams.Length];
1000 Array.Copy (tparams, constraints, constraints.Length);
1004 // Using a factory to avoid possibly expensive inflator build up
1006 if (inflator == null)
1007 inflator = inflatorFactory (arg);
1009 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1013 if (constraints == null)
1014 constraints = tparams;
1019 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1021 tps.BaseType = inflator.Inflate (BaseType);
1022 if (ifaces != null) {
1023 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1024 for (int i = 0; i < ifaces.Count; ++i)
1025 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1028 if (targs != null) {
1029 tps.targs = new TypeSpec[targs.Length];
1030 for (int i = 0; i < targs.Length; ++i)
1031 tps.targs[i] = inflator.Inflate (targs[i]);
1035 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1037 var tps = (TypeParameterSpec) MemberwiseClone ();
1038 InflateConstraints (inflator, tps);
1043 // Populates type parameter members using type parameter constraints
1044 // The trick here is to be called late enough but not too late to
1045 // populate member cache with all members from other types
1047 protected override void InitializeMemberCache (bool onlyTypes)
1049 cache = new MemberCache ();
1052 // For a type parameter the membercache is the union of the sets of members of the types
1053 // specified as a primary constraint or secondary constraint
1055 if (BaseType != TypeManager.object_type && BaseType != TypeManager.value_type)
1056 cache.AddBaseType (BaseType);
1058 if (ifaces != null) {
1059 foreach (var iface_type in Interfaces) {
1060 cache.AddInterface (iface_type);
1064 if (targs != null) {
1065 foreach (var ta in targs) {
1066 if (ta.BaseType != TypeManager.object_type && ta.BaseType != TypeManager.value_type)
1067 cache.AddBaseType (ta.BaseType);
1069 if (ta.Interfaces != null) {
1070 foreach (var iface_type in ta.Interfaces) {
1071 cache.AddInterface (iface_type);
1078 public bool IsConvertibleToInterface (TypeSpec iface)
1080 if (Interfaces != null) {
1081 foreach (var t in Interfaces) {
1087 if (TypeArguments != null) {
1088 foreach (var t in TypeArguments) {
1089 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1097 public override TypeSpec Mutate (TypeParameterMutator mutator)
1099 return mutator.Mutate (this);
1103 public struct TypeParameterInflator
1105 readonly TypeSpec type;
1106 readonly TypeParameterSpec[] tparams;
1107 readonly TypeSpec[] targs;
1108 readonly IModuleContext context;
1110 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1111 : this (nested.context, type, nested.tparams, nested.targs)
1115 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1117 if (tparams.Length != targs.Length)
1118 throw new ArgumentException ("Invalid arguments");
1120 this.context = context;
1121 this.tparams = tparams;
1128 public IModuleContext Context {
1134 public TypeSpec TypeInstance {
1141 // Type parameters to inflate
1143 public TypeParameterSpec[] TypeParameters {
1151 public TypeSpec Inflate (TypeSpec type)
1153 var tp = type as TypeParameterSpec;
1155 return Inflate (tp);
1157 var ac = type as ArrayContainer;
1159 var et = Inflate (ac.Element);
1160 if (et != ac.Element)
1161 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1167 // When inflating a nested type, inflate its parent first
1168 // in case it's using same type parameters (was inflated within the type)
1172 if (type.IsNested) {
1173 var parent = Inflate (type.DeclaringType);
1176 // Keep the inflated type arguments
1178 targs = type.TypeArguments;
1181 // Parent was inflated, find the same type on inflated type
1182 // to use same cache for nested types on same generic parent
1184 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1187 // Handle the tricky case where parent shares local type arguments
1188 // which means inflating inflated type
1191 // public static Nested<T> Foo () { return null; }
1193 // public class Nested<U> {}
1196 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1198 if (targs.Length > 0) {
1199 var inflated_targs = new TypeSpec[targs.Length];
1200 for (; i < targs.Length; ++i)
1201 inflated_targs[i] = Inflate (targs[i]);
1203 type = type.MakeGenericType (context, inflated_targs);
1209 // Nothing to do for non-generic type
1210 if (type.Arity == 0)
1213 targs = new TypeSpec[type.Arity];
1216 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1218 if (type is InflatedTypeSpec) {
1219 for (; i < targs.Length; ++i)
1220 targs[i] = Inflate (type.TypeArguments[i]);
1222 type = type.GetDefinition ();
1225 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1227 var args = type.MemberDefinition.TypeParameters;
1228 foreach (var ds_tp in args)
1229 targs[i++] = Inflate (ds_tp);
1232 return type.MakeGenericType (context, targs);
1235 public TypeSpec Inflate (TypeParameterSpec tp)
1237 for (int i = 0; i < tparams.Length; ++i)
1238 if (tparams [i] == tp)
1241 // This can happen when inflating nested types
1242 // without type arguments specified
1248 // Before emitting any code we have to change all MVAR references to VAR
1249 // when the method is of generic type and has hoisted variables
1251 public class TypeParameterMutator
1253 TypeParameter[] mvar;
1254 TypeParameter[] var;
1255 Dictionary<TypeSpec, TypeSpec> mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1257 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1259 if (mvar.Length != var.Length)
1260 throw new ArgumentException ();
1268 public TypeParameter[] MethodTypeParameters {
1276 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1278 if (type is InflatedTypeSpec) {
1279 if (type.DeclaringType == null)
1280 return type.GetDefinition ();
1282 var parent = GetMemberDeclaringType (type.DeclaringType);
1283 type = MemberCache.GetMember<TypeSpec> (parent, type);
1289 public TypeSpec Mutate (TypeSpec ts)
1292 if (mutated_typespec.TryGetValue (ts, out value))
1295 value = ts.Mutate (this);
1296 mutated_typespec.Add (ts, value);
1300 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1302 for (int i = 0; i < mvar.Length; ++i) {
1303 if (mvar[i].Type == tp)
1310 public TypeSpec[] Mutate (TypeSpec[] targs)
1312 TypeSpec[] mutated = new TypeSpec[targs.Length];
1313 bool changed = false;
1314 for (int i = 0; i < targs.Length; ++i) {
1315 mutated[i] = Mutate (targs[i]);
1316 changed |= targs[i] != mutated[i];
1319 return changed ? mutated : targs;
1324 /// A TypeExpr which already resolved to a type parameter.
1326 public class TypeParameterExpr : TypeExpr {
1328 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1330 this.type = type_parameter.Type;
1331 this.eclass = ExprClass.TypeParameter;
1335 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1337 throw new NotSupportedException ();
1340 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1346 public class InflatedTypeSpec : TypeSpec
1349 TypeParameterSpec[] constraints;
1350 readonly TypeSpec open_type;
1351 readonly IModuleContext context;
1353 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1354 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1357 throw new ArgumentNullException ("targs");
1359 // this.state = openType.state;
1360 this.context = context;
1361 this.open_type = openType;
1364 foreach (var arg in targs) {
1365 if (arg.HasDynamicElement || arg == InternalType.Dynamic) {
1366 state |= StateFlags.HasDynamicElement;
1371 if (open_type.Kind == MemberKind.MissingType)
1372 MemberCache = MemberCache.Empty;
1377 public override TypeSpec BaseType {
1379 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1380 InitializeMemberCache (true);
1382 return base.BaseType;
1387 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1389 public TypeParameterSpec[] Constraints {
1391 if (constraints == null) {
1392 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1399 public override IList<TypeSpec> Interfaces {
1402 InitializeMemberCache (true);
1404 return base.Interfaces;
1409 // Types used to inflate the generic type
1411 public override TypeSpec[] TypeArguments {
1419 public static bool ContainsTypeParameter (TypeSpec type)
1421 if (type.Kind == MemberKind.TypeParameter)
1424 var element_container = type as ElementTypeSpec;
1425 if (element_container != null)
1426 return ContainsTypeParameter (element_container.Element);
1428 foreach (var t in type.TypeArguments) {
1429 if (ContainsTypeParameter (t)) {
1437 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1439 TypeParameterSpec[] tparams_full;
1440 TypeSpec[] targs_full = targs;
1443 // Special case is needed when we are inflating an open type (nested type definition)
1444 // on inflated parent. Consider following case
1446 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1448 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1450 List<TypeSpec> merged_targs = null;
1451 List<TypeParameterSpec> merged_tparams = null;
1453 var type = DeclaringType;
1456 if (type.TypeArguments.Length > 0) {
1457 if (merged_targs == null) {
1458 merged_targs = new List<TypeSpec> ();
1459 merged_tparams = new List<TypeParameterSpec> ();
1460 if (targs.Length > 0) {
1461 merged_targs.AddRange (targs);
1462 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1465 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1466 merged_targs.AddRange (type.TypeArguments);
1468 type = type.DeclaringType;
1469 } while (type != null);
1471 if (merged_targs != null) {
1472 // Type arguments are not in the right order but it should not matter in this case
1473 targs_full = merged_targs.ToArray ();
1474 tparams_full = merged_tparams.ToArray ();
1475 } else if (targs.Length == 0) {
1476 tparams_full = TypeParameterSpec.EmptyTypes;
1478 tparams_full = open_type.MemberDefinition.TypeParameters;
1480 } else if (targs.Length == 0) {
1481 tparams_full = TypeParameterSpec.EmptyTypes;
1483 tparams_full = open_type.MemberDefinition.TypeParameters;
1486 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1489 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1492 // Converts nested type arguments into right order
1493 // Foo<string, bool>.Bar<int> => string, bool, int
1495 var all = new List<MetaType> ();
1496 TypeSpec type = this;
1497 TypeSpec definition = type;
1499 if (type.GetDefinition().IsGeneric) {
1501 type.TypeArguments != TypeSpec.EmptyTypes ?
1502 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1503 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1506 definition = definition.GetDefinition ();
1507 type = type.DeclaringType;
1508 } while (type != null);
1510 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1513 public override ObsoleteAttribute GetAttributeObsolete ()
1515 return open_type.GetAttributeObsolete ();
1518 protected override bool IsNotCLSCompliant (out bool attrValue)
1520 if (base.IsNotCLSCompliant (out attrValue))
1523 foreach (var ta in TypeArguments) {
1524 if (ta.MemberDefinition.CLSAttributeValue == false)
1531 public override TypeSpec GetDefinition ()
1536 public override MetaType GetMetaInfo ()
1539 info = CreateMetaInfo (null);
1544 public override string GetSignatureForError ()
1546 if (TypeManager.IsNullableType (open_type))
1547 return targs[0].GetSignatureForError () + "?";
1549 return base.GetSignatureForError ();
1552 protected override string GetTypeNameSignature ()
1554 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1557 return "<" + TypeManager.CSharpName (targs) + ">";
1560 protected override void InitializeMemberCache (bool onlyTypes)
1563 cache = new MemberCache (onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache);
1565 var inflator = CreateLocalInflator (context);
1568 // Two stage inflate due to possible nested types recursive
1578 // When resolving type of `b' members of `B' cannot be
1579 // inflated because are not yet available in membercache
1581 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1582 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1585 // Inflate any implemented interfaces
1587 if (open_type.Interfaces != null) {
1588 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1589 foreach (var iface in open_type.Interfaces) {
1590 var iface_inflated = inflator.Inflate (iface);
1591 AddInterface (iface_inflated);
1596 // Handles the tricky case of recursive nested base generic type
1598 // class A<T> : Base<A<T>.Nested> {
1602 // When inflating A<T>. base type is not yet known, secondary
1603 // inflation is required (not common case) once base scope
1606 if (open_type.BaseType == null) {
1608 state |= StateFlags.PendingBaseTypeInflate;
1610 BaseType = inflator.Inflate (open_type.BaseType);
1612 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1613 BaseType = inflator.Inflate (open_type.BaseType);
1614 state &= ~StateFlags.PendingBaseTypeInflate;
1618 state |= StateFlags.PendingMemberCacheMembers;
1622 var tc = open_type.MemberDefinition as TypeContainer;
1623 if (tc != null && !tc.HasMembersDefined)
1624 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1626 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1627 BaseType = inflator.Inflate (open_type.BaseType);
1628 state &= ~StateFlags.PendingBaseTypeInflate;
1631 state &= ~StateFlags.PendingMemberCacheMembers;
1632 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1635 public override TypeSpec Mutate (TypeParameterMutator mutator)
1637 var targs = TypeArguments;
1639 targs = mutator.Mutate (targs);
1641 var decl = DeclaringType;
1642 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1643 decl = mutator.Mutate (decl);
1645 if (targs == TypeArguments && decl == DeclaringType)
1648 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1649 if (decl != DeclaringType) {
1650 // Gets back MethodInfo in case of metaInfo was inflated
1651 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1653 mutated.declaringType = decl;
1654 mutated.state |= StateFlags.PendingMetaInflate;
1657 if (targs != null) {
1658 mutated.targs = targs;
1659 mutated.info = null;
1668 // Tracks the type arguments when instantiating a generic type. It's used
1669 // by both type arguments and type parameters
1671 public class TypeArguments
1673 List<FullNamedExpression> args;
1676 public TypeArguments (params FullNamedExpression[] types)
1678 this.args = new List<FullNamedExpression> (types);
1681 public void Add (FullNamedExpression type)
1686 // TODO: Kill this monster
1687 public TypeParameterName[] GetDeclarations ()
1689 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1693 /// We may only be used after Resolve() is called and return the fully
1696 // TODO: Not needed, just return type from resolve
1697 public TypeSpec[] Arguments {
1709 public virtual bool IsEmpty {
1715 public string GetSignatureForError()
1717 StringBuilder sb = new StringBuilder ();
1718 for (int i = 0; i < Count; ++i) {
1721 sb.Append (expr.GetSignatureForError ());
1727 return sb.ToString ();
1731 /// Resolve the type arguments.
1733 public virtual bool Resolve (IMemberContext ec)
1736 return atypes.Length != 0;
1738 int count = args.Count;
1741 atypes = new TypeSpec [count];
1743 for (int i = 0; i < count; i++){
1744 TypeExpr te = args[i].ResolveAsTypeTerminal (ec, false);
1750 atypes[i] = te.Type;
1752 if (te.Type.IsStatic) {
1753 ec.Module.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1754 te.GetSignatureForError ());
1758 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1759 ec.Module.Compiler.Report.Error (306, te.Location,
1760 "The type `{0}' may not be used as a type argument",
1761 te.GetSignatureForError ());
1767 atypes = TypeSpec.EmptyTypes;
1772 public TypeArguments Clone ()
1774 TypeArguments copy = new TypeArguments ();
1775 foreach (var ta in args)
1782 public class UnboundTypeArguments : TypeArguments
1784 public UnboundTypeArguments (int arity)
1785 : base (new FullNamedExpression[arity])
1789 public override bool IsEmpty {
1795 public override bool Resolve (IMemberContext ec)
1797 // Nothing to be resolved
1802 public class TypeParameterName : SimpleName
1804 Attributes attributes;
1807 public TypeParameterName (string name, Attributes attrs, Location loc)
1808 : this (name, attrs, Variance.None, loc)
1812 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1816 this.variance = variance;
1819 public Attributes OptAttributes {
1825 public Variance Variance {
1833 // A type expression of generic type with type arguments
1835 class GenericTypeExpr : TypeExpr
1839 bool constraints_checked;
1842 /// Instantiate the generic type `t' with the type arguments `args'.
1843 /// Use this constructor if you already know the fully resolved
1846 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1848 this.open_type = open_type;
1853 public TypeArguments TypeArguments {
1854 get { return args; }
1857 public override string GetSignatureForError ()
1859 return TypeManager.CSharpName (type);
1862 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1864 if (!args.Resolve (ec))
1867 TypeSpec[] atypes = args.Arguments;
1870 // Now bind the parameters
1872 type = open_type.MakeGenericType (ec, atypes);
1875 // Check constraints when context is not method/base type
1877 if (!ec.HasUnresolvedConstraints)
1878 CheckConstraints (ec);
1884 // Checks the constraints of open generic type against type
1885 // arguments. Has to be called after all members have been defined
1887 public bool CheckConstraints (IMemberContext ec)
1889 if (constraints_checked)
1892 constraints_checked = true;
1894 var gtype = (InflatedTypeSpec) type;
1895 var constraints = gtype.Constraints;
1896 if (constraints == null)
1899 return new ConstraintChecker(ec).CheckAll (open_type, args.Arguments, constraints, loc);
1902 public bool HasDynamicArguments ()
1904 return HasDynamicArguments (args.Arguments);
1907 static bool HasDynamicArguments (TypeSpec[] args)
1909 for (int i = 0; i < args.Length; ++i) {
1912 if (item == InternalType.Dynamic)
1915 if (TypeManager.IsGenericType (item))
1916 return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1919 while (item.IsArray) {
1920 item = ((ArrayContainer) item).Element;
1923 if (item == InternalType.Dynamic)
1931 public override bool Equals (object obj)
1933 GenericTypeExpr cobj = obj as GenericTypeExpr;
1937 if ((type == null) || (cobj.type == null))
1940 return type == cobj.type;
1943 public override int GetHashCode ()
1945 return base.GetHashCode ();
1950 // Generic type with unbound type arguments, used for typeof (G<,,>)
1952 class GenericOpenTypeExpr : TypeExpr
1954 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
1956 this.type = type.GetDefinition ();
1960 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1966 struct ConstraintChecker
1969 bool ignore_inferred_dynamic;
1971 public ConstraintChecker (IMemberContext ctx)
1974 ignore_inferred_dynamic = false;
1979 public bool IgnoreInferredDynamic {
1981 return ignore_inferred_dynamic;
1984 ignore_inferred_dynamic = value;
1991 // Checks all type arguments againts type parameters constraints
1992 // NOTE: It can run in probing mode when `mc' is null
1994 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
1996 for (int i = 0; i < tparams.Length; i++) {
1997 if (ignore_inferred_dynamic && targs[i] == InternalType.Dynamic)
2000 if (!CheckConstraint (context, targs [i], tparams [i], loc))
2007 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2010 // First, check the `class' and `struct' constraints.
2012 if (tparam.HasSpecialClass && !TypeManager.IsReferenceType (atype)) {
2014 mc.Module.Compiler.Report.Error (452, loc,
2015 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2016 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2022 if (tparam.HasSpecialStruct && (!TypeManager.IsValueType (atype) || TypeManager.IsNullableType (atype))) {
2024 mc.Module.Compiler.Report.Error (453, loc,
2025 "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}'",
2026 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2035 // Check the class constraint
2037 if (tparam.HasTypeConstraint) {
2038 var dep = tparam.BaseType.GetMissingDependencies ();
2043 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2047 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2056 // Check the interfaces constraints
2058 if (tparam.Interfaces != null) {
2059 if (TypeManager.IsNullableType (atype)) {
2063 mc.Module.Compiler.Report.Error (313, loc,
2064 "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",
2065 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2068 foreach (TypeSpec iface in tparam.Interfaces) {
2069 var dep = iface.GetMissingDependencies ();
2074 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2077 // return immediately to avoid duplicate errors because we are scanning
2078 // expanded interface list
2082 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2093 // Check the type parameter constraint
2095 if (tparam.TypeArguments != null) {
2096 foreach (var ta in tparam.TypeArguments) {
2097 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2107 // Finally, check the constructor constraint.
2109 if (!tparam.HasSpecialConstructor)
2112 if (!HasDefaultConstructor (atype)) {
2114 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2115 mc.Module.Compiler.Report.Error (310, loc,
2116 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2117 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2125 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2127 for (int i = 0; i < targs.Length; ++i) {
2128 var targ = targs [i];
2129 if (targ == InternalType.Dynamic)
2132 if (HasDynamicTypeArgument (targ.TypeArguments))
2139 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2141 if (TypeManager.IsValueType (atype)) {
2142 if (atype == ttype || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2145 var expr = new EmptyExpression (atype);
2147 if (atype.IsGenericParameter) {
2148 if (Convert.ImplicitTypeParameterConversion (expr, ttype) != null)
2152 if (Convert.ImplicitStandardConversionExists (expr, ttype))
2157 // When partial/full type inference finds a dynamic type argument delay
2158 // the constraint check to runtime, it can succeed for real underlying
2161 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2165 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2166 if (TypeManager.IsValueType (atype)) {
2167 mc.Module.Compiler.Report.Error (315, loc,
2168 "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}'",
2169 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2170 } else if (atype.IsGenericParameter) {
2171 mc.Module.Compiler.Report.Error (314, loc,
2172 "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}'",
2173 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2175 mc.Module.Compiler.Report.Error (311, loc,
2176 "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}'",
2177 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2184 bool HasDefaultConstructor (TypeSpec atype)
2186 var tp = atype as TypeParameterSpec;
2188 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2191 if (atype.IsStruct || atype.IsEnum)
2194 if (atype.IsAbstract)
2197 var tdef = atype.GetDefinition ();
2200 // In some circumstances MemberCache is not yet populated and members
2201 // cannot be defined yet (recursive type new constraints)
2203 // class A<T> where T : B<T>, new () {}
2204 // class B<T> where T : A<T>, new () {}
2206 var tc = tdef.MemberDefinition as Class;
2208 if (tc.InstanceConstructors == null) {
2209 // Default ctor will be generated later
2213 foreach (var c in tc.InstanceConstructors) {
2214 if (c.ParameterInfo.IsEmpty) {
2215 if ((c.ModFlags & Modifiers.PUBLIC) != 0)
2223 var found = MemberCache.FindMember (tdef,
2224 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2225 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2227 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2232 /// A generic method definition.
2234 public class GenericMethod : DeclSpace
2236 ParametersCompiled parameters;
2238 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
2239 FullNamedExpression return_type, ParametersCompiled parameters)
2240 : base (ns, parent, name, null)
2242 this.parameters = parameters;
2245 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2246 FullNamedExpression return_type, ParametersCompiled parameters)
2247 : this (ns, parent, name, return_type, parameters)
2249 this.type_params = tparams;
2252 public override TypeParameter[] CurrentTypeParameters {
2254 return base.type_params;
2258 protected override TypeAttributes TypeAttr {
2260 throw new NotSupportedException ();
2264 public override void DefineType ()
2266 throw new Exception ();
2269 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2271 throw new NotSupportedException ();
2274 public override bool Define ()
2276 throw new NotSupportedException ();
2280 /// Define and resolve the type parameters.
2281 /// We're called from Method.Define().
2283 public bool Define (MethodOrOperator m)
2285 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2286 string[] snames = new string [names.Length];
2287 var block = m.Block;
2288 for (int i = 0; i < names.Length; i++) {
2289 string type_argument_name = names[i].Name;
2291 if (block == null) {
2292 int idx = parameters.GetParameterIndexByName (type_argument_name);
2296 b = new ToplevelBlock (Compiler, Location);
2298 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2301 INamedBlockVariable variable = null;
2302 block.GetLocalName (type_argument_name, m.Block, ref variable);
2303 if (variable != null)
2304 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2307 snames[i] = type_argument_name;
2310 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2311 for (int i = 0; i < TypeParameters.Length; i++)
2312 TypeParameters [i].Define (gen_params [i], null);
2317 public void EmitAttributes ()
2319 if (OptAttributes != null)
2320 OptAttributes.Emit ();
2323 public override string GetSignatureForError ()
2325 return base.GetSignatureForError () + parameters.GetSignatureForError ();
2328 public override AttributeTargets AttributeTargets {
2330 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2334 public override string DocCommentHeader {
2335 get { return "M:"; }
2338 public new void VerifyClsCompliance ()
2340 foreach (TypeParameter tp in TypeParameters) {
2341 tp.VerifyClsCompliance ();
2346 public partial class TypeManager
2348 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2350 var tp = t as TypeParameterSpec;
2352 Variance v = tp.Variance;
2353 if (expected == Variance.None && v != expected ||
2354 expected == Variance.Covariant && v == Variance.Contravariant ||
2355 expected == Variance.Contravariant && v == Variance.Covariant) {
2356 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2362 if (t.TypeArguments.Length > 0) {
2363 var targs_definition = t.MemberDefinition.TypeParameters;
2364 TypeSpec[] targs = GetTypeArguments (t);
2365 for (int i = 0; i < targs.Length; ++i) {
2366 Variance v = targs_definition[i].Variance;
2367 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2374 return CheckTypeVariance (GetElementType (t), expected, member);
2376 return Variance.None;
2381 // Implements C# type inference
2386 // Tracks successful rate of type inference
2388 int score = int.MaxValue;
2389 readonly Arguments arguments;
2390 readonly int arg_count;
2392 public TypeInference (Arguments arguments)
2394 this.arguments = arguments;
2395 if (arguments != null)
2396 arg_count = arguments.Count;
2399 public int InferenceScore {
2405 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2407 var method_generic_args = method.GenericDefinition.TypeParameters;
2408 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2409 if (!context.UnfixedVariableExists)
2410 return TypeSpec.EmptyTypes;
2412 AParametersCollection pd = method.Parameters;
2413 if (!InferInPhases (ec, context, pd))
2416 return context.InferredTypeArguments;
2420 // Implements method type arguments inference
2422 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2424 int params_arguments_start;
2425 if (methodParameters.HasParams) {
2426 params_arguments_start = methodParameters.Count - 1;
2428 params_arguments_start = arg_count;
2431 TypeSpec [] ptypes = methodParameters.Types;
2434 // The first inference phase
2436 TypeSpec method_parameter = null;
2437 for (int i = 0; i < arg_count; i++) {
2438 Argument a = arguments [i];
2442 if (i < params_arguments_start) {
2443 method_parameter = methodParameters.Types [i];
2444 } else if (i == params_arguments_start) {
2445 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2446 method_parameter = methodParameters.Types [params_arguments_start];
2448 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2450 ptypes = (TypeSpec[]) ptypes.Clone ();
2451 ptypes [i] = method_parameter;
2455 // When a lambda expression, an anonymous method
2456 // is used an explicit argument type inference takes a place
2458 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2460 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2466 score -= tic.ExactInference (a.Type, method_parameter);
2470 if (a.Expr.Type == InternalType.Null)
2473 if (TypeManager.IsValueType (method_parameter)) {
2474 score -= tic.LowerBoundInference (a.Type, method_parameter);
2479 // Otherwise an output type inference is made
2481 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2485 // Part of the second phase but because it happens only once
2486 // we don't need to call it in cycle
2488 bool fixed_any = false;
2489 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2492 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2495 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2497 bool fixed_any = false;
2498 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2501 // If no further unfixed type variables exist, type inference succeeds
2502 if (!tic.UnfixedVariableExists)
2505 if (!fixed_any && fixDependent)
2508 // For all arguments where the corresponding argument output types
2509 // contain unfixed type variables but the input types do not,
2510 // an output type inference is made
2511 for (int i = 0; i < arg_count; i++) {
2513 // Align params arguments
2514 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2516 if (!TypeManager.IsDelegateType (t_i)) {
2517 if (t_i.GetDefinition () != TypeManager.expression_type)
2520 t_i = TypeManager.GetTypeArguments (t_i) [0];
2523 var mi = Delegate.GetInvokeMethod (t_i);
2524 TypeSpec rtype = mi.ReturnType;
2526 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2527 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2531 return DoSecondPhase (ec, tic, methodParameters, true);
2535 public class TypeInferenceContext
2537 protected enum BoundKind
2544 protected class BoundInfo : IEquatable<BoundInfo>
2546 public readonly TypeSpec Type;
2547 public readonly BoundKind Kind;
2549 public BoundInfo (TypeSpec type, BoundKind kind)
2555 public override int GetHashCode ()
2557 return Type.GetHashCode ();
2560 public virtual Expression GetTypeExpression ()
2562 return new TypeExpression (Type, Location.Null);
2565 #region IEquatable<BoundInfo> Members
2567 public virtual bool Equals (BoundInfo other)
2569 return Type == other.Type && Kind == other.Kind;
2575 readonly TypeSpec[] tp_args;
2576 readonly TypeSpec[] fixed_types;
2577 readonly List<BoundInfo>[] bounds;
2580 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2581 public TypeInferenceContext (TypeSpec[] typeArguments)
2583 if (typeArguments.Length == 0)
2584 throw new ArgumentException ("Empty generic arguments");
2586 fixed_types = new TypeSpec [typeArguments.Length];
2587 for (int i = 0; i < typeArguments.Length; ++i) {
2588 if (typeArguments [i].IsGenericParameter) {
2589 if (bounds == null) {
2590 bounds = new List<BoundInfo> [typeArguments.Length];
2591 tp_args = new TypeSpec [typeArguments.Length];
2593 tp_args [i] = typeArguments [i];
2595 fixed_types [i] = typeArguments [i];
2601 // Used together with AddCommonTypeBound fo implement
2602 // 7.4.2.13 Finding the best common type of a set of expressions
2604 public TypeInferenceContext ()
2606 fixed_types = new TypeSpec [1];
2607 tp_args = new TypeSpec [1];
2608 tp_args[0] = InternalType.Arglist; // it can be any internal type
2609 bounds = new List<BoundInfo> [1];
2612 public TypeSpec[] InferredTypeArguments {
2618 public void AddCommonTypeBound (TypeSpec type)
2620 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2623 protected void AddToBounds (BoundInfo bound, int index)
2626 // Some types cannot be used as type arguments
2628 if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2631 var a = bounds [index];
2633 a = new List<BoundInfo> (2);
2639 if (a.Contains (bound))
2645 bool AllTypesAreFixed (TypeSpec[] types)
2647 foreach (TypeSpec t in types) {
2648 if (t.IsGenericParameter) {
2654 if (TypeManager.IsGenericType (t))
2655 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2662 // 26.3.3.8 Exact Inference
2664 public int ExactInference (TypeSpec u, TypeSpec v)
2666 // If V is an array type
2671 // TODO MemberCache: GetMetaInfo ()
2672 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2675 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2678 // If V is constructed type and U is constructed type
2679 if (TypeManager.IsGenericType (v)) {
2680 if (!TypeManager.IsGenericType (u))
2683 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2684 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2685 if (ga_u.Length != ga_v.Length)
2689 for (int i = 0; i < ga_u.Length; ++i)
2690 score += ExactInference (ga_u [i], ga_v [i]);
2692 return score > 0 ? 1 : 0;
2695 // If V is one of the unfixed type arguments
2696 int pos = IsUnfixed (v);
2700 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2704 public bool FixAllTypes (ResolveContext ec)
2706 for (int i = 0; i < tp_args.Length; ++i) {
2707 if (!FixType (ec, i))
2714 // All unfixed type variables Xi are fixed for which all of the following hold:
2715 // a, There is at least one type variable Xj that depends on Xi
2716 // b, Xi has a non-empty set of bounds
2718 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2720 for (int i = 0; i < tp_args.Length; ++i) {
2721 if (fixed_types[i] != null)
2724 if (bounds[i] == null)
2727 if (!FixType (ec, i))
2737 // All unfixed type variables Xi which depend on no Xj are fixed
2739 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2741 var types_to_fix = new List<TypeSpec> (tp_args);
2742 for (int i = 0; i < methodParameters.Length; ++i) {
2743 TypeSpec t = methodParameters[i];
2745 if (!TypeManager.IsDelegateType (t)) {
2746 if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
2749 t = TypeManager.GetTypeArguments (t) [0];
2752 if (t.IsGenericParameter)
2755 var invoke = Delegate.GetInvokeMethod (t);
2756 TypeSpec rtype = invoke.ReturnType;
2757 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2760 // Remove dependent types, they cannot be fixed yet
2761 RemoveDependentTypes (types_to_fix, rtype);
2764 foreach (TypeSpec t in types_to_fix) {
2768 int idx = IsUnfixed (t);
2769 if (idx >= 0 && !FixType (ec, idx)) {
2774 fixed_any = types_to_fix.Count > 0;
2781 public bool FixType (ResolveContext ec, int i)
2783 // It's already fixed
2784 if (fixed_types[i] != null)
2785 throw new InternalErrorException ("Type argument has been already fixed");
2790 var candidates = bounds [i];
2791 if (candidates == null)
2794 if (candidates.Count == 1) {
2795 TypeSpec t = candidates[0].Type;
2796 if (t == InternalType.Null)
2799 fixed_types [i] = t;
2804 // Determines a unique type from which there is
2805 // a standard implicit conversion to all the other
2808 TypeSpec best_candidate = null;
2810 int candidates_count = candidates.Count;
2811 for (int ci = 0; ci < candidates_count; ++ci) {
2812 BoundInfo bound = candidates [ci];
2813 for (cii = 0; cii < candidates_count; ++cii) {
2817 BoundInfo cbound = candidates[cii];
2819 // Same type parameters with different bounds
2820 if (cbound.Type == bound.Type) {
2821 if (bound.Kind != BoundKind.Exact)
2827 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2828 if (cbound.Kind == BoundKind.Lower) {
2829 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2835 if (cbound.Kind == BoundKind.Upper) {
2836 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2843 if (bound.Kind != BoundKind.Exact) {
2844 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2855 if (bound.Kind == BoundKind.Lower) {
2856 if (cbound.Kind == BoundKind.Lower) {
2857 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2861 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2871 if (bound.Kind == BoundKind.Upper) {
2872 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2876 throw new NotImplementedException ("variance conversion");
2880 if (cii != candidates_count)
2884 // We already have the best candidate, break if thet are different
2886 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
2888 if (best_candidate != null) {
2890 if (best_candidate == InternalType.Dynamic)
2893 if (bound.Type != InternalType.Dynamic && best_candidate != bound.Type)
2897 best_candidate = bound.Type;
2900 if (best_candidate == null)
2903 fixed_types[i] = best_candidate;
2908 // Uses inferred or partially infered types to inflate delegate type argument. Returns
2909 // null when type parameter has not been fixed
2911 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
2913 var tp = parameter as TypeParameterSpec;
2916 // Type inference works on generic arguments (MVAR) only
2918 if (!tp.IsMethodOwned)
2922 // Ensure the type parameter belongs to same container
2924 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
2925 return fixed_types[tp.DeclaredPosition] ?? parameter;
2930 var gt = parameter as InflatedTypeSpec;
2932 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
2933 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
2934 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
2935 if (inflated == null)
2938 inflated_targs[ii] = inflated;
2941 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
2948 // Tests whether all delegate input arguments are fixed and generic output type
2949 // requires output type inference
2951 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
2953 if (returnType.IsGenericParameter) {
2954 if (IsFixed (returnType))
2956 } else if (TypeManager.IsGenericType (returnType)) {
2957 if (TypeManager.IsDelegateType (returnType)) {
2958 invoke = Delegate.GetInvokeMethod (returnType);
2959 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2962 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
2964 // At least one unfixed return type has to exist
2965 if (AllTypesAreFixed (g_args))
2971 // All generic input arguments have to be fixed
2972 AParametersCollection d_parameters = invoke.Parameters;
2973 return AllTypesAreFixed (d_parameters.Types);
2976 bool IsFixed (TypeSpec type)
2978 return IsUnfixed (type) == -1;
2981 int IsUnfixed (TypeSpec type)
2983 if (!type.IsGenericParameter)
2986 for (int i = 0; i < tp_args.Length; ++i) {
2987 if (tp_args[i] == type) {
2988 if (fixed_types[i] != null)
2999 // 26.3.3.9 Lower-bound Inference
3001 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3003 return LowerBoundInference (u, v, false);
3007 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3009 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3011 // If V is one of the unfixed type arguments
3012 int pos = IsUnfixed (v);
3014 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3018 // If U is an array type
3019 var u_ac = u as ArrayContainer;
3021 var v_ac = v as ArrayContainer;
3023 if (u_ac.Rank != v_ac.Rank)
3026 if (TypeManager.IsValueType (u_ac.Element))
3027 return ExactInference (u_ac.Element, v_ac.Element);
3029 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3035 if (TypeManager.IsGenericType (v)) {
3036 TypeSpec g_v = v.GetDefinition ();
3037 if (g_v != TypeManager.generic_ilist_type &&
3038 g_v != TypeManager.generic_icollection_type &&
3039 g_v != TypeManager.generic_ienumerable_type)
3042 var v_i = TypeManager.GetTypeArguments (v) [0];
3043 if (TypeManager.IsValueType (u_ac.Element))
3044 return ExactInference (u_ac.Element, v_i);
3046 return LowerBoundInference (u_ac.Element, v_i);
3048 } else if (TypeManager.IsGenericType (v)) {
3050 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3051 // such that U is identical to, inherits from (directly or indirectly),
3052 // or implements (directly or indirectly) C<U1..Uk>
3054 var u_candidates = new List<TypeSpec> ();
3055 var open_v = v.MemberDefinition;
3057 for (TypeSpec t = u; t != null; t = t.BaseType) {
3058 if (open_v == t.MemberDefinition)
3059 u_candidates.Add (t);
3062 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3063 // that would complicate the process a lot, instead I treat them as dynamic
3065 if (t == InternalType.Dynamic)
3066 u_candidates.Add (t);
3068 if (t.Interfaces != null) {
3069 foreach (var iface in t.Interfaces) {
3070 if (open_v == iface.MemberDefinition)
3071 u_candidates.Add (iface);
3076 TypeSpec [] unique_candidate_targs = null;
3077 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
3078 foreach (TypeSpec u_candidate in u_candidates) {
3080 // The unique set of types U1..Uk means that if we have an interface I<T>,
3081 // class U : I<int>, I<long> then no type inference is made when inferring
3082 // type I<T> by applying type U because T could be int or long
3084 if (unique_candidate_targs != null) {
3085 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3086 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3087 unique_candidate_targs = second_unique_candidate_targs;
3092 // This should always cause type inference failure
3099 // A candidate is dynamic type expression, to simplify things use dynamic
3100 // for all type parameter of this type. For methods like this one
3102 // void M<T, U> (IList<T>, IList<U[]>)
3104 // dynamic becomes both T and U when the arguments are of dynamic type
3106 if (u_candidate == InternalType.Dynamic) {
3107 unique_candidate_targs = new TypeSpec[ga_v.Length];
3108 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3109 unique_candidate_targs[i] = u_candidate;
3111 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3115 if (unique_candidate_targs != null) {
3116 var ga_open_v = open_v.TypeParameters;
3118 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3119 Variance variance = ga_open_v [i].Variance;
3121 TypeSpec u_i = unique_candidate_targs [i];
3122 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
3123 if (ExactInference (u_i, ga_v [i]) == 0)
3126 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3127 (variance == Variance.Covariant && inversed);
3129 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3141 // 26.3.3.6 Output Type Inference
3143 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3145 // If e is a lambda or anonymous method with inferred return type
3146 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3148 TypeSpec rt = ame.InferReturnType (ec, this, t);
3149 var invoke = Delegate.GetInvokeMethod (t);
3152 AParametersCollection pd = invoke.Parameters;
3153 return ame.Parameters.Count == pd.Count ? 1 : 0;
3156 TypeSpec rtype = invoke.ReturnType;
3157 return LowerBoundInference (rt, rtype) + 1;
3161 // if E is a method group and T is a delegate type or expression tree type
3162 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3163 // resolution of E with the types T1..Tk yields a single method with return type U,
3164 // then a lower-bound inference is made from U for Tb.
3166 if (e is MethodGroupExpr) {
3167 if (!TypeManager.IsDelegateType (t)) {
3168 if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
3171 t = TypeManager.GetTypeArguments (t)[0];
3174 var invoke = Delegate.GetInvokeMethod (t);
3175 TypeSpec rtype = invoke.ReturnType;
3177 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3180 // LAMESPEC: Standard does not specify that all methodgroup arguments
3181 // has to be fixed but it does not specify how to do recursive type inference
3182 // either. We choose the simple option and infer return type only
3183 // if all delegate generic arguments are fixed.
3184 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3185 for (int i = 0; i < param_types.Length; ++i) {
3186 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3187 if (inflated == null)
3190 if (IsUnfixed (inflated) >= 0)
3193 param_types[i] = inflated;
3196 MethodGroupExpr mg = (MethodGroupExpr) e;
3197 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3198 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3202 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3206 // if e is an expression with type U, then
3207 // a lower-bound inference is made from U for T
3209 return LowerBoundInference (e.Type, t) * 2;
3212 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3214 int idx = IsUnfixed (returnType);
3220 if (TypeManager.IsGenericType (returnType)) {
3221 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3222 RemoveDependentTypes (types, t);
3227 public bool UnfixedVariableExists {
3229 foreach (TypeSpec ut in fixed_types) {