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 IsNullableType {
1510 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1515 // Types used to inflate the generic type
1517 public override TypeSpec[] TypeArguments {
1525 public static bool ContainsTypeParameter (TypeSpec type)
1527 if (type.Kind == MemberKind.TypeParameter)
1530 var element_container = type as ElementTypeSpec;
1531 if (element_container != null)
1532 return ContainsTypeParameter (element_container.Element);
1534 foreach (var t in type.TypeArguments) {
1535 if (ContainsTypeParameter (t)) {
1543 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1545 TypeParameterSpec[] tparams_full;
1546 TypeSpec[] targs_full = targs;
1549 // Special case is needed when we are inflating an open type (nested type definition)
1550 // on inflated parent. Consider following case
1552 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1554 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1556 List<TypeSpec> merged_targs = null;
1557 List<TypeParameterSpec> merged_tparams = null;
1559 var type = DeclaringType;
1562 if (type.TypeArguments.Length > 0) {
1563 if (merged_targs == null) {
1564 merged_targs = new List<TypeSpec> ();
1565 merged_tparams = new List<TypeParameterSpec> ();
1566 if (targs.Length > 0) {
1567 merged_targs.AddRange (targs);
1568 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1571 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1572 merged_targs.AddRange (type.TypeArguments);
1574 type = type.DeclaringType;
1575 } while (type != null);
1577 if (merged_targs != null) {
1578 // Type arguments are not in the right order but it should not matter in this case
1579 targs_full = merged_targs.ToArray ();
1580 tparams_full = merged_tparams.ToArray ();
1581 } else if (targs.Length == 0) {
1582 tparams_full = TypeParameterSpec.EmptyTypes;
1584 tparams_full = open_type.MemberDefinition.TypeParameters;
1586 } else if (targs.Length == 0) {
1587 tparams_full = TypeParameterSpec.EmptyTypes;
1589 tparams_full = open_type.MemberDefinition.TypeParameters;
1592 return new TypeParameterInflator (context, this, tparams_full, targs_full);
1595 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1598 // Converts nested type arguments into right order
1599 // Foo<string, bool>.Bar<int> => string, bool, int
1601 var all = new List<MetaType> ();
1602 TypeSpec type = this;
1603 TypeSpec definition = type;
1605 if (type.GetDefinition().IsGeneric) {
1607 type.TypeArguments != TypeSpec.EmptyTypes ?
1608 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1609 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1612 definition = definition.GetDefinition ();
1613 type = type.DeclaringType;
1614 } while (type != null);
1616 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1619 public override ObsoleteAttribute GetAttributeObsolete ()
1621 return open_type.GetAttributeObsolete ();
1624 protected override bool IsNotCLSCompliant (out bool attrValue)
1626 if (base.IsNotCLSCompliant (out attrValue))
1629 foreach (var ta in TypeArguments) {
1630 if (ta.MemberDefinition.CLSAttributeValue == false)
1637 public override TypeSpec GetDefinition ()
1642 public override MetaType GetMetaInfo ()
1645 info = CreateMetaInfo (null);
1650 public override string GetSignatureForError ()
1653 return targs[0].GetSignatureForError () + "?";
1655 return base.GetSignatureForError ();
1658 protected override string GetTypeNameSignature ()
1660 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1663 return "<" + TypeManager.CSharpName (targs) + ">";
1666 public bool HasDynamicArgument ()
1668 for (int i = 0; i < targs.Length; ++i) {
1669 var item = targs[i];
1671 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1674 if (item is InflatedTypeSpec) {
1675 if (((InflatedTypeSpec) item).HasDynamicArgument ())
1682 while (item.IsArray) {
1683 item = ((ArrayContainer) item).Element;
1686 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1694 protected override void InitializeMemberCache (bool onlyTypes)
1696 if (cache == null) {
1697 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1699 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1700 // for imported type parameter constraints referencing nested type of this declaration
1702 cache = new MemberCache (open_cache);
1705 var inflator = CreateLocalInflator (context);
1708 // Two stage inflate due to possible nested types recursive
1718 // When resolving type of `b' members of `B' cannot be
1719 // inflated because are not yet available in membercache
1721 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1722 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1725 // Inflate any implemented interfaces
1727 if (open_type.Interfaces != null) {
1728 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1729 foreach (var iface in open_type.Interfaces) {
1730 var iface_inflated = inflator.Inflate (iface);
1731 if (iface_inflated == null)
1734 AddInterface (iface_inflated);
1739 // Handles the tricky case of recursive nested base generic type
1741 // class A<T> : Base<A<T>.Nested> {
1745 // When inflating A<T>. base type is not yet known, secondary
1746 // inflation is required (not common case) once base scope
1749 if (open_type.BaseType == null) {
1751 state |= StateFlags.PendingBaseTypeInflate;
1753 BaseType = inflator.Inflate (open_type.BaseType);
1755 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1756 BaseType = inflator.Inflate (open_type.BaseType);
1757 state &= ~StateFlags.PendingBaseTypeInflate;
1761 state |= StateFlags.PendingMemberCacheMembers;
1765 var tc = open_type.MemberDefinition as TypeContainer;
1766 if (tc != null && !tc.HasMembersDefined)
1767 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1769 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1770 BaseType = inflator.Inflate (open_type.BaseType);
1771 state &= ~StateFlags.PendingBaseTypeInflate;
1774 state &= ~StateFlags.PendingMemberCacheMembers;
1775 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1778 public override TypeSpec Mutate (TypeParameterMutator mutator)
1780 var targs = TypeArguments;
1782 targs = mutator.Mutate (targs);
1784 var decl = DeclaringType;
1785 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1786 decl = mutator.Mutate (decl);
1788 if (targs == TypeArguments && decl == DeclaringType)
1791 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1792 if (decl != DeclaringType) {
1793 // Gets back MethodInfo in case of metaInfo was inflated
1794 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1796 mutated.declaringType = decl;
1797 mutated.state |= StateFlags.PendingMetaInflate;
1800 if (targs != null) {
1801 mutated.targs = targs;
1802 mutated.info = null;
1811 // Tracks the type arguments when instantiating a generic type. It's used
1812 // by both type arguments and type parameters
1814 public class TypeArguments
1816 List<FullNamedExpression> args;
1819 public TypeArguments (params FullNamedExpression[] types)
1821 this.args = new List<FullNamedExpression> (types);
1824 public void Add (FullNamedExpression type)
1829 // TODO: Kill this monster
1830 public TypeParameterName[] GetDeclarations ()
1832 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1836 /// We may only be used after Resolve() is called and return the fully
1839 // TODO: Not needed, just return type from resolve
1840 public TypeSpec[] Arguments {
1855 public virtual bool IsEmpty {
1861 public string GetSignatureForError()
1863 StringBuilder sb = new StringBuilder ();
1864 for (int i = 0; i < Count; ++i) {
1867 sb.Append (expr.GetSignatureForError ());
1873 return sb.ToString ();
1877 /// Resolve the type arguments.
1879 public virtual bool Resolve (IMemberContext ec)
1882 return atypes.Length != 0;
1884 int count = args.Count;
1887 atypes = new TypeSpec [count];
1889 for (int i = 0; i < count; i++){
1890 var te = args[i].ResolveAsType (ec);
1899 ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
1900 te.GetSignatureForError ());
1904 if (te.IsPointer || te.IsSpecialRuntimeType) {
1905 ec.Module.Compiler.Report.Error (306, args[i].Location,
1906 "The type `{0}' may not be used as a type argument",
1907 te.GetSignatureForError ());
1913 atypes = TypeSpec.EmptyTypes;
1918 public TypeArguments Clone ()
1920 TypeArguments copy = new TypeArguments ();
1921 foreach (var ta in args)
1928 public class UnboundTypeArguments : TypeArguments
1930 public UnboundTypeArguments (int arity)
1931 : base (new FullNamedExpression[arity])
1935 public override bool IsEmpty {
1941 public override bool Resolve (IMemberContext ec)
1943 // Nothing to be resolved
1948 public class TypeParameterName : SimpleName
1950 Attributes attributes;
1953 public TypeParameterName (string name, Attributes attrs, Location loc)
1954 : this (name, attrs, Variance.None, loc)
1958 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1962 this.variance = variance;
1965 public Attributes OptAttributes {
1971 public Variance Variance {
1979 // A type expression of generic type with type arguments
1981 class GenericTypeExpr : TypeExpr
1987 /// Instantiate the generic type `t' with the type arguments `args'.
1988 /// Use this constructor if you already know the fully resolved
1991 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1993 this.open_type = open_type;
1998 public TypeArguments TypeArguments {
1999 get { return args; }
2002 public override string GetSignatureForError ()
2004 return TypeManager.CSharpName (type);
2007 public override TypeSpec ResolveAsType (IMemberContext mc)
2009 if (eclass != ExprClass.Unresolved)
2012 if (!args.Resolve (mc))
2015 TypeSpec[] atypes = args.Arguments;
2018 // Now bind the parameters
2020 var inflated = open_type.MakeGenericType (mc, atypes);
2022 eclass = ExprClass.Type;
2025 // The constraints can be checked only when full type hierarchy is known
2027 if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2028 var constraints = inflated.Constraints;
2029 if (constraints != null) {
2030 var cc = new ConstraintChecker (mc);
2031 if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2032 inflated.HasConstraintsChecked = true;
2040 public override bool Equals (object obj)
2042 GenericTypeExpr cobj = obj as GenericTypeExpr;
2046 if ((type == null) || (cobj.type == null))
2049 return type == cobj.type;
2052 public override int GetHashCode ()
2054 return base.GetHashCode ();
2059 // Generic type with unbound type arguments, used for typeof (G<,,>)
2061 class GenericOpenTypeExpr : TypeExpression
2063 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2064 : base (type.GetDefinition (), loc)
2069 struct ConstraintChecker
2072 bool ignore_inferred_dynamic;
2073 bool recursive_checks;
2075 public ConstraintChecker (IMemberContext ctx)
2078 ignore_inferred_dynamic = false;
2079 recursive_checks = false;
2084 public bool IgnoreInferredDynamic {
2086 return ignore_inferred_dynamic;
2089 ignore_inferred_dynamic = value;
2096 // Checks the constraints of open generic type against type
2097 // arguments. This version is used for types which could not be
2098 // checked immediatelly during construction because the type
2099 // hierarchy was not yet fully setup (before Emit phase)
2101 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2104 // Check declaring type first if there is any
2106 if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2109 while (type is ElementTypeSpec)
2110 type = ((ElementTypeSpec) type).Element;
2112 if (type.Arity == 0)
2115 var gtype = type as InflatedTypeSpec;
2119 var constraints = gtype.Constraints;
2120 if (constraints == null)
2123 if (gtype.HasConstraintsChecked)
2126 var cc = new ConstraintChecker (mc);
2127 cc.recursive_checks = true;
2129 if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2130 gtype.HasConstraintsChecked = true;
2138 // Checks all type arguments againts type parameters constraints
2139 // NOTE: It can run in probing mode when `mc' is null
2141 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2143 for (int i = 0; i < tparams.Length; i++) {
2144 if (ignore_inferred_dynamic && targs[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2147 var targ = targs[i];
2148 if (!CheckConstraint (context, targ, tparams [i], loc))
2151 if (!recursive_checks)
2154 if (!Check (mc, targ, loc))
2161 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2164 // First, check the `class' and `struct' constraints.
2166 if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2168 mc.Module.Compiler.Report.Error (452, loc,
2169 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2170 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2176 if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2178 mc.Module.Compiler.Report.Error (453, loc,
2179 "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}'",
2180 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2189 // Check the class constraint
2191 if (tparam.HasTypeConstraint) {
2192 var dep = tparam.BaseType.GetMissingDependencies ();
2197 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2201 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2210 // Check the interfaces constraints
2212 if (tparam.Interfaces != null) {
2213 if (atype.IsNullableType) {
2217 mc.Module.Compiler.Report.Error (313, loc,
2218 "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",
2219 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2222 foreach (TypeSpec iface in tparam.Interfaces) {
2223 var dep = iface.GetMissingDependencies ();
2228 ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2231 // return immediately to avoid duplicate errors because we are scanning
2232 // expanded interface list
2236 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2247 // Check the type parameter constraint
2249 if (tparam.TypeArguments != null) {
2250 foreach (var ta in tparam.TypeArguments) {
2251 if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2261 // Finally, check the constructor constraint.
2263 if (!tparam.HasSpecialConstructor)
2266 if (!HasDefaultConstructor (atype)) {
2268 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2269 mc.Module.Compiler.Report.Error (310, loc,
2270 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2271 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2279 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2281 for (int i = 0; i < targs.Length; ++i) {
2282 var targ = targs [i];
2283 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2286 if (HasDynamicTypeArgument (targ.TypeArguments))
2293 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2298 if (atype.IsGenericParameter) {
2299 var tps = (TypeParameterSpec) atype;
2300 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2304 // LAMESPEC: Identity conversion with inflated type parameter
2305 // It's not clear from the spec what rule should apply to inherited
2306 // inflated type parameter. The specification allows only type parameter
2307 // conversion but that's clearly not enough
2309 if (tps.HasTypeConstraint && tps.BaseType == ttype)
2312 } else if (TypeSpec.IsValueType (atype)) {
2313 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2316 var expr = new EmptyExpression (atype);
2317 if (Convert.ImplicitStandardConversionExists (expr, ttype))
2322 // When partial/full type inference finds a dynamic type argument delay
2323 // the constraint check to runtime, it can succeed for real underlying
2326 if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2330 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2331 if (atype.IsGenericParameter) {
2332 mc.Module.Compiler.Report.Error (314, loc,
2333 "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}'",
2334 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2335 } else if (TypeSpec.IsValueType (atype)) {
2336 mc.Module.Compiler.Report.Error (315, loc,
2337 "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}'",
2338 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2340 mc.Module.Compiler.Report.Error (311, loc,
2341 "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}'",
2342 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2349 bool HasDefaultConstructor (TypeSpec atype)
2351 var tp = atype as TypeParameterSpec;
2353 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2356 if (atype.IsStruct || atype.IsEnum)
2359 if (atype.IsAbstract)
2362 var tdef = atype.GetDefinition ();
2364 var found = MemberCache.FindMember (tdef,
2365 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2366 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2368 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2373 /// A generic method definition.
2375 public class GenericMethod : DeclSpace
2377 ParametersCompiled parameters;
2379 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name,
2380 FullNamedExpression return_type, ParametersCompiled parameters)
2381 : base (ns, parent, name, null)
2383 this.parameters = parameters;
2386 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2387 FullNamedExpression return_type, ParametersCompiled parameters)
2388 : this (ns, parent, name, return_type, parameters)
2390 this.type_params = tparams;
2393 public override TypeParameter[] CurrentTypeParameters {
2395 return base.type_params;
2399 protected override TypeAttributes TypeAttr {
2401 throw new NotSupportedException ();
2405 public override void DefineType ()
2407 throw new Exception ();
2410 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2412 throw new NotSupportedException ();
2415 public override bool Define ()
2417 throw new NotSupportedException ();
2421 /// Define and resolve the type parameters.
2422 /// We're called from Method.Define().
2424 public bool Define (MethodOrOperator m)
2426 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2427 string[] snames = new string [names.Length];
2428 var block = m.Block;
2429 for (int i = 0; i < names.Length; i++) {
2430 string type_argument_name = names[i].Name;
2432 if (block == null) {
2433 int idx = parameters.GetParameterIndexByName (type_argument_name);
2437 b = new ToplevelBlock (Compiler, Location);
2439 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2442 INamedBlockVariable variable = null;
2443 block.GetLocalName (type_argument_name, m.Block, ref variable);
2444 if (variable != null)
2445 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2448 snames[i] = type_argument_name;
2451 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2452 for (int i = 0; i < TypeParameters.Length; i++)
2453 TypeParameters [i].Define (gen_params [i], null);
2458 public void EmitAttributes ()
2460 if (OptAttributes != null)
2461 OptAttributes.Emit ();
2464 public override string GetSignatureForError ()
2466 return base.GetSignatureForError () + parameters.GetSignatureForError ();
2469 public override AttributeTargets AttributeTargets {
2471 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2475 public override string DocCommentHeader {
2476 get { return "M:"; }
2479 public new void VerifyClsCompliance ()
2481 foreach (TypeParameter tp in TypeParameters) {
2482 tp.VerifyClsCompliance ();
2487 public partial class TypeManager
2489 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2491 var tp = t as TypeParameterSpec;
2493 Variance v = tp.Variance;
2494 if (expected == Variance.None && v != expected ||
2495 expected == Variance.Covariant && v == Variance.Contravariant ||
2496 expected == Variance.Contravariant && v == Variance.Covariant) {
2497 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2503 if (t.TypeArguments.Length > 0) {
2504 var targs_definition = t.MemberDefinition.TypeParameters;
2505 TypeSpec[] targs = GetTypeArguments (t);
2506 for (int i = 0; i < targs.Length; ++i) {
2507 Variance v = targs_definition[i].Variance;
2508 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2515 return CheckTypeVariance (GetElementType (t), expected, member);
2517 return Variance.None;
2522 // Implements C# type inference
2527 // Tracks successful rate of type inference
2529 int score = int.MaxValue;
2530 readonly Arguments arguments;
2531 readonly int arg_count;
2533 public TypeInference (Arguments arguments)
2535 this.arguments = arguments;
2536 if (arguments != null)
2537 arg_count = arguments.Count;
2540 public int InferenceScore {
2546 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2548 var method_generic_args = method.GenericDefinition.TypeParameters;
2549 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2550 if (!context.UnfixedVariableExists)
2551 return TypeSpec.EmptyTypes;
2553 AParametersCollection pd = method.Parameters;
2554 if (!InferInPhases (ec, context, pd))
2557 return context.InferredTypeArguments;
2561 // Implements method type arguments inference
2563 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2565 int params_arguments_start;
2566 if (methodParameters.HasParams) {
2567 params_arguments_start = methodParameters.Count - 1;
2569 params_arguments_start = arg_count;
2572 TypeSpec [] ptypes = methodParameters.Types;
2575 // The first inference phase
2577 TypeSpec method_parameter = null;
2578 for (int i = 0; i < arg_count; i++) {
2579 Argument a = arguments [i];
2583 if (i < params_arguments_start) {
2584 method_parameter = methodParameters.Types [i];
2585 } else if (i == params_arguments_start) {
2586 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2587 method_parameter = methodParameters.Types [params_arguments_start];
2589 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2591 ptypes = (TypeSpec[]) ptypes.Clone ();
2592 ptypes [i] = method_parameter;
2596 // When a lambda expression, an anonymous method
2597 // is used an explicit argument type inference takes a place
2599 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2601 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2607 score -= tic.ExactInference (a.Type, method_parameter);
2611 if (a.Expr.Type == InternalType.NullLiteral)
2614 if (TypeSpec.IsValueType (method_parameter)) {
2615 score -= tic.LowerBoundInference (a.Type, method_parameter);
2620 // Otherwise an output type inference is made
2622 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2626 // Part of the second phase but because it happens only once
2627 // we don't need to call it in cycle
2629 bool fixed_any = false;
2630 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2633 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2636 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2638 bool fixed_any = false;
2639 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2642 // If no further unfixed type variables exist, type inference succeeds
2643 if (!tic.UnfixedVariableExists)
2646 if (!fixed_any && fixDependent)
2649 // For all arguments where the corresponding argument output types
2650 // contain unfixed type variables but the input types do not,
2651 // an output type inference is made
2652 for (int i = 0; i < arg_count; i++) {
2654 // Align params arguments
2655 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2657 if (!TypeManager.IsDelegateType (t_i)) {
2658 if (!t_i.IsExpressionTreeType)
2661 t_i = TypeManager.GetTypeArguments (t_i) [0];
2664 var mi = Delegate.GetInvokeMethod (t_i);
2665 TypeSpec rtype = mi.ReturnType;
2667 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2668 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2672 return DoSecondPhase (ec, tic, methodParameters, true);
2676 public class TypeInferenceContext
2678 protected enum BoundKind
2685 protected class BoundInfo : IEquatable<BoundInfo>
2687 public readonly TypeSpec Type;
2688 public readonly BoundKind Kind;
2690 public BoundInfo (TypeSpec type, BoundKind kind)
2696 public override int GetHashCode ()
2698 return Type.GetHashCode ();
2701 public virtual Expression GetTypeExpression ()
2703 return new TypeExpression (Type, Location.Null);
2706 #region IEquatable<BoundInfo> Members
2708 public virtual bool Equals (BoundInfo other)
2710 return Type == other.Type && Kind == other.Kind;
2716 readonly TypeSpec[] tp_args;
2717 readonly TypeSpec[] fixed_types;
2718 readonly List<BoundInfo>[] bounds;
2721 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2722 public TypeInferenceContext (TypeSpec[] typeArguments)
2724 if (typeArguments.Length == 0)
2725 throw new ArgumentException ("Empty generic arguments");
2727 fixed_types = new TypeSpec [typeArguments.Length];
2728 for (int i = 0; i < typeArguments.Length; ++i) {
2729 if (typeArguments [i].IsGenericParameter) {
2730 if (bounds == null) {
2731 bounds = new List<BoundInfo> [typeArguments.Length];
2732 tp_args = new TypeSpec [typeArguments.Length];
2734 tp_args [i] = typeArguments [i];
2736 fixed_types [i] = typeArguments [i];
2742 // Used together with AddCommonTypeBound fo implement
2743 // 7.4.2.13 Finding the best common type of a set of expressions
2745 public TypeInferenceContext ()
2747 fixed_types = new TypeSpec [1];
2748 tp_args = new TypeSpec [1];
2749 tp_args[0] = InternalType.Arglist; // it can be any internal type
2750 bounds = new List<BoundInfo> [1];
2753 public TypeSpec[] InferredTypeArguments {
2759 public void AddCommonTypeBound (TypeSpec type)
2761 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2764 protected void AddToBounds (BoundInfo bound, int index)
2767 // Some types cannot be used as type arguments
2769 if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType)
2772 var a = bounds [index];
2774 a = new List<BoundInfo> (2);
2780 if (a.Contains (bound))
2786 bool AllTypesAreFixed (TypeSpec[] types)
2788 foreach (TypeSpec t in types) {
2789 if (t.IsGenericParameter) {
2795 if (TypeManager.IsGenericType (t))
2796 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2803 // 26.3.3.8 Exact Inference
2805 public int ExactInference (TypeSpec u, TypeSpec v)
2807 // If V is an array type
2812 // TODO MemberCache: GetMetaInfo ()
2813 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2816 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2819 // If V is constructed type and U is constructed type
2820 if (TypeManager.IsGenericType (v)) {
2821 if (!TypeManager.IsGenericType (u))
2824 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2825 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2826 if (ga_u.Length != ga_v.Length)
2830 for (int i = 0; i < ga_u.Length; ++i)
2831 score += ExactInference (ga_u [i], ga_v [i]);
2833 return score > 0 ? 1 : 0;
2836 // If V is one of the unfixed type arguments
2837 int pos = IsUnfixed (v);
2841 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2845 public bool FixAllTypes (ResolveContext ec)
2847 for (int i = 0; i < tp_args.Length; ++i) {
2848 if (!FixType (ec, i))
2855 // All unfixed type variables Xi are fixed for which all of the following hold:
2856 // a, There is at least one type variable Xj that depends on Xi
2857 // b, Xi has a non-empty set of bounds
2859 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2861 for (int i = 0; i < tp_args.Length; ++i) {
2862 if (fixed_types[i] != null)
2865 if (bounds[i] == null)
2868 if (!FixType (ec, i))
2878 // All unfixed type variables Xi which depend on no Xj are fixed
2880 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2882 var types_to_fix = new List<TypeSpec> (tp_args);
2883 for (int i = 0; i < methodParameters.Length; ++i) {
2884 TypeSpec t = methodParameters[i];
2886 if (!TypeManager.IsDelegateType (t)) {
2887 if (!t.IsExpressionTreeType)
2890 t = TypeManager.GetTypeArguments (t) [0];
2893 if (t.IsGenericParameter)
2896 var invoke = Delegate.GetInvokeMethod (t);
2897 TypeSpec rtype = invoke.ReturnType;
2898 while (rtype.IsArray)
2899 rtype = ((ArrayContainer) rtype).Element;
2901 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2904 // Remove dependent types, they cannot be fixed yet
2905 RemoveDependentTypes (types_to_fix, rtype);
2908 foreach (TypeSpec t in types_to_fix) {
2912 int idx = IsUnfixed (t);
2913 if (idx >= 0 && !FixType (ec, idx)) {
2918 fixed_any = types_to_fix.Count > 0;
2925 public bool FixType (ResolveContext ec, int i)
2927 // It's already fixed
2928 if (fixed_types[i] != null)
2929 throw new InternalErrorException ("Type argument has been already fixed");
2934 var candidates = bounds [i];
2935 if (candidates == null)
2938 if (candidates.Count == 1) {
2939 TypeSpec t = candidates[0].Type;
2940 if (t == InternalType.NullLiteral)
2943 fixed_types [i] = t;
2948 // Determines a unique type from which there is
2949 // a standard implicit conversion to all the other
2952 TypeSpec best_candidate = null;
2954 int candidates_count = candidates.Count;
2955 for (int ci = 0; ci < candidates_count; ++ci) {
2956 BoundInfo bound = candidates [ci];
2957 for (cii = 0; cii < candidates_count; ++cii) {
2961 BoundInfo cbound = candidates[cii];
2963 // Same type parameters with different bounds
2964 if (cbound.Type == bound.Type) {
2965 if (bound.Kind != BoundKind.Exact)
2971 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2972 if (cbound.Kind == BoundKind.Lower) {
2973 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2979 if (cbound.Kind == BoundKind.Upper) {
2980 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2987 if (bound.Kind != BoundKind.Exact) {
2988 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2999 if (bound.Kind == BoundKind.Lower) {
3000 if (cbound.Kind == BoundKind.Lower) {
3001 if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3005 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3015 if (bound.Kind == BoundKind.Upper) {
3016 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3020 throw new NotImplementedException ("variance conversion");
3024 if (cii != candidates_count)
3028 // We already have the best candidate, break if thet are different
3030 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3032 if (best_candidate != null) {
3034 if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3037 if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3041 best_candidate = bound.Type;
3044 if (best_candidate == null)
3047 fixed_types[i] = best_candidate;
3052 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3053 // null when type parameter has not been fixed
3055 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3057 var tp = parameter as TypeParameterSpec;
3060 // Type inference works on generic arguments (MVAR) only
3062 if (!tp.IsMethodOwned)
3066 // Ensure the type parameter belongs to same container
3068 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3069 return fixed_types[tp.DeclaredPosition] ?? parameter;
3074 var gt = parameter as InflatedTypeSpec;
3076 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3077 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3078 var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3079 if (inflated == null)
3082 inflated_targs[ii] = inflated;
3085 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3092 // Tests whether all delegate input arguments are fixed and generic output type
3093 // requires output type inference
3095 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3097 while (returnType.IsArray)
3098 returnType = ((ArrayContainer) returnType).Element;
3100 if (returnType.IsGenericParameter) {
3101 if (IsFixed (returnType))
3103 } else if (TypeManager.IsGenericType (returnType)) {
3104 if (TypeManager.IsDelegateType (returnType)) {
3105 invoke = Delegate.GetInvokeMethod (returnType);
3106 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3109 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3111 // At least one unfixed return type has to exist
3112 if (AllTypesAreFixed (g_args))
3118 // All generic input arguments have to be fixed
3119 AParametersCollection d_parameters = invoke.Parameters;
3120 return AllTypesAreFixed (d_parameters.Types);
3123 bool IsFixed (TypeSpec type)
3125 return IsUnfixed (type) == -1;
3128 int IsUnfixed (TypeSpec type)
3130 if (!type.IsGenericParameter)
3133 for (int i = 0; i < tp_args.Length; ++i) {
3134 if (tp_args[i] == type) {
3135 if (fixed_types[i] != null)
3146 // 26.3.3.9 Lower-bound Inference
3148 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3150 return LowerBoundInference (u, v, false);
3154 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3156 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3158 // If V is one of the unfixed type arguments
3159 int pos = IsUnfixed (v);
3161 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3165 // If U is an array type
3166 var u_ac = u as ArrayContainer;
3168 var v_ac = v as ArrayContainer;
3170 if (u_ac.Rank != v_ac.Rank)
3173 if (TypeSpec.IsValueType (u_ac.Element))
3174 return ExactInference (u_ac.Element, v_ac.Element);
3176 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3179 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3182 var v_i = TypeManager.GetTypeArguments (v) [0];
3183 if (TypeSpec.IsValueType (u_ac.Element))
3184 return ExactInference (u_ac.Element, v_i);
3186 return LowerBoundInference (u_ac.Element, v_i);
3189 if (TypeManager.IsGenericType (v)) {
3191 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3192 // such that U is identical to, inherits from (directly or indirectly),
3193 // or implements (directly or indirectly) C<U1..Uk>
3195 var u_candidates = new List<TypeSpec> ();
3196 var open_v = v.MemberDefinition;
3198 for (TypeSpec t = u; t != null; t = t.BaseType) {
3199 if (open_v == t.MemberDefinition)
3200 u_candidates.Add (t);
3203 // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3204 // that would complicate the process a lot, instead I treat them as dynamic
3206 if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3207 u_candidates.Add (t);
3209 if (t.Interfaces != null) {
3210 foreach (var iface in t.Interfaces) {
3211 if (open_v == iface.MemberDefinition)
3212 u_candidates.Add (iface);
3217 TypeSpec [] unique_candidate_targs = null;
3218 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
3219 foreach (TypeSpec u_candidate in u_candidates) {
3221 // The unique set of types U1..Uk means that if we have an interface I<T>,
3222 // class U : I<int>, I<long> then no type inference is made when inferring
3223 // type I<T> by applying type U because T could be int or long
3225 if (unique_candidate_targs != null) {
3226 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3227 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3228 unique_candidate_targs = second_unique_candidate_targs;
3233 // This should always cause type inference failure
3240 // A candidate is dynamic type expression, to simplify things use dynamic
3241 // for all type parameter of this type. For methods like this one
3243 // void M<T, U> (IList<T>, IList<U[]>)
3245 // dynamic becomes both T and U when the arguments are of dynamic type
3247 if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3248 unique_candidate_targs = new TypeSpec[ga_v.Length];
3249 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3250 unique_candidate_targs[i] = u_candidate;
3252 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3256 if (unique_candidate_targs != null) {
3257 var ga_open_v = open_v.TypeParameters;
3259 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3260 Variance variance = ga_open_v [i].Variance;
3262 TypeSpec u_i = unique_candidate_targs [i];
3263 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3264 if (ExactInference (u_i, ga_v [i]) == 0)
3267 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3268 (variance == Variance.Covariant && inversed);
3270 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3282 // 26.3.3.6 Output Type Inference
3284 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3286 // If e is a lambda or anonymous method with inferred return type
3287 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3289 TypeSpec rt = ame.InferReturnType (ec, this, t);
3290 var invoke = Delegate.GetInvokeMethod (t);
3293 AParametersCollection pd = invoke.Parameters;
3294 return ame.Parameters.Count == pd.Count ? 1 : 0;
3297 TypeSpec rtype = invoke.ReturnType;
3298 return LowerBoundInference (rt, rtype) + 1;
3302 // if E is a method group and T is a delegate type or expression tree type
3303 // return type Tb with parameter types T1..Tk and return type Tb, and overload
3304 // resolution of E with the types T1..Tk yields a single method with return type U,
3305 // then a lower-bound inference is made from U for Tb.
3307 if (e is MethodGroupExpr) {
3308 if (!TypeManager.IsDelegateType (t)) {
3309 if (!t.IsExpressionTreeType)
3312 t = TypeManager.GetTypeArguments (t)[0];
3315 var invoke = Delegate.GetInvokeMethod (t);
3316 TypeSpec rtype = invoke.ReturnType;
3318 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3321 // LAMESPEC: Standard does not specify that all methodgroup arguments
3322 // has to be fixed but it does not specify how to do recursive type inference
3323 // either. We choose the simple option and infer return type only
3324 // if all delegate generic arguments are fixed.
3325 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3326 for (int i = 0; i < param_types.Length; ++i) {
3327 var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3328 if (inflated == null)
3331 if (IsUnfixed (inflated) >= 0)
3334 param_types[i] = inflated;
3337 MethodGroupExpr mg = (MethodGroupExpr) e;
3338 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3339 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3343 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3347 // if e is an expression with type U, then
3348 // a lower-bound inference is made from U for T
3350 return LowerBoundInference (e.Type, t) * 2;
3353 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3355 int idx = IsUnfixed (returnType);
3361 if (TypeManager.IsGenericType (returnType)) {
3362 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3363 RemoveDependentTypes (types, t);
3368 public bool UnfixedVariableExists {
3370 foreach (TypeSpec ut in fixed_types) {