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.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. The effective base class is always a class-type
860 public TypeSpec GetEffectiveBase ()
862 if (HasSpecialStruct)
866 // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
868 if (BaseType != null && targs == null) {
870 // If T has a constraint V that is a value-type, use instead the most specific base type of V that is a class-type.
872 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
874 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
875 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
877 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
881 if (HasTypeConstraint) {
882 Array.Resize (ref types, types.Length + 1);
883 types[types.Length - 1] = BaseType;
887 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
892 public override string GetSignatureForDocumentation ()
895 var type = DeclaringType;
896 while (type != null && type.DeclaringType != null) {
897 type = type.DeclaringType;
898 c += type.MemberDefinition.TypeParametersCount;
901 var prefix = IsMethodOwned ? "``" : "`";
902 return prefix + (c + DeclaredPosition);
905 public override string GetSignatureForError ()
911 // Constraints have to match by definition but not position, used by
912 // partial classes or methods
914 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
916 if (spec != other.spec)
919 if (BaseType != other.BaseType)
922 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
925 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
932 // Constraints have to match by using same set of types, used by
933 // implicit interface implementation
935 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
937 if (spec != other.spec)
941 // It can be same base type or inflated type parameter
943 // interface I<T> { void Foo<U> where U : T; }
944 // class A : I<int> { void Foo<X> where X : int {} }
947 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
948 if (other.targs == null)
952 foreach (var otarg in other.targs) {
953 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
963 // Check interfaces implementation -> definition
964 if (InterfacesDefined != null) {
965 foreach (var iface in InterfacesDefined) {
967 if (other.InterfacesDefined != null) {
968 foreach (var oiface in other.InterfacesDefined) {
969 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
979 if (other.targs != null) {
980 foreach (var otarg in other.targs) {
981 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
993 // Check interfaces implementation <- definition
994 if (other.InterfacesDefined != null) {
995 if (InterfacesDefined == null)
998 foreach (var oiface in other.InterfacesDefined) {
1000 foreach (var iface in InterfacesDefined) {
1001 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1012 // Check type parameters implementation -> definition
1013 if (targs != null) {
1014 if (other.targs == null)
1017 foreach (var targ in targs) {
1019 foreach (var otarg in other.targs) {
1020 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1031 // Check type parameters implementation <- definition
1032 if (other.targs != null) {
1033 foreach (var otarg in other.targs) {
1034 // Ignore inflated type arguments, were checked above
1035 if (!otarg.IsGenericParameter)
1042 foreach (var targ in targs) {
1043 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1057 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1059 return InflateConstraints (tparams, l => l, inflator);
1062 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1064 TypeParameterSpec[] constraints = null;
1065 TypeParameterInflator? inflator = null;
1067 for (int i = 0; i < tparams.Length; ++i) {
1068 var tp = tparams[i];
1069 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1070 if (constraints == null) {
1071 constraints = new TypeParameterSpec[tparams.Length];
1072 Array.Copy (tparams, constraints, constraints.Length);
1076 // Using a factory to avoid possibly expensive inflator build up
1078 if (inflator == null)
1079 inflator = inflatorFactory (arg);
1081 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1085 if (constraints == null)
1086 constraints = tparams;
1091 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1093 tps.BaseType = inflator.Inflate (BaseType);
1094 if (ifaces != null) {
1095 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1096 for (int i = 0; i < ifaces.Count; ++i)
1097 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1100 if (targs != null) {
1101 tps.targs = new TypeSpec[targs.Length];
1102 for (int i = 0; i < targs.Length; ++i)
1103 tps.targs[i] = inflator.Inflate (targs[i]);
1107 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1109 var tps = (TypeParameterSpec) MemberwiseClone ();
1110 InflateConstraints (inflator, tps);
1115 // Populates type parameter members using type parameter constraints
1116 // The trick here is to be called late enough but not too late to
1117 // populate member cache with all members from other types
1119 protected override void InitializeMemberCache (bool onlyTypes)
1121 cache = new MemberCache ();
1124 // For a type parameter the membercache is the union of the sets of members of the types
1125 // specified as a primary constraint or secondary constraint
1127 if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1128 cache.AddBaseType (BaseType);
1130 if (ifaces != null) {
1131 foreach (var iface_type in Interfaces) {
1132 cache.AddInterface (iface_type);
1136 if (targs != null) {
1137 foreach (var ta in targs) {
1138 var b_type = ta.BaseType;
1139 if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1140 cache.AddBaseType (b_type);
1142 if (ta.Interfaces != null) {
1143 foreach (var iface_type in ta.Interfaces) {
1144 cache.AddInterface (iface_type);
1151 public bool IsConvertibleToInterface (TypeSpec iface)
1153 if (Interfaces != null) {
1154 foreach (var t in Interfaces) {
1160 if (TypeArguments != null) {
1161 foreach (var t in TypeArguments) {
1162 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1170 public override TypeSpec Mutate (TypeParameterMutator mutator)
1172 return mutator.Mutate (this);
1176 public struct TypeParameterInflator
1178 readonly TypeSpec type;
1179 readonly TypeParameterSpec[] tparams;
1180 readonly TypeSpec[] targs;
1181 readonly IModuleContext context;
1183 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1184 : this (nested.context, type, nested.tparams, nested.targs)
1188 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1190 if (tparams.Length != targs.Length)
1191 throw new ArgumentException ("Invalid arguments");
1193 this.context = context;
1194 this.tparams = tparams;
1201 public IModuleContext Context {
1207 public TypeSpec TypeInstance {
1214 // Type parameters to inflate
1216 public TypeParameterSpec[] TypeParameters {
1224 public TypeSpec Inflate (TypeSpec type)
1226 var tp = type as TypeParameterSpec;
1228 return Inflate (tp);
1230 var ac = type as ArrayContainer;
1232 var et = Inflate (ac.Element);
1233 if (et != ac.Element)
1234 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1240 // When inflating a nested type, inflate its parent first
1241 // in case it's using same type parameters (was inflated within the type)
1245 if (type.IsNested) {
1246 var parent = Inflate (type.DeclaringType);
1249 // Keep the inflated type arguments
1251 targs = type.TypeArguments;
1254 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1255 // because the import cache helps us to catch it. However, that means we have to look at
1256 // type definition to get type argument (they are in fact type parameter in this case)
1258 if (targs.Length == 0 && type.Arity > 0)
1259 targs = type.MemberDefinition.TypeParameters;
1262 // Parent was inflated, find the same type on inflated type
1263 // to use same cache for nested types on same generic parent
1265 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1268 // Handle the tricky case where parent shares local type arguments
1269 // which means inflating inflated type
1272 // public static Nested<T> Foo () { return null; }
1274 // public class Nested<U> {}
1277 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1279 if (targs.Length > 0) {
1280 var inflated_targs = new TypeSpec[targs.Length];
1281 for (; i < targs.Length; ++i)
1282 inflated_targs[i] = Inflate (targs[i]);
1284 type = type.MakeGenericType (context, inflated_targs);
1290 // Nothing to do for non-generic type
1291 if (type.Arity == 0)
1294 targs = new TypeSpec[type.Arity];
1297 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1299 if (type is InflatedTypeSpec) {
1300 for (; i < targs.Length; ++i)
1301 targs[i] = Inflate (type.TypeArguments[i]);
1303 type = type.GetDefinition ();
1306 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1308 var args = type.MemberDefinition.TypeParameters;
1309 foreach (var ds_tp in args)
1310 targs[i++] = Inflate (ds_tp);
1313 return type.MakeGenericType (context, targs);
1316 public TypeSpec Inflate (TypeParameterSpec tp)
1318 for (int i = 0; i < tparams.Length; ++i)
1319 if (tparams [i] == tp)
1322 // This can happen when inflating nested types
1323 // without type arguments specified
1329 // Before emitting any code we have to change all MVAR references to VAR
1330 // when the method is of generic type and has hoisted variables
1332 public class TypeParameterMutator
1334 readonly TypeParameter[] mvar;
1335 readonly TypeParameter[] var;
1336 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1338 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1340 if (mvar.Length != var.Length)
1341 throw new ArgumentException ();
1349 public TypeParameter[] MethodTypeParameters {
1357 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1359 if (type is InflatedTypeSpec) {
1360 if (type.DeclaringType == null)
1361 return type.GetDefinition ();
1363 var parent = GetMemberDeclaringType (type.DeclaringType);
1364 type = MemberCache.GetMember<TypeSpec> (parent, type);
1370 public TypeSpec Mutate (TypeSpec ts)
1373 if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1376 value = ts.Mutate (this);
1377 if (mutated_typespec == null)
1378 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1380 mutated_typespec.Add (ts, value);
1384 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1386 for (int i = 0; i < mvar.Length; ++i) {
1387 if (mvar[i].Type == tp)
1394 public TypeSpec[] Mutate (TypeSpec[] targs)
1396 TypeSpec[] mutated = new TypeSpec[targs.Length];
1397 bool changed = false;
1398 for (int i = 0; i < targs.Length; ++i) {
1399 mutated[i] = Mutate (targs[i]);
1400 changed |= targs[i] != mutated[i];
1403 return changed ? mutated : targs;
1408 /// A TypeExpr which already resolved to a type parameter.
1410 public class TypeParameterExpr : TypeExpression
1412 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1413 : base (type_parameter.Type, loc)
1415 this.eclass = ExprClass.TypeParameter;
1419 public class InflatedTypeSpec : TypeSpec
1422 TypeParameterSpec[] constraints;
1423 readonly TypeSpec open_type;
1424 readonly IModuleContext context;
1426 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1427 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1430 throw new ArgumentNullException ("targs");
1432 // this.state = openType.state;
1433 this.context = context;
1434 this.open_type = openType;
1437 foreach (var arg in targs) {
1438 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1439 state |= StateFlags.HasDynamicElement;
1444 if (open_type.Kind == MemberKind.MissingType)
1445 MemberCache = MemberCache.Empty;
1447 if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1448 state |= StateFlags.ConstraintsChecked;
1453 public override TypeSpec BaseType {
1455 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1456 InitializeMemberCache (true);
1458 return base.BaseType;
1463 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1465 public TypeParameterSpec[] Constraints {
1467 if (constraints == null) {
1468 constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1476 // Used to cache expensive constraints validation on constructed types
1478 public bool HasConstraintsChecked {
1480 return (state & StateFlags.ConstraintsChecked) != 0;
1483 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1487 public override IList<TypeSpec> Interfaces {
1490 InitializeMemberCache (true);
1492 return base.Interfaces;
1496 public override bool IsExpressionTreeType {
1498 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1502 public override bool IsGenericIterateInterface {
1504 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1508 public override bool IsGenericTask {
1510 return (open_type.state & StateFlags.GenericTask) != 0;
1514 public override bool IsNullableType {
1516 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1521 // Types used to inflate the generic type
1523 public override TypeSpec[] TypeArguments {
1531 public static bool ContainsTypeParameter (TypeSpec type)
1533 if (type.Kind == MemberKind.TypeParameter)
1536 var element_container = type as ElementTypeSpec;
1537 if (element_container != null)
1538 return ContainsTypeParameter (element_container.Element);
1540 foreach (var t in type.TypeArguments) {
1541 if (ContainsTypeParameter (t)) {
1549 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1551 TypeParameterSpec[] tparams_full;
1552 TypeSpec[] targs_full = targs;
1555 // Special case is needed when we are inflating an open type (nested type definition)
1556 // on inflated parent. Consider following case
1558 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1560 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1562 List<TypeSpec> merged_targs = null;
1563 List<TypeParameterSpec> merged_tparams = null;
1565 var type = DeclaringType;
1568 if (type.TypeArguments.Length > 0) {
1569 if (merged_targs == null) {
1570 merged_targs = new List<TypeSpec> ();
1571 merged_tparams = new List<TypeParameterSpec> ();
1572 if (targs.Length > 0) {
1573 merged_targs.AddRange (targs);
1574 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1577 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1578 merged_targs.AddRange (type.TypeArguments);
1580 type = type.DeclaringType;
1581 } while (type != null);
1583 if (merged_targs != null) {
1584 // Type arguments are not in the right order but it should not matter in this case
1585 targs_full = merged_targs.ToArray ();
1586 tparams_full = merged_tparams.ToArray ();
1587 } else if (targs.Length == 0) {
1588 tparams_full = TypeParameterSpec.EmptyTypes;
1590 tparams_full = open_type.MemberDefinition.TypeParameters;
1592 } else if (targs.Length == 0) {
1593 tparams_full = TypeParameterSpec.EmptyTypes;
1595 tparams_full = open_type.MemberDefinition.TypeParameters;
1598 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1601 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1604 // Converts nested type arguments into right order
1605 // Foo<string, bool>.Bar<int> => string, bool, int
1607 var all = new List<MetaType> ();
1608 TypeSpec type = this;
1609 TypeSpec definition = type;
1611 if (type.GetDefinition().IsGeneric) {
1613 type.TypeArguments != TypeSpec.EmptyTypes ?
1614 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1615 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1618 definition = definition.GetDefinition ();
1619 type = type.DeclaringType;
1620 } while (type != null);
1622 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1625 public override ObsoleteAttribute GetAttributeObsolete ()
1627 return open_type.GetAttributeObsolete ();
1630 protected override bool IsNotCLSCompliant (out bool attrValue)
1632 if (base.IsNotCLSCompliant (out attrValue))
1635 foreach (var ta in TypeArguments) {
1636 if (ta.MemberDefinition.CLSAttributeValue == false)
1643 public override TypeSpec GetDefinition ()
1648 public override MetaType GetMetaInfo ()
1651 info = CreateMetaInfo (null);
1656 public override string GetSignatureForError ()
1659 return targs[0].GetSignatureForError () + "?";
1661 return base.GetSignatureForError ();
1664 protected override string GetTypeNameSignature ()
1666 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1669 return "<" + TypeManager.CSharpName (targs) + ">";
1672 public bool HasDynamicArgument ()
1674 for (int i = 0; i < targs.Length; ++i) {
1675 var item = targs[i];
1677 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1680 if (item is InflatedTypeSpec) {
1681 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1688 while (item.IsArray) {
1689 item = ((ArrayContainer) item).Element;
1692 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1700 protected override void InitializeMemberCache (bool onlyTypes)
1702 if (cache == null) {
1703 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1705 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1706 // for imported type parameter constraints referencing nested type of this declaration
1708 cache = new MemberCache (open_cache);
1711 var inflator = CreateLocalInflator (context);
1714 // Two stage inflate due to possible nested types recursive
1724 // When resolving type of `b' members of `B' cannot be
1725 // inflated because are not yet available in membercache
1727 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1728 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1731 // Inflate any implemented interfaces
1733 if (open_type.Interfaces != null) {
1734 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1735 foreach (var iface in open_type.Interfaces) {
1736 var iface_inflated = inflator.Inflate (iface);
1737 if (iface_inflated == null)
1740 AddInterface (iface_inflated);
1745 // Handles the tricky case of recursive nested base generic type
1747 // class A<T> : Base<A<T>.Nested> {
1751 // When inflating A<T>. base type is not yet known, secondary
1752 // inflation is required (not common case) once base scope
1755 if (open_type.BaseType == null) {
1757 state |= StateFlags.PendingBaseTypeInflate;
1759 BaseType = inflator.Inflate (open_type.BaseType);
1761 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1762 BaseType = inflator.Inflate (open_type.BaseType);
1763 state &= ~StateFlags.PendingBaseTypeInflate;
1767 state |= StateFlags.PendingMemberCacheMembers;
1771 var tc = open_type.MemberDefinition as TypeContainer;
1772 if (tc != null && !tc.HasMembersDefined)
1773 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1775 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1776 BaseType = inflator.Inflate (open_type.BaseType);
1777 state &= ~StateFlags.PendingBaseTypeInflate;
1780 state &= ~StateFlags.PendingMemberCacheMembers;
1781 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1784 public override TypeSpec Mutate (TypeParameterMutator mutator)
1786 var targs = TypeArguments;
1788 targs = mutator.Mutate (targs);
1790 var decl = DeclaringType;
1791 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1792 decl = mutator.Mutate (decl);
1794 if (targs == TypeArguments && decl == DeclaringType)
1797 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1798 if (decl != DeclaringType) {
1799 // Gets back MethodInfo in case of metaInfo was inflated
1800 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1802 mutated.declaringType = decl;
1803 mutated.state |= StateFlags.PendingMetaInflate;
1806 if (targs != null) {
1807 mutated.targs = targs;
1808 mutated.info = null;
1817 // Tracks the type arguments when instantiating a generic type. It's used
1818 // by both type arguments and type parameters
1820 public class TypeArguments
1822 List<FullNamedExpression> args;
1825 public TypeArguments (params FullNamedExpression[] types)
1827 this.args = new List<FullNamedExpression> (types);
1830 public void Add (FullNamedExpression type)
1835 // TODO: Kill this monster
1836 public TypeParameterName[] GetDeclarations ()
1838 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1842 /// We may only be used after Resolve() is called and return the fully
1845 // TODO: Not needed, just return type from resolve
1846 public TypeSpec[] Arguments {
1861 public virtual bool IsEmpty {
1867 public string GetSignatureForError()
1869 StringBuilder sb = new StringBuilder ();
1870 for (int i = 0; i < Count; ++i) {
1873 sb.Append (expr.GetSignatureForError ());
1879 return sb.ToString ();
1883 /// Resolve the type arguments.
1885 public virtual bool Resolve (IMemberContext ec)
1888 return atypes.Length != 0;
1890 int count = args.Count;
1893 atypes = new TypeSpec [count];
1895 for (int i = 0; i < count; i++){
1896 var te = args[i].ResolveAsType (ec);
1905 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
1906 te.GetSignatureForError ());
1910 if (te.IsPointer || te.IsSpecialRuntimeType) {
1911 ec.Module.Compiler.Report.Error (306, args[i].Location,
1912 "The type `{0}' may not be used as a type argument",
1913 te.GetSignatureForError ());
1919 atypes = TypeSpec.EmptyTypes;
1924 public TypeArguments Clone ()
1926 TypeArguments copy = new TypeArguments ();
1927 foreach (var ta in args)
1934 public class UnboundTypeArguments : TypeArguments
1936 public UnboundTypeArguments (int arity)
1937 : base (new FullNamedExpression[arity])
1941 public override bool IsEmpty {
1947 public override bool Resolve (IMemberContext ec)
1949 // Nothing to be resolved
1954 public class TypeParameterName : SimpleName
1956 Attributes attributes;
1959 public TypeParameterName (string name, Attributes attrs, Location loc)
1960 : this (name, attrs, Variance.None, loc)
1964 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1968 this.variance = variance;
1971 public Attributes OptAttributes {
1977 public Variance Variance {
1985 // A type expression of generic type with type arguments
1987 class GenericTypeExpr : TypeExpr
1993 /// Instantiate the generic type `t' with the type arguments `args'.
1994 /// Use this constructor if you already know the fully resolved
1997 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1999 this.open_type = open_type;
2004 public TypeArguments TypeArguments {
2005 get { return args; }
2008 public override string GetSignatureForError ()
2010 return TypeManager.CSharpName (type);
2013 public override TypeSpec ResolveAsType (IMemberContext mc)
2015 if (eclass != ExprClass.Unresolved)
2018 if (!args.Resolve (mc))
2021 TypeSpec[] atypes = args.Arguments;
2024 // Now bind the parameters
2026 var inflated = open_type.MakeGenericType (mc, atypes);
2028 eclass = ExprClass.Type;
2031 // The constraints can be checked only when full type hierarchy is known
2033 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2034 var constraints = inflated.Constraints;
2035 if (constraints != null) {
2036 var cc = new ConstraintChecker (mc);
2037 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2038 inflated.HasConstraintsChecked = true;
2046 public override bool Equals (object obj)
2048 GenericTypeExpr cobj = obj as GenericTypeExpr;
2052 if ((type == null) || (cobj.type == null))
2055 return type == cobj.type;
2058 public override int GetHashCode ()
2060 return base.GetHashCode ();
2065 // Generic type with unbound type arguments, used for typeof (G<,,>)
2067 class GenericOpenTypeExpr : TypeExpression
2069 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2070 : base (type.GetDefinition (), loc)
2075 struct ConstraintChecker
2078 bool ignore_inferred_dynamic;
2079 bool recursive_checks;
2081 public ConstraintChecker (IMemberContext ctx)
2084 ignore_inferred_dynamic = false;
2085 recursive_checks = false;
2090 public bool IgnoreInferredDynamic {
2092 return ignore_inferred_dynamic;
2095 ignore_inferred_dynamic = value;
2102 // Checks the constraints of open generic type against type
2103 // arguments. This version is used for types which could not be
2104 // checked immediatelly during construction because the type
2105 // hierarchy was not yet fully setup (before Emit phase)
2107 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2110 // Check declaring type first if there is any
2112 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2115 while (type is ElementTypeSpec)
2116 type = ((ElementTypeSpec) type).Element;
2118 if (type.Arity == 0)
2121 var gtype = type as InflatedTypeSpec;
2125 var constraints = gtype.Constraints;
2126 if (constraints == null)
2129 if (gtype.HasConstraintsChecked)
2132 var cc = new ConstraintChecker (mc);
2133 cc.recursive_checks = true;
2135 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2136 gtype.HasConstraintsChecked = true;
2144 // Checks all type arguments againts type parameters constraints
2145 // NOTE: It can run in probing mode when `mc' is null
2147 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2149 for (int i = 0; i < tparams.Length; i++) {
2150 if (ignore_inferred_dynamic && targs[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2153 var targ = targs[i];
2154 if (!CheckConstraint (context, targ, tparams [i], loc))
2157 if (!recursive_checks)
2160 if (!Check (mc, targ, loc))
2167 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2170 // First, check the `class' and `struct' constraints.
2172 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2174 mc.Module.Compiler.Report.Error (452, loc,
2175 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2176 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2182 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2184 mc.Module.Compiler.Report.Error (453, loc,
2185 "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}'",
2186 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2195 // Check the class constraint
2197 if (tparam.HasTypeConstraint) {
2198 var dep = tparam.BaseType.GetMissingDependencies ();
2203 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2207 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2216 // Check the interfaces constraints
2218 if (tparam.Interfaces != null) {
2219 if (atype.IsNullableType) {
2223 mc.Module.Compiler.Report.Error (313, loc,
2224 "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",
2225 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2228 foreach (TypeSpec iface in tparam.Interfaces) {
2229 var dep = iface.GetMissingDependencies ();
2234 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2237 // return immediately to avoid duplicate errors because we are scanning
2238 // expanded interface list
2242 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2253 // Check the type parameter constraint
2255 if (tparam.TypeArguments != null) {
2256 foreach (var ta in tparam.TypeArguments) {
2257 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2267 // Finally, check the constructor constraint.
2269 if (!tparam.HasSpecialConstructor)
2272 if (!HasDefaultConstructor (atype)) {
2274 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2275 mc.Module.Compiler.Report.Error (310, loc,
2276 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2277 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2285 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2287 for (int i = 0; i < targs.Length; ++i) {
2288 var targ = targs [i];
2289 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2292 if (HasDynamicTypeArgument (targ.TypeArguments))
2299 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2304 if (atype.IsGenericParameter) {
2305 var tps = (TypeParameterSpec) atype;
2306 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2310 // LAMESPEC: Identity conversion with inflated type parameter
2311 // It's not clear from the spec what rule should apply to inherited
2312 // inflated type parameter. The specification allows only type parameter
2313 // conversion but that's clearly not enough
2315 if (tps.HasTypeConstraint && tps.BaseType == ttype)
2318 } else if (TypeSpec.IsValueType (atype)) {
2319 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2322 var expr = new EmptyExpression (atype);
2323 if (Convert.ImplicitStandardConversionExists (expr, ttype))
2328 // When partial/full type inference finds a dynamic type argument delay
2329 // the constraint check to runtime, it can succeed for real underlying
2332 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2336 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2337 if (atype.IsGenericParameter) {
2338 mc.Module.Compiler.Report.Error (314, loc,
2339 "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}'",
2340 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2341 } else if (TypeSpec.IsValueType (atype)) {
2342 mc.Module.Compiler.Report.Error (315, loc,
2343 "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}'",
2344 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2346 mc.Module.Compiler.Report.Error (311, loc,
2347 "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}'",
2348 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2355 bool HasDefaultConstructor (TypeSpec atype)
2357 var tp = atype as TypeParameterSpec;
2359 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2362 if (atype.IsStruct || atype.IsEnum)
2365 if (atype.IsAbstract)
2368 var tdef = atype.GetDefinition ();
2370 var found = MemberCache.FindMember (tdef,
2371 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2372 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2374 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2379 /// A generic method definition.
2381 public class GenericMethod : DeclSpace
2383 ParametersCompiled parameters;
2385 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name,
2386 FullNamedExpression return_type, ParametersCompiled parameters)
2387 : base (ns, parent, name, null)
2389 this.parameters = parameters;
2392 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2393 FullNamedExpression return_type, ParametersCompiled parameters)
2394 : this (ns, parent, name, return_type, parameters)
2396 this.type_params = tparams;
2399 public override TypeParameter[] CurrentTypeParameters {
2401 return base.type_params;
2405 protected override TypeAttributes TypeAttr {
2407 throw new NotSupportedException ();
2411 public override void DefineType ()
2413 throw new Exception ();
2416 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2418 throw new NotSupportedException ();
2421 public override bool Define ()
2423 throw new NotSupportedException ();
2427 /// Define and resolve the type parameters.
2428 /// We're called from Method.Define().
2430 public bool Define (MethodOrOperator m)
2432 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2433 string[] snames = new string [names.Length];
2434 var block = m.Block;
2435 for (int i = 0; i < names.Length; i++) {
2436 string type_argument_name = names[i].Name;
2438 if (block == null) {
2439 int idx = parameters.GetParameterIndexByName (type_argument_name);
2443 b = new ToplevelBlock (Compiler, Location);
2445 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2448 INamedBlockVariable variable = null;
2449 block.GetLocalName (type_argument_name, m.Block, ref variable);
2450 if (variable != null)
2451 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2454 snames[i] = type_argument_name;
2457 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2458 for (int i = 0; i < TypeParameters.Length; i++)
2459 TypeParameters [i].Define (gen_params [i], null);
2464 public void EmitAttributes ()
2466 if (OptAttributes != null)
2467 OptAttributes.Emit ();
2470 public override string GetSignatureForError ()
2472 return base.GetSignatureForError () + parameters.GetSignatureForError ();
2475 public override AttributeTargets AttributeTargets {
2477 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2481 public override string DocCommentHeader {
2482 get { return "M:"; }
2485 public new void VerifyClsCompliance ()
2487 foreach (TypeParameter tp in TypeParameters) {
2488 tp.VerifyClsCompliance ();
2493 public partial class TypeManager
2495 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2497 var tp = t as TypeParameterSpec;
2499 Variance v = tp.Variance;
2500 if (expected == Variance.None && v != expected ||
2501 expected == Variance.Covariant && v == Variance.Contravariant ||
2502 expected == Variance.Contravariant && v == Variance.Covariant) {
2503 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2509 if (t.TypeArguments.Length > 0) {
2510 var targs_definition = t.MemberDefinition.TypeParameters;
2511 TypeSpec[] targs = GetTypeArguments (t);
2512 for (int i = 0; i < targs.Length; ++i) {
2513 Variance v = targs_definition[i].Variance;
2514 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2521 return CheckTypeVariance (GetElementType (t), expected, member);
2523 return Variance.None;
2528 // Implements C# type inference
2533 // Tracks successful rate of type inference
2535 int score = int.MaxValue;
2536 readonly Arguments arguments;
2537 readonly int arg_count;
2539 public TypeInference (Arguments arguments)
2541 this.arguments = arguments;
2542 if (arguments != null)
2543 arg_count = arguments.Count;
2546 public int InferenceScore {
2552 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2554 var method_generic_args = method.GenericDefinition.TypeParameters;
2555 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2556 if (!context.UnfixedVariableExists)
2557 return TypeSpec.EmptyTypes;
2559 AParametersCollection pd = method.Parameters;
2560 if (!InferInPhases (ec, context, pd))
2563 return context.InferredTypeArguments;
2567 // Implements method type arguments inference
2569 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2571 int params_arguments_start;
2572 if (methodParameters.HasParams) {
2573 params_arguments_start = methodParameters.Count - 1;
2575 params_arguments_start = arg_count;
2578 TypeSpec [] ptypes = methodParameters.Types;
2581 // The first inference phase
2583 TypeSpec method_parameter = null;
2584 for (int i = 0; i < arg_count; i++) {
2585 Argument a = arguments [i];
2589 if (i < params_arguments_start) {
2590 method_parameter = methodParameters.Types [i];
2591 } else if (i == params_arguments_start) {
2592 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2593 method_parameter = methodParameters.Types [params_arguments_start];
2595 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2597 ptypes = (TypeSpec[]) ptypes.Clone ();
2598 ptypes [i] = method_parameter;
2602 // When a lambda expression, an anonymous method
2603 // is used an explicit argument type inference takes a place
2605 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2607 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2613 score -= tic.ExactInference (a.Type, method_parameter);
2617 if (a.Expr.Type == InternalType.NullLiteral)
2620 if (TypeSpec.IsValueType (method_parameter)) {
2621 score -= tic.LowerBoundInference (a.Type, method_parameter);
2626 // Otherwise an output type inference is made
2628 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2632 // Part of the second phase but because it happens only once
2633 // we don't need to call it in cycle
2635 bool fixed_any = false;
2636 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2639 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2642 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2644 bool fixed_any = false;
2645 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2648 // If no further unfixed type variables exist, type inference succeeds
2649 if (!tic.UnfixedVariableExists)
2652 if (!fixed_any && fixDependent)
2655 // For all arguments where the corresponding argument output types
2656 // contain unfixed type variables but the input types do not,
2657 // an output type inference is made
2658 for (int i = 0; i < arg_count; i++) {
2660 // Align params arguments
2661 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2663 if (!TypeManager.IsDelegateType (t_i)) {
2664 if (!t_i.IsExpressionTreeType)
2667 t_i = TypeManager.GetTypeArguments (t_i) [0];
2670 var mi = Delegate.GetInvokeMethod (t_i);
2671 TypeSpec rtype = mi.ReturnType;
2673 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2674 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2678 return DoSecondPhase (ec, tic, methodParameters, true);
2682 public class TypeInferenceContext
2684 protected enum BoundKind
2691 protected class BoundInfo : IEquatable<BoundInfo>
2693 public readonly TypeSpec Type;
2694 public readonly BoundKind Kind;
2696 public BoundInfo (TypeSpec type, BoundKind kind)
2702 public override int GetHashCode ()
2704 return Type.GetHashCode ();
2707 public virtual Expression GetTypeExpression ()
2709 return new TypeExpression (Type, Location.Null);
2712 #region IEquatable<BoundInfo> Members
2714 public virtual bool Equals (BoundInfo other)
2716 return Type == other.Type && Kind == other.Kind;
2722 readonly TypeSpec[] tp_args;
2723 readonly TypeSpec[] fixed_types;
2724 readonly List<BoundInfo>[] bounds;
2727 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2728 public TypeInferenceContext (TypeSpec[] typeArguments)
2730 if (typeArguments.Length == 0)
2731 throw new ArgumentException ("Empty generic arguments");
2733 fixed_types = new TypeSpec [typeArguments.Length];
2734 for (int i = 0; i < typeArguments.Length; ++i) {
2735 if (typeArguments [i].IsGenericParameter) {
2736 if (bounds == null) {
2737 bounds = new List<BoundInfo> [typeArguments.Length];
2738 tp_args = new TypeSpec [typeArguments.Length];
2740 tp_args [i] = typeArguments [i];
2742 fixed_types [i] = typeArguments [i];
2748 // Used together with AddCommonTypeBound fo implement
2749 // 7.4.2.13 Finding the best common type of a set of expressions
2751 public TypeInferenceContext ()
2753 fixed_types = new TypeSpec [1];
2754 tp_args = new TypeSpec [1];
2755 tp_args[0] = InternalType.Arglist; // it can be any internal type
2756 bounds = new List<BoundInfo> [1];
2759 public TypeSpec[] InferredTypeArguments {
2765 public void AddCommonTypeBound (TypeSpec type)
2767 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2770 protected void AddToBounds (BoundInfo bound, int index)
2773 // Some types cannot be used as type arguments
2775 if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2776 bound.Type == InternalType.MethodGroup)
2779 var a = bounds [index];
2781 a = new List<BoundInfo> (2);
2787 if (a.Contains (bound))
2793 bool AllTypesAreFixed (TypeSpec[] types)
2795 foreach (TypeSpec t in types) {
2796 if (t.IsGenericParameter) {
2802 if (TypeManager.IsGenericType (t))
2803 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2810 // 26.3.3.8 Exact Inference
2812 public int ExactInference (TypeSpec u, TypeSpec v)
2814 // If V is an array type
2819 // TODO MemberCache: GetMetaInfo ()
2820 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2823 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2826 // If V is constructed type and U is constructed type
2827 if (TypeManager.IsGenericType (v)) {
2828 if (!TypeManager.IsGenericType (u))
2831 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2832 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2833 if (ga_u.Length != ga_v.Length)
2837 for (int i = 0; i < ga_u.Length; ++i)
2838 score += ExactInference (ga_u [i], ga_v [i]);
2840 return score > 0 ? 1 : 0;
2843 // If V is one of the unfixed type arguments
2844 int pos = IsUnfixed (v);
2848 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2852 public bool FixAllTypes (ResolveContext ec)
2854 for (int i = 0; i < tp_args.Length; ++i) {
2855 if (!FixType (ec, i))
2862 // All unfixed type variables Xi are fixed for which all of the following hold:
2863 // a, There is at least one type variable Xj that depends on Xi
2864 // b, Xi has a non-empty set of bounds
2866 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2868 for (int i = 0; i < tp_args.Length; ++i) {
2869 if (fixed_types[i] != null)
2872 if (bounds[i] == null)
2875 if (!FixType (ec, i))
2885 // All unfixed type variables Xi which depend on no Xj are fixed
2887 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2889 var types_to_fix = new List<TypeSpec> (tp_args);
2890 for (int i = 0; i < methodParameters.Length; ++i) {
2891 TypeSpec t = methodParameters[i];
2893 if (!TypeManager.IsDelegateType (t)) {
2894 if (!t.IsExpressionTreeType)
2897 t = TypeManager.GetTypeArguments (t) [0];
2900 if (t.IsGenericParameter)
2903 var invoke = Delegate.GetInvokeMethod (t);
2904 TypeSpec rtype = invoke.ReturnType;
2905 while (rtype.IsArray)
2906 rtype = ((ArrayContainer) rtype).Element;
2908 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2911 // Remove dependent types, they cannot be fixed yet
2912 RemoveDependentTypes (types_to_fix, rtype);
2915 foreach (TypeSpec t in types_to_fix) {
2919 int idx = IsUnfixed (t);
2920 if (idx >= 0 && !FixType (ec, idx)) {
2925 fixed_any = types_to_fix.Count > 0;
2932 public bool FixType (ResolveContext ec, int i)
2934 // It's already fixed
2935 if (fixed_types[i] != null)
2936 throw new InternalErrorException ("Type argument has been already fixed");
2941 var candidates = bounds [i];
2942 if (candidates == null)
2945 if (candidates.Count == 1) {
2946 TypeSpec t = candidates[0].Type;
2947 if (t == InternalType.NullLiteral)
2950 fixed_types [i] = t;
2955 // Determines a unique type from which there is
2956 // a standard implicit conversion to all the other
2959 TypeSpec best_candidate = null;
2961 int candidates_count = candidates.Count;
2962 for (int ci = 0; ci < candidates_count; ++ci) {
2963 BoundInfo bound = candidates [ci];
2964 for (cii = 0; cii < candidates_count; ++cii) {
2968 BoundInfo cbound = candidates[cii];
2970 // Same type parameters with different bounds
2971 if (cbound.Type == bound.Type) {
2972 if (bound.Kind != BoundKind.Exact)
2978 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2979 if (cbound.Kind == BoundKind.Lower) {
2980 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2986 if (cbound.Kind == BoundKind.Upper) {
2987 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2994 if (bound.Kind != BoundKind.Exact) {
2995 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3006 if (bound.Kind == BoundKind.Lower) {
3007 if (cbound.Kind == BoundKind.Lower) {
3008 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3012 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3022 if (bound.Kind == BoundKind.Upper) {
3023 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3027 throw new NotImplementedException ("variance conversion");
3031 if (cii != candidates_count)
3035 // We already have the best candidate, break if thet are different
3037 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3039 if (best_candidate != null) {
3041 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3044 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3048 best_candidate = bound.Type;
3051 if (best_candidate == null)
3054 fixed_types[i] = best_candidate;
3058 public bool HasBounds (int pos)
3060 return bounds[pos] != null;
3064 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3065 // null when type parameter has not been fixed
3067 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3069 var tp = parameter as TypeParameterSpec;
3072 // Type inference works on generic arguments (MVAR) only
3074 if (!tp.IsMethodOwned)
3078 // Ensure the type parameter belongs to same container
3080 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3081 return fixed_types[tp.DeclaredPosition] ?? parameter;
3086 var gt = parameter as InflatedTypeSpec;
3088 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3089 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3090 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3091 if (inflated == null)
3094 inflated_targs[ii] = inflated;
3097 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3104 // Tests whether all delegate input arguments are fixed and generic output type
3105 // requires output type inference
3107 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3109 while (returnType.IsArray)
3110 returnType = ((ArrayContainer) returnType).Element;
3112 if (returnType.IsGenericParameter) {
3113 if (IsFixed (returnType))
3115 } else if (TypeManager.IsGenericType (returnType)) {
3116 if (TypeManager.IsDelegateType (returnType)) {
3117 invoke = Delegate.GetInvokeMethod (returnType);
3118 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3121 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3123 // At least one unfixed return type has to exist
3124 if (AllTypesAreFixed (g_args))
3130 // All generic input arguments have to be fixed
3131 AParametersCollection d_parameters = invoke.Parameters;
3132 return AllTypesAreFixed (d_parameters.Types);
3135 bool IsFixed (TypeSpec type)
3137 return IsUnfixed (type) == -1;
3140 int IsUnfixed (TypeSpec type)
3142 if (!type.IsGenericParameter)
3145 for (int i = 0; i < tp_args.Length; ++i) {
3146 if (tp_args[i] == type) {
3147 if (fixed_types[i] != null)
3158 // 26.3.3.9 Lower-bound Inference
3160 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3162 return LowerBoundInference (u, v, false);
3166 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3168 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3170 // If V is one of the unfixed type arguments
3171 int pos = IsUnfixed (v);
3173 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3177 // If U is an array type
3178 var u_ac = u as ArrayContainer;
3180 var v_ac = v as ArrayContainer;
3182 if (u_ac.Rank != v_ac.Rank)
3185 if (TypeSpec.IsValueType (u_ac.Element))
3186 return ExactInference (u_ac.Element, v_ac.Element);
3188 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3191 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3194 var v_i = TypeManager.GetTypeArguments (v) [0];
3195 if (TypeSpec.IsValueType (u_ac.Element))
3196 return ExactInference (u_ac.Element, v_i);
3198 return LowerBoundInference (u_ac.Element, v_i);
3201 if (TypeManager.IsGenericType (v)) {
3203 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3204 // such that U is identical to, inherits from (directly or indirectly),
3205 // or implements (directly or indirectly) C<U1..Uk>
3207 var u_candidates = new List<TypeSpec> ();
3208 var open_v = v.MemberDefinition;
3210 for (TypeSpec t = u; t != null; t = t.BaseType) {
3211 if (open_v == t.MemberDefinition)
3212 u_candidates.Add (t);
3215 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3216 // that would complicate the process a lot, instead I treat them as dynamic
3218 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3219 u_candidates.Add (t);
3221 if (t.Interfaces != null) {
3222 foreach (var iface in t.Interfaces) {
3223 if (open_v == iface.MemberDefinition)
3224 u_candidates.Add (iface);
3229 TypeSpec [] unique_candidate_targs = null;
3230 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
3231 foreach (TypeSpec u_candidate in u_candidates) {
3233 // The unique set of types U1..Uk means that if we have an interface I<T>,
3234 // class U : I<int>, I<long> then no type inference is made when inferring
3235 // type I<T> by applying type U because T could be int or long
3237 if (unique_candidate_targs != null) {
3238 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3239 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3240 unique_candidate_targs = second_unique_candidate_targs;
3245 // This should always cause type inference failure
3252 // A candidate is dynamic type expression, to simplify things use dynamic
3253 // for all type parameter of this type. For methods like this one
3255 // void M<T, U> (IList<T>, IList<U[]>)
3257 // dynamic becomes both T and U when the arguments are of dynamic type
3259 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3260 unique_candidate_targs = new TypeSpec[ga_v.Length];
3261 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3262 unique_candidate_targs[i] = u_candidate;
3264 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3268 if (unique_candidate_targs != null) {
3269 var ga_open_v = open_v.TypeParameters;
3271 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3272 Variance variance = ga_open_v [i].Variance;
3274 TypeSpec u_i = unique_candidate_targs [i];
3275 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3276 if (ExactInference (u_i, ga_v [i]) == 0)
3279 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3280 (variance == Variance.Covariant && inversed);
3282 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3294 // 26.3.3.6 Output Type Inference
3296 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3298 // If e is a lambda or anonymous method with inferred return type
3299 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3301 TypeSpec rt = ame.InferReturnType (ec, this, t);
3302 var invoke = Delegate.GetInvokeMethod (t);
3305 AParametersCollection pd = invoke.Parameters;
3306 return ame.Parameters.Count == pd.Count ? 1 : 0;
3309 TypeSpec rtype = invoke.ReturnType;
3310 return LowerBoundInference (rt, rtype) + 1;
3314 // if E is a method group and T is a delegate type or expression tree type
3315 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3316 // resolution of E with the types T1..Tk yields a single method with return type U,
3317 // then a lower-bound inference is made from U for Tb.
3319 if (e is MethodGroupExpr) {
3320 if (!TypeManager.IsDelegateType (t)) {
3321 if (!t.IsExpressionTreeType)
3324 t = TypeManager.GetTypeArguments (t)[0];
3327 var invoke = Delegate.GetInvokeMethod (t);
3328 TypeSpec rtype = invoke.ReturnType;
3330 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3333 // LAMESPEC: Standard does not specify that all methodgroup arguments
3334 // has to be fixed but it does not specify how to do recursive type inference
3335 // either. We choose the simple option and infer return type only
3336 // if all delegate generic arguments are fixed.
3337 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3338 for (int i = 0; i < param_types.Length; ++i) {
3339 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3340 if (inflated == null)
3343 if (IsUnfixed (inflated) >= 0)
3346 param_types[i] = inflated;
3349 MethodGroupExpr mg = (MethodGroupExpr) e;
3350 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3351 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3355 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3359 // if e is an expression with type U, then
3360 // a lower-bound inference is made from U for T
3362 return LowerBoundInference (e.Type, t) * 2;
3365 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3367 int idx = IsUnfixed (returnType);
3373 if (TypeManager.IsGenericType (returnType)) {
3374 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3375 RemoveDependentTypes (types, t);
3380 public bool UnfixedVariableExists {
3382 foreach (TypeSpec ut in fixed_types) {