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 ();
63 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
65 throw new NotImplementedException ();
70 // A set of parsed constraints for a type parameter
72 public class Constraints
74 SimpleMemberName tparam;
75 List<FullNamedExpression> constraints;
80 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
83 this.constraints = constraints;
89 public Location Location {
95 public SimpleMemberName TypeParameter {
103 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
105 if (spec.HasSpecialClass && bb.IsStruct) {
106 context.Module.Compiler.Report.Error (455, loc,
107 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
108 spec.Name, "class", bb.GetSignatureForError ());
113 return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
116 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
121 if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
124 context.Module.Compiler.Report.Error (455, loc,
125 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
126 spec.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
130 public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
132 foreach (var c in constraints) {
141 ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
142 if (obsolete_attr != null)
143 AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
146 ConstraintChecker.Check (context, t, c.Location);
151 // Resolve the constraints types with only possible early checks, return
152 // value `false' is reserved for recursive failure
154 public bool Resolve (IMemberContext context, TypeParameter tp)
164 List<TypeParameterSpec> tparam_types = null;
165 bool iface_found = false;
167 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
169 for (int i = 0; i < constraints.Count; ++i) {
170 var constraint = constraints[i];
172 if (constraint is SpecialContraintExpr) {
173 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
174 if (spec.HasSpecialStruct)
175 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
177 // Set to null as it does not have a type
178 constraints[i] = null;
182 var type = constraint.ResolveAsType (context);
186 if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
187 context.Module.Compiler.Report.Error (1968, constraint.Location,
188 "A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
192 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
193 context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
194 context.Module.Compiler.Report.Error (703, loc,
195 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
196 type.GetSignatureForError (), context.GetSignatureForError ());
199 if (type.IsInterface) {
200 if (!spec.AddInterface (type)) {
201 context.Module.Compiler.Report.Error (405, constraint.Location,
202 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
210 var constraint_tp = type as TypeParameterSpec;
211 if (constraint_tp != null) {
212 if (tparam_types == null) {
213 tparam_types = new List<TypeParameterSpec> (2);
214 } else if (tparam_types.Contains (constraint_tp)) {
215 context.Module.Compiler.Report.Error (405, constraint.Location,
216 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
221 // Checks whether each generic method parameter constraint type
222 // is valid with respect to T
224 if (tp.IsMethodTypeParameter) {
225 TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
228 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
229 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
230 context.Module.Compiler.Report.Error (454, constraint.Location,
231 "Circular constraint dependency involving `{0}' and `{1}'",
232 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
237 // Checks whether there are no conflicts between type parameter constraints
243 // A and B are not convertible and only 1 class constraint is allowed
245 if (constraint_tp.HasTypeConstraint) {
246 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
247 if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
250 for (int ii = 0; ii < tparam_types.Count; ++ii) {
251 if (!tparam_types[ii].HasTypeConstraint)
254 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
260 if (constraint_tp.HasSpecialStruct) {
261 context.Module.Compiler.Report.Error (456, constraint.Location,
262 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
263 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
267 tparam_types.Add (constraint_tp);
271 if (iface_found || spec.HasTypeConstraint) {
272 context.Module.Compiler.Report.Error (406, constraint.Location,
273 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
274 type.GetSignatureForError ());
277 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
278 context.Module.Compiler.Report.Error (450, constraint.Location,
279 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
280 type.GetSignatureForError ());
283 switch (type.BuiltinType) {
284 case BuiltinTypeSpec.Type.Array:
285 case BuiltinTypeSpec.Type.Delegate:
286 case BuiltinTypeSpec.Type.MulticastDelegate:
287 case BuiltinTypeSpec.Type.Enum:
288 case BuiltinTypeSpec.Type.ValueType:
289 case BuiltinTypeSpec.Type.Object:
290 context.Module.Compiler.Report.Error (702, constraint.Location,
291 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
293 case BuiltinTypeSpec.Type.Dynamic:
294 context.Module.Compiler.Report.Error (1967, constraint.Location,
295 "A constraint cannot be the dynamic type");
299 if (type.IsSealed || !type.IsClass) {
300 context.Module.Compiler.Report.Error (701, loc,
301 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
302 TypeManager.CSharpName (type));
307 context.Module.Compiler.Report.Error (717, constraint.Location,
308 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
309 type.GetSignatureForError ());
312 spec.BaseType = type;
315 if (tparam_types != null)
316 spec.TypeArguments = tparam_types.ToArray ();
323 public void VerifyClsCompliance (Report report)
325 foreach (var c in constraints)
330 if (!c.Type.IsCLSCompliant ()) {
331 report.SymbolRelatedToPreviousError (c.Type);
332 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
333 c.Type.GetSignatureForError ());
340 // A type parameter for a generic type or generic method definition
342 public class TypeParameter : MemberCore, ITypeDefinition
344 static readonly string[] attribute_target = new string [] { "type parameter" };
346 Constraints constraints;
347 GenericTypeParameterBuilder builder;
348 TypeParameterSpec spec;
350 public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
351 : base (parent, name, attrs)
353 this.constraints = constraints;
354 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
357 public TypeParameter (TypeParameterSpec spec, DeclSpace parent, TypeSpec parentSpec, MemberName name, Attributes attrs)
358 : base (parent, name, attrs)
360 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
361 BaseType = spec.BaseType,
362 InterfacesDefined = spec.InterfacesDefined,
363 TypeArguments = spec.TypeArguments
369 public override AttributeTargets AttributeTargets {
371 return AttributeTargets.GenericParameter;
375 public IAssemblyDefinition DeclaringAssembly {
377 return Module.DeclaringAssembly;
381 public override string DocCommentHeader {
383 throw new InvalidOperationException (
384 "Unexpected attempt to get doc comment from " + this.GetType ());
388 public bool IsMethodTypeParameter {
390 return spec.IsMethodOwned;
394 public string Namespace {
400 public TypeParameterSpec Type {
406 public int TypeParametersCount {
412 public TypeParameterSpec[] TypeParameters {
418 public override string[] ValidAttributeTargets {
420 return attribute_target;
424 public Variance Variance {
426 return spec.Variance;
433 // This is called for each part of a partial generic type definition.
435 // If partial type parameters constraints are not null and we don't
436 // already have constraints they become our constraints. If we already
437 // have constraints, we must check that they're the same.
439 public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
442 throw new InvalidOperationException ();
444 var new_constraints = tp.constraints;
445 if (new_constraints == null)
448 // TODO: could create spec only
449 //tp.Define (null, -1, part.Definition);
450 tp.spec.DeclaringType = part.Definition;
451 if (!tp.ResolveConstraints (part))
454 if (constraints != null)
455 return spec.HasSameConstraintsDefinition (tp.Type);
457 // Copy constraint from resolved part to partial container
458 spec.SpecialConstraint = tp.spec.SpecialConstraint;
459 spec.InterfacesDefined = tp.spec.InterfacesDefined;
460 spec.TypeArguments = tp.spec.TypeArguments;
461 spec.BaseType = tp.spec.BaseType;
466 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
468 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
471 public void CheckGenericConstraints (bool obsoleteCheck)
473 if (constraints != null)
474 constraints.CheckGenericConstraints (this, obsoleteCheck);
477 public TypeParameter CreateHoistedCopy (TypeContainer declaringType, TypeSpec declaringSpec)
479 return new TypeParameter (spec, declaringType, declaringSpec, MemberName, null);
482 public override bool Define ()
488 // This is the first method which is called during the resolving
489 // process; we're called immediately after creating the type parameters
490 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
493 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
496 throw new InternalErrorException ();
499 spec.DeclaringType = declaringType;
500 spec.SetMetaInfo (type);
503 public void EmitConstraints (GenericTypeParameterBuilder builder)
505 var attr = GenericParameterAttributes.None;
506 if (spec.Variance == Variance.Contravariant)
507 attr |= GenericParameterAttributes.Contravariant;
508 else if (spec.Variance == Variance.Covariant)
509 attr |= GenericParameterAttributes.Covariant;
511 if (spec.HasSpecialClass)
512 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
513 else if (spec.HasSpecialStruct)
514 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
516 if (spec.HasSpecialConstructor)
517 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
519 if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
520 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
522 if (spec.InterfacesDefined != null)
523 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
525 if (spec.TypeArguments != null)
526 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
528 builder.SetGenericParameterAttributes (attr);
531 public override void Emit ()
533 EmitConstraints (builder);
535 if (OptAttributes != null)
536 OptAttributes.Emit ();
541 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
543 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
544 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
545 string gtype_variance;
547 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
548 case Variance.Covariant: gtype_variance = "covariantly"; break;
549 default: gtype_variance = "invariantly"; break;
552 Delegate d = mc as Delegate;
553 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
555 Report.Error (1961, Location,
556 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
557 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
560 public TypeSpec GetAttributeCoClass ()
565 public string GetAttributeDefaultMember ()
567 throw new NotSupportedException ();
570 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
572 throw new NotSupportedException ();
575 public override string GetSignatureForDocumentation ()
577 throw new NotImplementedException ();
580 public override string GetSignatureForError ()
582 return MemberName.Name;
585 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
587 return spec.GetEffectiveBase ().MemberDefinition.DeclaringAssembly == assembly;
590 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
592 throw new NotSupportedException ("Not supported for compiled definition");
596 // Resolves all type parameter constraints
598 public bool ResolveConstraints (IMemberContext context)
600 if (constraints != null)
601 return constraints.Resolve (context, this);
603 if (spec.BaseType == null)
604 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
609 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
611 foreach (var tp in tparams) {
619 public override bool IsClsComplianceRequired ()
624 public new void VerifyClsCompliance ()
626 if (constraints != null)
627 constraints.VerifyClsCompliance (Report);
631 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
632 public class TypeParameterSpec : TypeSpec
634 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
637 SpecialConstraint spec;
640 TypeSpec[] ifaces_defined;
643 // Creates type owned type parameter
645 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
646 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
648 this.variance = variance;
650 state &= ~StateFlags.Obsolete_Undetected;
655 // Creates method owned type parameter
657 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
658 : this (null, index, definition, spec, variance, info)
664 public int DeclaredPosition {
670 public bool HasSpecialConstructor {
672 return (spec & SpecialConstraint.Constructor) != 0;
676 public bool HasSpecialClass {
678 return (spec & SpecialConstraint.Class) != 0;
682 public bool HasSpecialStruct {
684 return (spec & SpecialConstraint.Struct) != 0;
688 public bool HasTypeConstraint {
690 var bt = BaseType.BuiltinType;
691 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
695 public override IList<TypeSpec> Interfaces {
697 if ((state & StateFlags.InterfacesExpanded) == 0) {
698 if (ifaces != null) {
699 for (int i = 0; i < ifaces.Count; ++i ) {
700 var iface_type = ifaces[i];
701 if (iface_type.Interfaces != null) {
702 if (ifaces_defined == null)
703 ifaces_defined = ifaces.ToArray ();
705 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
706 var ii_iface_type = iface_type.Interfaces [ii];
708 AddInterface (ii_iface_type);
714 if (ifaces_defined == null && ifaces != null)
715 ifaces_defined = ifaces.ToArray ();
717 state |= StateFlags.InterfacesExpanded;
725 // Unexpanded interfaces list
727 public TypeSpec[] InterfacesDefined {
729 if (ifaces_defined == null && ifaces != null)
730 ifaces_defined = ifaces.ToArray ();
732 return ifaces_defined;
735 ifaces = ifaces_defined = value;
739 public bool IsConstrained {
741 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
746 // Returns whether the type parameter is known to be a reference type
748 public new bool IsReferenceType {
750 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
751 return (spec & SpecialConstraint.Class) != 0;
754 // Full check is needed (see IsValueType for details)
756 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
760 foreach (var ta in targs) {
762 // Secondary special constraints are ignored (I am not sure why)
764 var tp = ta as TypeParameterSpec;
765 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
768 if (TypeSpec.IsReferenceType (ta))
778 // Returns whether the type parameter is known to be a value type
780 public new bool IsValueType {
783 // Even if structs/enums cannot be used directly as constraints
784 // they can apear as constraint type when inheriting base constraint
785 // which has dependant type parameter constraint which has been
786 // inflated using value type
788 // class A : B<int> { override void Foo<U> () {} }
789 // class B<T> { virtual void Foo<U> () where U : T {} }
791 return HasSpecialStruct || TypeSpec.IsValueType (BaseType);
795 public override string Name {
797 return definition.Name;
801 public bool IsMethodOwned {
803 return DeclaringType == null;
807 public SpecialConstraint SpecialConstraint {
817 // Types used to inflate the generic type
819 public new TypeSpec[] TypeArguments {
828 public Variance Variance {
836 public void ChangeTypeArgumentToBaseType (int index)
838 BaseType = targs [index];
839 if (targs.Length == 1) {
842 var copy = new TypeSpec[targs.Length - 1];
844 Array.Copy (targs, copy, index);
846 Array.Copy (targs, index + 1, copy, index, targs.Length - index - 1);
851 public string DisplayDebugInfo ()
853 var s = GetSignatureForError ();
854 return IsMethodOwned ? s + "!!" : s + "!";
858 // Finds effective base class
860 public TypeSpec GetEffectiveBase ()
862 if (HasSpecialStruct)
865 if (BaseType != null && targs == null)
869 if (HasTypeConstraint) {
870 Array.Resize (ref types, types.Length + 1);
871 types[types.Length - 1] = BaseType;
875 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
880 public override string GetSignatureForDocumentation ()
883 var type = DeclaringType;
884 while (type != null && type.DeclaringType != null) {
885 type = type.DeclaringType;
886 c += type.MemberDefinition.TypeParametersCount;
889 var prefix = IsMethodOwned ? "``" : "`";
890 return prefix + (c + DeclaredPosition);
893 public override string GetSignatureForError ()
899 // Constraints have to match by definition but not position, used by
900 // partial classes or methods
902 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
904 if (spec != other.spec)
907 if (BaseType != other.BaseType)
910 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
913 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
920 // Constraints have to match by using same set of types, used by
921 // implicit interface implementation
923 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
925 if (spec != other.spec)
929 // It can be same base type or inflated type parameter
931 // interface I<T> { void Foo<U> where U : T; }
932 // class A : I<int> { void Foo<X> where X : int {} }
935 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
936 if (other.targs == null)
940 foreach (var otarg in other.targs) {
941 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
951 // Check interfaces implementation -> definition
952 if (InterfacesDefined != null) {
953 foreach (var iface in InterfacesDefined) {
955 if (other.InterfacesDefined != null) {
956 foreach (var oiface in other.InterfacesDefined) {
957 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
967 if (other.targs != null) {
968 foreach (var otarg in other.targs) {
969 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
981 // Check interfaces implementation <- definition
982 if (other.InterfacesDefined != null) {
983 if (InterfacesDefined == null)
986 foreach (var oiface in other.InterfacesDefined) {
988 foreach (var iface in InterfacesDefined) {
989 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1000 // Check type parameters implementation -> definition
1001 if (targs != null) {
1002 if (other.targs == null)
1005 foreach (var targ in targs) {
1007 foreach (var otarg in other.targs) {
1008 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1019 // Check type parameters implementation <- definition
1020 if (other.targs != null) {
1021 foreach (var otarg in other.targs) {
1022 // Ignore inflated type arguments, were checked above
1023 if (!otarg.IsGenericParameter)
1030 foreach (var targ in targs) {
1031 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1045 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1047 return InflateConstraints (tparams, l => l, inflator);
1050 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1052 TypeParameterSpec[] constraints = null;
1053 TypeParameterInflator? inflator = null;
1055 for (int i = 0; i < tparams.Length; ++i) {
1056 var tp = tparams[i];
1057 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1058 if (constraints == null) {
1059 constraints = new TypeParameterSpec[tparams.Length];
1060 Array.Copy (tparams, constraints, constraints.Length);
1064 // Using a factory to avoid possibly expensive inflator build up
1066 if (inflator == null)
1067 inflator = inflatorFactory (arg);
1069 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1073 if (constraints == null)
1074 constraints = tparams;
1079 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1081 tps.BaseType = inflator.Inflate (BaseType);
1082 if (ifaces != null) {
1083 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1084 for (int i = 0; i < ifaces.Count; ++i)
1085 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1088 if (targs != null) {
1089 tps.targs = new TypeSpec[targs.Length];
1090 for (int i = 0; i < targs.Length; ++i)
1091 tps.targs[i] = inflator.Inflate (targs[i]);
1095 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1097 var tps = (TypeParameterSpec) MemberwiseClone ();
1098 InflateConstraints (inflator, tps);
1103 // Populates type parameter members using type parameter constraints
1104 // The trick here is to be called late enough but not too late to
1105 // populate member cache with all members from other types
1107 protected override void InitializeMemberCache (bool onlyTypes)
1109 cache = new MemberCache ();
1112 // For a type parameter the membercache is the union of the sets of members of the types
1113 // specified as a primary constraint or secondary constraint
1115 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1116 cache.AddBaseType (BaseType);
1118 if (ifaces != null) {
1119 foreach (var iface_type in Interfaces) {
1120 cache.AddInterface (iface_type);
1124 if (targs != null) {
1125 foreach (var ta in targs) {
1126 var b_type = ta.BaseType;
1127 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1128 cache.AddBaseType (b_type);
1130 if (ta.Interfaces != null) {
1131 foreach (var iface_type in ta.Interfaces) {
1132 cache.AddInterface (iface_type);
1139 public bool IsConvertibleToInterface (TypeSpec iface)
1141 if (Interfaces != null) {
1142 foreach (var t in Interfaces) {
1148 if (TypeArguments != null) {
1149 foreach (var t in TypeArguments) {
1150 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1158 public override TypeSpec Mutate (TypeParameterMutator mutator)
1160 return mutator.Mutate (this);
1164 public struct TypeParameterInflator
1166 readonly TypeSpec type;
1167 readonly TypeParameterSpec[] tparams;
1168 readonly TypeSpec[] targs;
1169 readonly IModuleContext context;
1171 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1172 : this (nested.context, type, nested.tparams, nested.targs)
1176 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1178 if (tparams.Length != targs.Length)
1179 throw new ArgumentException ("Invalid arguments");
1181 this.context = context;
1182 this.tparams = tparams;
1189 public IModuleContext Context {
1195 public TypeSpec TypeInstance {
1202 // Type parameters to inflate
1204 public TypeParameterSpec[] TypeParameters {
1212 public TypeSpec Inflate (TypeSpec type)
1214 var tp = type as TypeParameterSpec;
1216 return Inflate (tp);
1218 var ac = type as ArrayContainer;
1220 var et = Inflate (ac.Element);
1221 if (et != ac.Element)
1222 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1228 // When inflating a nested type, inflate its parent first
1229 // in case it's using same type parameters (was inflated within the type)
1233 if (type.IsNested) {
1234 var parent = Inflate (type.DeclaringType);
1237 // Keep the inflated type arguments
1239 targs = type.TypeArguments;
1242 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1243 // because the import cache helps us to catch it. However, that means we have to look at
1244 // type definition to get type argument (they are in fact type parameter in this case)
1246 if (targs.Length == 0 && type.Arity > 0)
1247 targs = type.MemberDefinition.TypeParameters;
1250 // Parent was inflated, find the same type on inflated type
1251 // to use same cache for nested types on same generic parent
1253 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1256 // Handle the tricky case where parent shares local type arguments
1257 // which means inflating inflated type
1260 // public static Nested<T> Foo () { return null; }
1262 // public class Nested<U> {}
1265 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1267 if (targs.Length > 0) {
1268 var inflated_targs = new TypeSpec[targs.Length];
1269 for (; i < targs.Length; ++i)
1270 inflated_targs[i] = Inflate (targs[i]);
1272 type = type.MakeGenericType (context, inflated_targs);
1278 // Nothing to do for non-generic type
1279 if (type.Arity == 0)
1282 targs = new TypeSpec[type.Arity];
1285 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1287 if (type is InflatedTypeSpec) {
1288 for (; i < targs.Length; ++i)
1289 targs[i] = Inflate (type.TypeArguments[i]);
1291 type = type.GetDefinition ();
1294 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1296 var args = type.MemberDefinition.TypeParameters;
1297 foreach (var ds_tp in args)
1298 targs[i++] = Inflate (ds_tp);
1301 return type.MakeGenericType (context, targs);
1304 public TypeSpec Inflate (TypeParameterSpec tp)
1306 for (int i = 0; i < tparams.Length; ++i)
1307 if (tparams [i] == tp)
1310 // This can happen when inflating nested types
1311 // without type arguments specified
1317 // Before emitting any code we have to change all MVAR references to VAR
1318 // when the method is of generic type and has hoisted variables
1320 public class TypeParameterMutator
1322 readonly TypeParameter[] mvar;
1323 readonly TypeParameter[] var;
1324 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1326 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1328 if (mvar.Length != var.Length)
1329 throw new ArgumentException ();
1337 public TypeParameter[] MethodTypeParameters {
1345 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1347 if (type is InflatedTypeSpec) {
1348 if (type.DeclaringType == null)
1349 return type.GetDefinition ();
1351 var parent = GetMemberDeclaringType (type.DeclaringType);
1352 type = MemberCache.GetMember<TypeSpec> (parent, type);
1358 public TypeSpec Mutate (TypeSpec ts)
1361 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1364 value = ts.Mutate (this);
1365 if (mutated_typespec == null)
1366 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1368 mutated_typespec.Add (ts, value);
1372 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1374 for (int i = 0; i < mvar.Length; ++i) {
1375 if (mvar[i].Type == tp)
1382 public TypeSpec[] Mutate (TypeSpec[] targs)
1384 TypeSpec[] mutated = new TypeSpec[targs.Length];
1385 bool changed = false;
1386 for (int i = 0; i < targs.Length; ++i) {
1387 mutated[i] = Mutate (targs[i]);
1388 changed |= targs[i] != mutated[i];
1391 return changed ? mutated : targs;
1396 /// A TypeExpr which already resolved to a type parameter.
1398 public class TypeParameterExpr : TypeExpression
1400 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1401 : base (type_parameter.Type, loc)
1403 this.eclass = ExprClass.TypeParameter;
1407 public class InflatedTypeSpec : TypeSpec
1410 TypeParameterSpec[] constraints;
1411 readonly TypeSpec open_type;
1412 readonly IModuleContext context;
1414 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1415 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1418 throw new ArgumentNullException ("targs");
1420 // this.state = openType.state;
1421 this.context = context;
1422 this.open_type = openType;
1425 foreach (var arg in targs) {
1426 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1427 state |= StateFlags.HasDynamicElement;
1432 if (open_type.Kind == MemberKind.MissingType)
1433 MemberCache = MemberCache.Empty;
1435 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1436 state |= StateFlags.ConstraintsChecked;
1441 public override TypeSpec BaseType {
1443 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1444 InitializeMemberCache (true);
1446 return base.BaseType;
1451 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1453 public TypeParameterSpec[] Constraints {
1455 if (constraints == null) {
1456 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1464 // Used to cache expensive constraints validation on constructed types
1466 public bool HasConstraintsChecked {
1468 return (state & StateFlags.ConstraintsChecked) != 0;
1471 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1475 public override IList<TypeSpec> Interfaces {
1478 InitializeMemberCache (true);
1480 return base.Interfaces;
1484 public override bool IsExpressionTreeType {
1486 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1490 public override bool IsGenericIterateInterface {
1492 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1496 public override bool IsNullableType {
1498 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1503 // Types used to inflate the generic type
1505 public override TypeSpec[] TypeArguments {
1513 public static bool ContainsTypeParameter (TypeSpec type)
1515 if (type.Kind == MemberKind.TypeParameter)
1518 var element_container = type as ElementTypeSpec;
1519 if (element_container != null)
1520 return ContainsTypeParameter (element_container.Element);
1522 foreach (var t in type.TypeArguments) {
1523 if (ContainsTypeParameter (t)) {
1531 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1533 TypeParameterSpec[] tparams_full;
1534 TypeSpec[] targs_full = targs;
1537 // Special case is needed when we are inflating an open type (nested type definition)
1538 // on inflated parent. Consider following case
1540 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1542 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1544 List<TypeSpec> merged_targs = null;
1545 List<TypeParameterSpec> merged_tparams = null;
1547 var type = DeclaringType;
1550 if (type.TypeArguments.Length > 0) {
1551 if (merged_targs == null) {
1552 merged_targs = new List<TypeSpec> ();
1553 merged_tparams = new List<TypeParameterSpec> ();
1554 if (targs.Length > 0) {
1555 merged_targs.AddRange (targs);
1556 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1559 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1560 merged_targs.AddRange (type.TypeArguments);
1562 type = type.DeclaringType;
1563 } while (type != null);
1565 if (merged_targs != null) {
1566 // Type arguments are not in the right order but it should not matter in this case
1567 targs_full = merged_targs.ToArray ();
1568 tparams_full = merged_tparams.ToArray ();
1569 } else if (targs.Length == 0) {
1570 tparams_full = TypeParameterSpec.EmptyTypes;
1572 tparams_full = open_type.MemberDefinition.TypeParameters;
1574 } else if (targs.Length == 0) {
1575 tparams_full = TypeParameterSpec.EmptyTypes;
1577 tparams_full = open_type.MemberDefinition.TypeParameters;
1580 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1583 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1586 // Converts nested type arguments into right order
1587 // Foo<string, bool>.Bar<int> => string, bool, int
1589 var all = new List<MetaType> ();
1590 TypeSpec type = this;
1591 TypeSpec definition = type;
1593 if (type.GetDefinition().IsGeneric) {
1595 type.TypeArguments != TypeSpec.EmptyTypes ?
1596 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1597 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1600 definition = definition.GetDefinition ();
1601 type = type.DeclaringType;
1602 } while (type != null);
1604 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1607 public override ObsoleteAttribute GetAttributeObsolete ()
1609 return open_type.GetAttributeObsolete ();
1612 protected override bool IsNotCLSCompliant (out bool attrValue)
1614 if (base.IsNotCLSCompliant (out attrValue))
1617 foreach (var ta in TypeArguments) {
1618 if (ta.MemberDefinition.CLSAttributeValue == false)
1625 public override TypeSpec GetDefinition ()
1630 public override MetaType GetMetaInfo ()
1633 info = CreateMetaInfo (null);
1638 public override string GetSignatureForError ()
1641 return targs[0].GetSignatureForError () + "?";
1643 return base.GetSignatureForError ();
1646 protected override string GetTypeNameSignature ()
1648 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1651 return "<" + TypeManager.CSharpName (targs) + ">";
1654 public bool HasDynamicArgument ()
1656 for (int i = 0; i < targs.Length; ++i) {
1657 var item = targs[i];
1659 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1662 if (item is InflatedTypeSpec) {
1663 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1670 while (item.IsArray) {
1671 item = ((ArrayContainer) item).Element;
1674 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1682 protected override void InitializeMemberCache (bool onlyTypes)
1684 if (cache == null) {
1685 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1687 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1688 // for imported type parameter constraints referencing nested type of this declaration
1690 cache = new MemberCache (open_cache);
1693 var inflator = CreateLocalInflator (context);
1696 // Two stage inflate due to possible nested types recursive
1706 // When resolving type of `b' members of `B' cannot be
1707 // inflated because are not yet available in membercache
1709 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1710 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1713 // Inflate any implemented interfaces
1715 if (open_type.Interfaces != null) {
1716 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1717 foreach (var iface in open_type.Interfaces) {
1718 var iface_inflated = inflator.Inflate (iface);
1719 if (iface_inflated == null)
1722 AddInterface (iface_inflated);
1727 // Handles the tricky case of recursive nested base generic type
1729 // class A<T> : Base<A<T>.Nested> {
1733 // When inflating A<T>. base type is not yet known, secondary
1734 // inflation is required (not common case) once base scope
1737 if (open_type.BaseType == null) {
1739 state |= StateFlags.PendingBaseTypeInflate;
1741 BaseType = inflator.Inflate (open_type.BaseType);
1743 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1744 BaseType = inflator.Inflate (open_type.BaseType);
1745 state &= ~StateFlags.PendingBaseTypeInflate;
1749 state |= StateFlags.PendingMemberCacheMembers;
1753 var tc = open_type.MemberDefinition as TypeContainer;
1754 if (tc != null && !tc.HasMembersDefined)
1755 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1757 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1758 BaseType = inflator.Inflate (open_type.BaseType);
1759 state &= ~StateFlags.PendingBaseTypeInflate;
1762 state &= ~StateFlags.PendingMemberCacheMembers;
1763 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1766 public override TypeSpec Mutate (TypeParameterMutator mutator)
1768 var targs = TypeArguments;
1770 targs = mutator.Mutate (targs);
1772 var decl = DeclaringType;
1773 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1774 decl = mutator.Mutate (decl);
1776 if (targs == TypeArguments && decl == DeclaringType)
1779 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1780 if (decl != DeclaringType) {
1781 // Gets back MethodInfo in case of metaInfo was inflated
1782 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1784 mutated.declaringType = decl;
1785 mutated.state |= StateFlags.PendingMetaInflate;
1788 if (targs != null) {
1789 mutated.targs = targs;
1790 mutated.info = null;
1799 // Tracks the type arguments when instantiating a generic type. It's used
1800 // by both type arguments and type parameters
1802 public class TypeArguments
1804 List<FullNamedExpression> args;
1807 public TypeArguments (params FullNamedExpression[] types)
1809 this.args = new List<FullNamedExpression> (types);
1812 public void Add (FullNamedExpression type)
1817 // TODO: Kill this monster
1818 public TypeParameterName[] GetDeclarations ()
1820 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1824 /// We may only be used after Resolve() is called and return the fully
1827 // TODO: Not needed, just return type from resolve
1828 public TypeSpec[] Arguments {
1840 public virtual bool IsEmpty {
1846 public string GetSignatureForError()
1848 StringBuilder sb = new StringBuilder ();
1849 for (int i = 0; i < Count; ++i) {
1852 sb.Append (expr.GetSignatureForError ());
1858 return sb.ToString ();
1862 /// Resolve the type arguments.
1864 public virtual bool Resolve (IMemberContext ec)
1867 return atypes.Length != 0;
1869 int count = args.Count;
1872 atypes = new TypeSpec [count];
1874 for (int i = 0; i < count; i++){
1875 var te = args[i].ResolveAsType (ec);
1884 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
1885 te.GetSignatureForError ());
1889 if (te.IsPointer || te.IsSpecialRuntimeType) {
1890 ec.Module.Compiler.Report.Error (306, args[i].Location,
1891 "The type `{0}' may not be used as a type argument",
1892 te.GetSignatureForError ());
1898 atypes = TypeSpec.EmptyTypes;
1903 public TypeArguments Clone ()
1905 TypeArguments copy = new TypeArguments ();
1906 foreach (var ta in args)
1913 public class UnboundTypeArguments : TypeArguments
1915 public UnboundTypeArguments (int arity)
1916 : base (new FullNamedExpression[arity])
1920 public override bool IsEmpty {
1926 public override bool Resolve (IMemberContext ec)
1928 // Nothing to be resolved
1933 public class TypeParameterName : SimpleName
1935 Attributes attributes;
1938 public TypeParameterName (string name, Attributes attrs, Location loc)
1939 : this (name, attrs, Variance.None, loc)
1943 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1947 this.variance = variance;
1950 public Attributes OptAttributes {
1956 public Variance Variance {
1964 // A type expression of generic type with type arguments
1966 class GenericTypeExpr : TypeExpr
1972 /// Instantiate the generic type `t' with the type arguments `args'.
1973 /// Use this constructor if you already know the fully resolved
1976 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1978 this.open_type = open_type;
1983 public TypeArguments TypeArguments {
1984 get { return args; }
1987 public override string GetSignatureForError ()
1989 return TypeManager.CSharpName (type);
1992 public override TypeSpec ResolveAsType (IMemberContext mc)
1994 if (eclass != ExprClass.Unresolved)
1997 if (!args.Resolve (mc))
2000 TypeSpec[] atypes = args.Arguments;
2003 // Now bind the parameters
2005 var inflated = open_type.MakeGenericType (mc, atypes);
2007 eclass = ExprClass.Type;
2010 // The constraints can be checked only when full type hierarchy is known
2012 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2013 var constraints = inflated.Constraints;
2014 if (constraints != null) {
2015 var cc = new ConstraintChecker (mc);
2016 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2017 inflated.HasConstraintsChecked = true;
2025 public override bool Equals (object obj)
2027 GenericTypeExpr cobj = obj as GenericTypeExpr;
2031 if ((type == null) || (cobj.type == null))
2034 return type == cobj.type;
2037 public override int GetHashCode ()
2039 return base.GetHashCode ();
2044 // Generic type with unbound type arguments, used for typeof (G<,,>)
2046 class GenericOpenTypeExpr : TypeExpression
2048 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2049 : base (type.GetDefinition (), loc)
2054 struct ConstraintChecker
2057 bool ignore_inferred_dynamic;
2058 bool recursive_checks;
2060 public ConstraintChecker (IMemberContext ctx)
2063 ignore_inferred_dynamic = false;
2064 recursive_checks = false;
2069 public bool IgnoreInferredDynamic {
2071 return ignore_inferred_dynamic;
2074 ignore_inferred_dynamic = value;
2081 // Checks the constraints of open generic type against type
2082 // arguments. This version is used for types which could not be
2083 // checked immediatelly during construction because the type
2084 // hierarchy was not yet fully setup (before Emit phase)
2086 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2089 // Check declaring type first if there is any
2091 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2094 while (type is ElementTypeSpec)
2095 type = ((ElementTypeSpec) type).Element;
2097 if (type.Arity == 0)
2100 var gtype = type as InflatedTypeSpec;
2104 var constraints = gtype.Constraints;
2105 if (constraints == null)
2108 if (gtype.HasConstraintsChecked)
2111 var cc = new ConstraintChecker (mc);
2112 cc.recursive_checks = true;
2114 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2115 gtype.HasConstraintsChecked = true;
2123 // Checks all type arguments againts type parameters constraints
2124 // NOTE: It can run in probing mode when `mc' is null
2126 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2128 for (int i = 0; i < tparams.Length; i++) {
2129 if (ignore_inferred_dynamic && targs[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2132 var targ = targs[i];
2133 if (!CheckConstraint (context, targ, tparams [i], loc))
2136 if (!recursive_checks)
2139 if (!Check (mc, targ, loc))
2146 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2149 // First, check the `class' and `struct' constraints.
2151 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2153 mc.Module.Compiler.Report.Error (452, loc,
2154 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2155 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2161 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2163 mc.Module.Compiler.Report.Error (453, loc,
2164 "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}'",
2165 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2174 // Check the class constraint
2176 if (tparam.HasTypeConstraint) {
2177 var dep = tparam.BaseType.GetMissingDependencies ();
2182 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2186 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2195 // Check the interfaces constraints
2197 if (tparam.Interfaces != null) {
2198 if (atype.IsNullableType) {
2202 mc.Module.Compiler.Report.Error (313, loc,
2203 "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",
2204 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2207 foreach (TypeSpec iface in tparam.Interfaces) {
2208 var dep = iface.GetMissingDependencies ();
2213 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2216 // return immediately to avoid duplicate errors because we are scanning
2217 // expanded interface list
2221 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2232 // Check the type parameter constraint
2234 if (tparam.TypeArguments != null) {
2235 foreach (var ta in tparam.TypeArguments) {
2236 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2246 // Finally, check the constructor constraint.
2248 if (!tparam.HasSpecialConstructor)
2251 if (!HasDefaultConstructor (atype)) {
2253 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2254 mc.Module.Compiler.Report.Error (310, loc,
2255 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2256 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2264 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2266 for (int i = 0; i < targs.Length; ++i) {
2267 var targ = targs [i];
2268 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2271 if (HasDynamicTypeArgument (targ.TypeArguments))
2278 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2280 if (atype.IsGenericParameter) {
2281 if (atype == ttype || Convert.ImplicitTypeParameterConversion (null, (TypeParameterSpec) atype, ttype) != null)
2283 } else if (TypeSpec.IsValueType (atype)) {
2284 if (atype == ttype || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2287 var expr = new EmptyExpression (atype);
2288 if (Convert.ImplicitStandardConversionExists (expr, ttype))
2293 // When partial/full type inference finds a dynamic type argument delay
2294 // the constraint check to runtime, it can succeed for real underlying
2297 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2301 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2302 if (atype.IsGenericParameter) {
2303 mc.Module.Compiler.Report.Error (314, loc,
2304 "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}'",
2305 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2306 } else if (TypeSpec.IsValueType (atype)) {
2307 mc.Module.Compiler.Report.Error (315, loc,
2308 "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}'",
2309 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2311 mc.Module.Compiler.Report.Error (311, loc,
2312 "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}'",
2313 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2320 bool HasDefaultConstructor (TypeSpec atype)
2322 var tp = atype as TypeParameterSpec;
2324 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2327 if (atype.IsStruct || atype.IsEnum)
2330 if (atype.IsAbstract)
2333 var tdef = atype.GetDefinition ();
2335 var found = MemberCache.FindMember (tdef,
2336 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2337 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2339 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2344 /// A generic method definition.
2346 public class GenericMethod : DeclSpace
2348 ParametersCompiled parameters;
2350 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name,
2351 FullNamedExpression return_type, ParametersCompiled parameters)
2352 : base (ns, parent, name, null)
2354 this.parameters = parameters;
2357 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2358 FullNamedExpression return_type, ParametersCompiled parameters)
2359 : this (ns, parent, name, return_type, parameters)
2361 this.type_params = tparams;
2364 public override TypeParameter[] CurrentTypeParameters {
2366 return base.type_params;
2370 protected override TypeAttributes TypeAttr {
2372 throw new NotSupportedException ();
2376 public override void DefineType ()
2378 throw new Exception ();
2381 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2383 throw new NotSupportedException ();
2386 public override bool Define ()
2388 throw new NotSupportedException ();
2392 /// Define and resolve the type parameters.
2393 /// We're called from Method.Define().
2395 public bool Define (MethodOrOperator m)
2397 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2398 string[] snames = new string [names.Length];
2399 var block = m.Block;
2400 for (int i = 0; i < names.Length; i++) {
2401 string type_argument_name = names[i].Name;
2403 if (block == null) {
2404 int idx = parameters.GetParameterIndexByName (type_argument_name);
2408 b = new ToplevelBlock (Compiler, Location);
2410 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2413 INamedBlockVariable variable = null;
2414 block.GetLocalName (type_argument_name, m.Block, ref variable);
2415 if (variable != null)
2416 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2419 snames[i] = type_argument_name;
2422 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2423 for (int i = 0; i < TypeParameters.Length; i++)
2424 TypeParameters [i].Define (gen_params [i], null);
2429 public void EmitAttributes ()
2431 if (OptAttributes != null)
2432 OptAttributes.Emit ();
2435 public override string GetSignatureForError ()
2437 return base.GetSignatureForError () + parameters.GetSignatureForError ();
2440 public override AttributeTargets AttributeTargets {
2442 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2446 public override string DocCommentHeader {
2447 get { return "M:"; }
2450 public new void VerifyClsCompliance ()
2452 foreach (TypeParameter tp in TypeParameters) {
2453 tp.VerifyClsCompliance ();
2458 public partial class TypeManager
2460 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2462 var tp = t as TypeParameterSpec;
2464 Variance v = tp.Variance;
2465 if (expected == Variance.None && v != expected ||
2466 expected == Variance.Covariant && v == Variance.Contravariant ||
2467 expected == Variance.Contravariant && v == Variance.Covariant) {
2468 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2474 if (t.TypeArguments.Length > 0) {
2475 var targs_definition = t.MemberDefinition.TypeParameters;
2476 TypeSpec[] targs = GetTypeArguments (t);
2477 for (int i = 0; i < targs.Length; ++i) {
2478 Variance v = targs_definition[i].Variance;
2479 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2486 return CheckTypeVariance (GetElementType (t), expected, member);
2488 return Variance.None;
2493 // Implements C# type inference
2498 // Tracks successful rate of type inference
2500 int score = int.MaxValue;
2501 readonly Arguments arguments;
2502 readonly int arg_count;
2504 public TypeInference (Arguments arguments)
2506 this.arguments = arguments;
2507 if (arguments != null)
2508 arg_count = arguments.Count;
2511 public int InferenceScore {
2517 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2519 var method_generic_args = method.GenericDefinition.TypeParameters;
2520 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2521 if (!context.UnfixedVariableExists)
2522 return TypeSpec.EmptyTypes;
2524 AParametersCollection pd = method.Parameters;
2525 if (!InferInPhases (ec, context, pd))
2528 return context.InferredTypeArguments;
2532 // Implements method type arguments inference
2534 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2536 int params_arguments_start;
2537 if (methodParameters.HasParams) {
2538 params_arguments_start = methodParameters.Count - 1;
2540 params_arguments_start = arg_count;
2543 TypeSpec [] ptypes = methodParameters.Types;
2546 // The first inference phase
2548 TypeSpec method_parameter = null;
2549 for (int i = 0; i < arg_count; i++) {
2550 Argument a = arguments [i];
2554 if (i < params_arguments_start) {
2555 method_parameter = methodParameters.Types [i];
2556 } else if (i == params_arguments_start) {
2557 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2558 method_parameter = methodParameters.Types [params_arguments_start];
2560 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2562 ptypes = (TypeSpec[]) ptypes.Clone ();
2563 ptypes [i] = method_parameter;
2567 // When a lambda expression, an anonymous method
2568 // is used an explicit argument type inference takes a place
2570 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2572 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2578 score -= tic.ExactInference (a.Type, method_parameter);
2582 if (a.Expr.Type == InternalType.NullLiteral)
2585 if (TypeSpec.IsValueType (method_parameter)) {
2586 score -= tic.LowerBoundInference (a.Type, method_parameter);
2591 // Otherwise an output type inference is made
2593 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2597 // Part of the second phase but because it happens only once
2598 // we don't need to call it in cycle
2600 bool fixed_any = false;
2601 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2604 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2607 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2609 bool fixed_any = false;
2610 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2613 // If no further unfixed type variables exist, type inference succeeds
2614 if (!tic.UnfixedVariableExists)
2617 if (!fixed_any && fixDependent)
2620 // For all arguments where the corresponding argument output types
2621 // contain unfixed type variables but the input types do not,
2622 // an output type inference is made
2623 for (int i = 0; i < arg_count; i++) {
2625 // Align params arguments
2626 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2628 if (!TypeManager.IsDelegateType (t_i)) {
2629 if (!t_i.IsExpressionTreeType)
2632 t_i = TypeManager.GetTypeArguments (t_i) [0];
2635 var mi = Delegate.GetInvokeMethod (t_i);
2636 TypeSpec rtype = mi.ReturnType;
2638 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2639 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2643 return DoSecondPhase (ec, tic, methodParameters, true);
2647 public class TypeInferenceContext
2649 protected enum BoundKind
2656 protected class BoundInfo : IEquatable<BoundInfo>
2658 public readonly TypeSpec Type;
2659 public readonly BoundKind Kind;
2661 public BoundInfo (TypeSpec type, BoundKind kind)
2667 public override int GetHashCode ()
2669 return Type.GetHashCode ();
2672 public virtual Expression GetTypeExpression ()
2674 return new TypeExpression (Type, Location.Null);
2677 #region IEquatable<BoundInfo> Members
2679 public virtual bool Equals (BoundInfo other)
2681 return Type == other.Type && Kind == other.Kind;
2687 readonly TypeSpec[] tp_args;
2688 readonly TypeSpec[] fixed_types;
2689 readonly List<BoundInfo>[] bounds;
2692 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2693 public TypeInferenceContext (TypeSpec[] typeArguments)
2695 if (typeArguments.Length == 0)
2696 throw new ArgumentException ("Empty generic arguments");
2698 fixed_types = new TypeSpec [typeArguments.Length];
2699 for (int i = 0; i < typeArguments.Length; ++i) {
2700 if (typeArguments [i].IsGenericParameter) {
2701 if (bounds == null) {
2702 bounds = new List<BoundInfo> [typeArguments.Length];
2703 tp_args = new TypeSpec [typeArguments.Length];
2705 tp_args [i] = typeArguments [i];
2707 fixed_types [i] = typeArguments [i];
2713 // Used together with AddCommonTypeBound fo implement
2714 // 7.4.2.13 Finding the best common type of a set of expressions
2716 public TypeInferenceContext ()
2718 fixed_types = new TypeSpec [1];
2719 tp_args = new TypeSpec [1];
2720 tp_args[0] = InternalType.Arglist; // it can be any internal type
2721 bounds = new List<BoundInfo> [1];
2724 public TypeSpec[] InferredTypeArguments {
2730 public void AddCommonTypeBound (TypeSpec type)
2732 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2735 protected void AddToBounds (BoundInfo bound, int index)
2738 // Some types cannot be used as type arguments
2740 if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType)
2743 var a = bounds [index];
2745 a = new List<BoundInfo> (2);
2751 if (a.Contains (bound))
2757 bool AllTypesAreFixed (TypeSpec[] types)
2759 foreach (TypeSpec t in types) {
2760 if (t.IsGenericParameter) {
2766 if (TypeManager.IsGenericType (t))
2767 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2774 // 26.3.3.8 Exact Inference
2776 public int ExactInference (TypeSpec u, TypeSpec v)
2778 // If V is an array type
2783 // TODO MemberCache: GetMetaInfo ()
2784 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2787 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2790 // If V is constructed type and U is constructed type
2791 if (TypeManager.IsGenericType (v)) {
2792 if (!TypeManager.IsGenericType (u))
2795 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2796 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2797 if (ga_u.Length != ga_v.Length)
2801 for (int i = 0; i < ga_u.Length; ++i)
2802 score += ExactInference (ga_u [i], ga_v [i]);
2804 return score > 0 ? 1 : 0;
2807 // If V is one of the unfixed type arguments
2808 int pos = IsUnfixed (v);
2812 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2816 public bool FixAllTypes (ResolveContext ec)
2818 for (int i = 0; i < tp_args.Length; ++i) {
2819 if (!FixType (ec, i))
2826 // All unfixed type variables Xi are fixed for which all of the following hold:
2827 // a, There is at least one type variable Xj that depends on Xi
2828 // b, Xi has a non-empty set of bounds
2830 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2832 for (int i = 0; i < tp_args.Length; ++i) {
2833 if (fixed_types[i] != null)
2836 if (bounds[i] == null)
2839 if (!FixType (ec, i))
2849 // All unfixed type variables Xi which depend on no Xj are fixed
2851 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2853 var types_to_fix = new List<TypeSpec> (tp_args);
2854 for (int i = 0; i < methodParameters.Length; ++i) {
2855 TypeSpec t = methodParameters[i];
2857 if (!TypeManager.IsDelegateType (t)) {
2858 if (!t.IsExpressionTreeType)
2861 t = TypeManager.GetTypeArguments (t) [0];
2864 if (t.IsGenericParameter)
2867 var invoke = Delegate.GetInvokeMethod (t);
2868 TypeSpec rtype = invoke.ReturnType;
2869 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2872 // Remove dependent types, they cannot be fixed yet
2873 RemoveDependentTypes (types_to_fix, rtype);
2876 foreach (TypeSpec t in types_to_fix) {
2880 int idx = IsUnfixed (t);
2881 if (idx >= 0 && !FixType (ec, idx)) {
2886 fixed_any = types_to_fix.Count > 0;
2893 public bool FixType (ResolveContext ec, int i)
2895 // It's already fixed
2896 if (fixed_types[i] != null)
2897 throw new InternalErrorException ("Type argument has been already fixed");
2902 var candidates = bounds [i];
2903 if (candidates == null)
2906 if (candidates.Count == 1) {
2907 TypeSpec t = candidates[0].Type;
2908 if (t == InternalType.NullLiteral)
2911 fixed_types [i] = t;
2916 // Determines a unique type from which there is
2917 // a standard implicit conversion to all the other
2920 TypeSpec best_candidate = null;
2922 int candidates_count = candidates.Count;
2923 for (int ci = 0; ci < candidates_count; ++ci) {
2924 BoundInfo bound = candidates [ci];
2925 for (cii = 0; cii < candidates_count; ++cii) {
2929 BoundInfo cbound = candidates[cii];
2931 // Same type parameters with different bounds
2932 if (cbound.Type == bound.Type) {
2933 if (bound.Kind != BoundKind.Exact)
2939 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2940 if (cbound.Kind == BoundKind.Lower) {
2941 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2947 if (cbound.Kind == BoundKind.Upper) {
2948 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2955 if (bound.Kind != BoundKind.Exact) {
2956 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2967 if (bound.Kind == BoundKind.Lower) {
2968 if (cbound.Kind == BoundKind.Lower) {
2969 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2973 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2983 if (bound.Kind == BoundKind.Upper) {
2984 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2988 throw new NotImplementedException ("variance conversion");
2992 if (cii != candidates_count)
2996 // We already have the best candidate, break if thet are different
2998 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3000 if (best_candidate != null) {
3002 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3005 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3009 best_candidate = bound.Type;
3012 if (best_candidate == null)
3015 fixed_types[i] = best_candidate;
3020 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3021 // null when type parameter has not been fixed
3023 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3025 var tp = parameter as TypeParameterSpec;
3028 // Type inference works on generic arguments (MVAR) only
3030 if (!tp.IsMethodOwned)
3034 // Ensure the type parameter belongs to same container
3036 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3037 return fixed_types[tp.DeclaredPosition] ?? parameter;
3042 var gt = parameter as InflatedTypeSpec;
3044 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3045 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3046 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3047 if (inflated == null)
3050 inflated_targs[ii] = inflated;
3053 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3060 // Tests whether all delegate input arguments are fixed and generic output type
3061 // requires output type inference
3063 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3065 if (returnType.IsGenericParameter) {
3066 if (IsFixed (returnType))
3068 } else if (TypeManager.IsGenericType (returnType)) {
3069 if (TypeManager.IsDelegateType (returnType)) {
3070 invoke = Delegate.GetInvokeMethod (returnType);
3071 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3074 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3076 // At least one unfixed return type has to exist
3077 if (AllTypesAreFixed (g_args))
3083 // All generic input arguments have to be fixed
3084 AParametersCollection d_parameters = invoke.Parameters;
3085 return AllTypesAreFixed (d_parameters.Types);
3088 bool IsFixed (TypeSpec type)
3090 return IsUnfixed (type) == -1;
3093 int IsUnfixed (TypeSpec type)
3095 if (!type.IsGenericParameter)
3098 for (int i = 0; i < tp_args.Length; ++i) {
3099 if (tp_args[i] == type) {
3100 if (fixed_types[i] != null)
3111 // 26.3.3.9 Lower-bound Inference
3113 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3115 return LowerBoundInference (u, v, false);
3119 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3121 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3123 // If V is one of the unfixed type arguments
3124 int pos = IsUnfixed (v);
3126 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3130 // If U is an array type
3131 var u_ac = u as ArrayContainer;
3133 var v_ac = v as ArrayContainer;
3135 if (u_ac.Rank != v_ac.Rank)
3138 if (TypeSpec.IsValueType (u_ac.Element))
3139 return ExactInference (u_ac.Element, v_ac.Element);
3141 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3144 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3147 var v_i = TypeManager.GetTypeArguments (v) [0];
3148 if (TypeSpec.IsValueType (u_ac.Element))
3149 return ExactInference (u_ac.Element, v_i);
3151 return LowerBoundInference (u_ac.Element, v_i);
3154 if (TypeManager.IsGenericType (v)) {
3156 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3157 // such that U is identical to, inherits from (directly or indirectly),
3158 // or implements (directly or indirectly) C<U1..Uk>
3160 var u_candidates = new List<TypeSpec> ();
3161 var open_v = v.MemberDefinition;
3163 for (TypeSpec t = u; t != null; t = t.BaseType) {
3164 if (open_v == t.MemberDefinition)
3165 u_candidates.Add (t);
3168 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3169 // that would complicate the process a lot, instead I treat them as dynamic
3171 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3172 u_candidates.Add (t);
3174 if (t.Interfaces != null) {
3175 foreach (var iface in t.Interfaces) {
3176 if (open_v == iface.MemberDefinition)
3177 u_candidates.Add (iface);
3182 TypeSpec [] unique_candidate_targs = null;
3183 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
3184 foreach (TypeSpec u_candidate in u_candidates) {
3186 // The unique set of types U1..Uk means that if we have an interface I<T>,
3187 // class U : I<int>, I<long> then no type inference is made when inferring
3188 // type I<T> by applying type U because T could be int or long
3190 if (unique_candidate_targs != null) {
3191 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3192 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3193 unique_candidate_targs = second_unique_candidate_targs;
3198 // This should always cause type inference failure
3205 // A candidate is dynamic type expression, to simplify things use dynamic
3206 // for all type parameter of this type. For methods like this one
3208 // void M<T, U> (IList<T>, IList<U[]>)
3210 // dynamic becomes both T and U when the arguments are of dynamic type
3212 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3213 unique_candidate_targs = new TypeSpec[ga_v.Length];
3214 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3215 unique_candidate_targs[i] = u_candidate;
3217 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3221 if (unique_candidate_targs != null) {
3222 var ga_open_v = open_v.TypeParameters;
3224 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3225 Variance variance = ga_open_v [i].Variance;
3227 TypeSpec u_i = unique_candidate_targs [i];
3228 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3229 if (ExactInference (u_i, ga_v [i]) == 0)
3232 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3233 (variance == Variance.Covariant && inversed);
3235 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3247 // 26.3.3.6 Output Type Inference
3249 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3251 // If e is a lambda or anonymous method with inferred return type
3252 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3254 TypeSpec rt = ame.InferReturnType (ec, this, t);
3255 var invoke = Delegate.GetInvokeMethod (t);
3258 AParametersCollection pd = invoke.Parameters;
3259 return ame.Parameters.Count == pd.Count ? 1 : 0;
3262 TypeSpec rtype = invoke.ReturnType;
3263 return LowerBoundInference (rt, rtype) + 1;
3267 // if E is a method group and T is a delegate type or expression tree type
3268 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3269 // resolution of E with the types T1..Tk yields a single method with return type U,
3270 // then a lower-bound inference is made from U for Tb.
3272 if (e is MethodGroupExpr) {
3273 if (!TypeManager.IsDelegateType (t)) {
3274 if (!t.IsExpressionTreeType)
3277 t = TypeManager.GetTypeArguments (t)[0];
3280 var invoke = Delegate.GetInvokeMethod (t);
3281 TypeSpec rtype = invoke.ReturnType;
3283 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3286 // LAMESPEC: Standard does not specify that all methodgroup arguments
3287 // has to be fixed but it does not specify how to do recursive type inference
3288 // either. We choose the simple option and infer return type only
3289 // if all delegate generic arguments are fixed.
3290 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3291 for (int i = 0; i < param_types.Length; ++i) {
3292 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3293 if (inflated == null)
3296 if (IsUnfixed (inflated) >= 0)
3299 param_types[i] = inflated;
3302 MethodGroupExpr mg = (MethodGroupExpr) e;
3303 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3304 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3308 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3312 // if e is an expression with type U, then
3313 // a lower-bound inference is made from U for T
3315 return LowerBoundInference (e.Type, t) * 2;
3318 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3320 int idx = IsUnfixed (returnType);
3326 if (TypeManager.IsGenericType (returnType)) {
3327 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3328 RemoveDependentTypes (types, t);
3333 public bool UnfixedVariableExists {
3335 foreach (TypeSpec ut in fixed_types) {