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.Reflection;
15 using System.Reflection.Emit;
16 using System.Globalization;
17 using System.Collections.Generic;
21 namespace Mono.CSharp {
25 // Don't add or modify internal values, they are used as -/+ calculation signs
33 public enum SpecialConstraint
41 public class SpecialContraintExpr : FullNamedExpression
43 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
46 this.Constraint = constraint;
49 public SpecialConstraint Constraint { get; private set; }
51 protected override Expression DoResolve (ResolveContext rc)
53 throw new NotImplementedException ();
58 // A set of parsed constraints for a type parameter
60 public class Constraints
62 SimpleMemberName tparam;
63 List<FullNamedExpression> constraints;
68 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
71 this.constraints = constraints;
77 public Location Location {
83 public SimpleMemberName TypeParameter {
91 bool CheckConflictingInheritedConstraint (TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
93 if (!TypeSpec.IsBaseClass (ba, bb, false) && !TypeSpec.IsBaseClass (bb, ba, false)) {
94 context.Compiler.Report.Error (455, loc,
95 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
97 ba.GetSignatureForError (), bb.GetSignatureForError ());
104 public void CheckGenericConstraints (IMemberContext context)
106 foreach (var c in constraints) {
107 var ge = c as GenericTypeExpr;
109 ge.CheckConstraints (context);
114 // Resolve the constraints types with only possible early checks, return
115 // value `false' is reserved for recursive failure
117 public bool Resolve (IMemberContext context, TypeParameter tp)
127 List<TypeParameterSpec> tparam_types = null;
128 bool iface_found = false;
130 spec.BaseType = TypeManager.object_type;
132 for (int i = 0; i < constraints.Count; ++i) {
133 var constraint = constraints[i];
135 if (constraint is SpecialContraintExpr) {
136 spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
137 if (spec.HasSpecialStruct)
138 spec.BaseType = TypeManager.value_type;
140 // Set to null as it does not have a type
141 constraints[i] = null;
145 var type_expr = constraints[i] = constraint.ResolveAsTypeTerminal (context, false);
146 if (type_expr == null)
149 var gexpr = type_expr as GenericTypeExpr;
150 if (gexpr != null && gexpr.HasDynamicArguments ()) {
151 context.Compiler.Report.Error (1968, constraint.Location,
152 "A constraint cannot be the dynamic type `{0}'", gexpr.GetSignatureForError ());
156 var type = type_expr.Type;
158 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
159 context.Compiler.Report.SymbolRelatedToPreviousError (type);
160 context.Compiler.Report.Error (703, loc,
161 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
162 type.GetSignatureForError (), context.GetSignatureForError ());
165 if (type.IsInterface) {
166 if (!spec.AddInterface (type)) {
167 context.Compiler.Report.Error (405, constraint.Location,
168 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
176 var constraint_tp = type as TypeParameterSpec;
177 if (constraint_tp != null) {
178 if (tparam_types == null) {
179 tparam_types = new List<TypeParameterSpec> (2);
180 } else if (tparam_types.Contains (constraint_tp)) {
181 context.Compiler.Report.Error (405, constraint.Location,
182 "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
187 // Checks whether each generic method parameter constraint type
188 // is valid with respect to T
190 if (tp.IsMethodTypeParameter) {
191 TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
194 var tp_def = constraint_tp.MemberDefinition as TypeParameter;
195 if (tp_def != null && !tp_def.ResolveConstraints (context)) {
196 context.Compiler.Report.Error (454, constraint.Location,
197 "Circular constraint dependency involving `{0}' and `{1}'",
198 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
203 // Checks whether there are no conflicts between type parameter constraints
209 // A and B are not convertible and only 1 class constraint is allowed
211 if (constraint_tp.HasTypeConstraint) {
212 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
213 if (!CheckConflictingInheritedConstraint (spec.BaseType, constraint_tp.BaseType, context, constraint.Location))
216 for (int ii = 0; ii < tparam_types.Count; ++ii) {
217 if (!tparam_types[ii].HasTypeConstraint)
220 if (!CheckConflictingInheritedConstraint (tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
226 if (constraint_tp.HasSpecialStruct) {
227 context.Compiler.Report.Error (456, constraint.Location,
228 "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
229 constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
233 tparam_types.Add (constraint_tp);
237 if (iface_found || spec.HasTypeConstraint) {
238 context.Compiler.Report.Error (406, constraint.Location,
239 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
240 type.GetSignatureForError ());
243 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
244 context.Compiler.Report.Error (450, type_expr.Location,
245 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
246 type.GetSignatureForError ());
249 if (type == InternalType.Dynamic) {
250 context.Compiler.Report.Error (1967, constraint.Location, "A constraint cannot be the dynamic type");
254 if (type.IsSealed || !type.IsClass) {
255 context.Compiler.Report.Error (701, loc,
256 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
257 TypeManager.CSharpName (type));
262 context.Compiler.Report.Error (717, constraint.Location,
263 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
264 type.GetSignatureForError ());
265 } else if (type == TypeManager.array_type || type == TypeManager.delegate_type ||
266 type == TypeManager.enum_type || type == TypeManager.value_type ||
267 type == TypeManager.object_type || type == TypeManager.multicast_delegate_type) {
268 context.Compiler.Report.Error (702, constraint.Location,
269 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
273 spec.BaseType = type;
276 if (tparam_types != null)
277 spec.TypeArguments = tparam_types.ToArray ();
284 public void VerifyClsCompliance (Report report)
286 foreach (var c in constraints)
291 if (!c.Type.IsCLSCompliant ()) {
292 report.SymbolRelatedToPreviousError (c.Type);
293 report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
294 c.Type.GetSignatureForError ());
301 // A type parameter for a generic type or generic method definition
303 public class TypeParameter : MemberCore, ITypeDefinition
305 static readonly string[] attribute_target = new string [] { "type parameter" };
307 Constraints constraints;
308 GenericTypeParameterBuilder builder;
309 TypeParameterSpec spec;
311 public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
312 : base (parent, name, attrs)
314 this.constraints = constraints;
315 this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
318 public TypeParameter (TypeParameterSpec spec, DeclSpace parent, TypeSpec parentSpec, MemberName name, Attributes attrs)
319 : base (parent, name, attrs)
321 this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
322 BaseType = spec.BaseType,
323 InterfacesDefined = spec.InterfacesDefined,
324 TypeArguments = spec.TypeArguments
330 public override AttributeTargets AttributeTargets {
332 return AttributeTargets.GenericParameter;
336 public override string DocCommentHeader {
338 throw new InvalidOperationException (
339 "Unexpected attempt to get doc comment from " + this.GetType ());
343 public bool IsMethodTypeParameter {
345 return spec.IsMethodOwned;
349 public string Namespace {
355 public TypeParameterSpec Type {
361 public int TypeParametersCount {
367 public TypeParameterSpec[] TypeParameters {
373 public override string[] ValidAttributeTargets {
375 return attribute_target;
379 public Variance Variance {
381 return spec.Variance;
388 // This is called for each part of a partial generic type definition.
390 // If partial type parameters constraints are not null and we don't
391 // already have constraints they become our constraints. If we already
392 // have constraints, we must check that they're the same.
394 public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
397 throw new InvalidOperationException ();
399 var new_constraints = tp.constraints;
400 if (new_constraints == null)
403 // TODO: could create spec only
404 //tp.Define (null, -1, part.Definition);
405 tp.spec.DeclaringType = part.Definition;
406 if (!tp.ResolveConstraints (part))
409 if (constraints != null)
410 return spec.HasSameConstraintsDefinition (tp.Type);
412 // Copy constraint from resolved part to partial container
413 spec.SpecialConstraint = tp.spec.SpecialConstraint;
414 spec.InterfacesDefined = tp.spec.InterfacesDefined;
415 spec.TypeArguments = tp.spec.TypeArguments;
416 spec.BaseType = tp.spec.BaseType;
421 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
423 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
426 public void CheckGenericConstraints ()
428 if (constraints != null)
429 constraints.CheckGenericConstraints (this);
432 public TypeParameter CreateHoistedCopy (TypeContainer declaringType, TypeSpec declaringSpec)
434 return new TypeParameter (spec, declaringType, declaringSpec, MemberName, null);
437 public override bool Define ()
443 // This is the first method which is called during the resolving
444 // process; we're called immediately after creating the type parameters
445 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
448 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
451 throw new InternalErrorException ();
454 spec.DeclaringType = declaringType;
455 spec.SetMetaInfo (type);
458 public void EmitConstraints (GenericTypeParameterBuilder builder)
460 var attr = GenericParameterAttributes.None;
461 if (spec.Variance == Variance.Contravariant)
462 attr |= GenericParameterAttributes.Contravariant;
463 else if (spec.Variance == Variance.Covariant)
464 attr |= GenericParameterAttributes.Covariant;
466 if (spec.HasSpecialClass)
467 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
468 else if (spec.HasSpecialStruct)
469 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
471 if (spec.HasSpecialConstructor)
472 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
474 if (spec.BaseType != TypeManager.object_type)
475 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
477 if (spec.InterfacesDefined != null)
478 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
480 if (spec.TypeArguments != null)
481 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
483 builder.SetGenericParameterAttributes (attr);
486 public override void Emit ()
488 EmitConstraints (builder);
490 if (OptAttributes != null)
491 OptAttributes.Emit ();
496 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
498 Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
499 string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
500 string gtype_variance;
502 case Variance.Contravariant: gtype_variance = "contravariantly"; break;
503 case Variance.Covariant: gtype_variance = "covariantly"; break;
504 default: gtype_variance = "invariantly"; break;
507 Delegate d = mc as Delegate;
508 string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
510 Report.Error (1961, Location,
511 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
512 GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
515 public TypeSpec GetAttributeCoClass ()
520 public string GetAttributeDefaultMember ()
522 throw new NotSupportedException ();
525 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
527 throw new NotSupportedException ();
530 public override string GetSignatureForError ()
532 return MemberName.Name;
535 public MemberCache LoadMembers (TypeSpec declaringType)
537 throw new NotSupportedException ("Not supported for compiled definition");
541 // Resolves all type parameter constraints
543 public bool ResolveConstraints (IMemberContext context)
545 if (constraints != null)
546 return constraints.Resolve (context, this);
548 if (spec.BaseType == null)
549 spec.BaseType = TypeManager.object_type;
554 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
556 foreach (var tp in tparams) {
564 public override bool IsClsComplianceRequired ()
569 public new void VerifyClsCompliance ()
571 if (constraints != null)
572 constraints.VerifyClsCompliance (Report);
576 [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
577 public class TypeParameterSpec : TypeSpec
579 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
582 SpecialConstraint spec;
585 TypeSpec[] ifaces_defined;
588 // Creates type owned type parameter
590 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
591 : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
593 this.variance = variance;
595 state &= ~StateFlags.Obsolete_Undetected;
600 // Creates method owned type parameter
602 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
603 : this (null, index, definition, spec, variance, info)
609 public int DeclaredPosition {
615 public bool HasSpecialConstructor {
617 return (spec & SpecialConstraint.Constructor) != 0;
621 public bool HasSpecialClass {
623 return (spec & SpecialConstraint.Class) != 0;
627 public bool HasSpecialStruct {
629 return (spec & SpecialConstraint.Struct) != 0;
633 public bool HasTypeConstraint {
635 return BaseType != TypeManager.object_type && BaseType != TypeManager.value_type;
639 public override IList<TypeSpec> Interfaces {
641 if ((state & StateFlags.InterfacesExpanded) == 0) {
642 if (ifaces != null) {
643 for (int i = 0; i < ifaces.Count; ++i ) {
644 var iface_type = ifaces[i];
645 if (iface_type.Interfaces != null) {
646 if (ifaces_defined == null)
647 ifaces_defined = ifaces.ToArray ();
649 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
650 var ii_iface_type = iface_type.Interfaces [ii];
652 AddInterface (ii_iface_type);
658 if (ifaces_defined == null && ifaces != null)
659 ifaces_defined = ifaces.ToArray ();
661 state |= StateFlags.InterfacesExpanded;
669 // Unexpanded interfaces list
671 public TypeSpec[] InterfacesDefined {
673 if (ifaces_defined == null && ifaces != null)
674 ifaces_defined = ifaces.ToArray ();
676 return ifaces_defined;
679 ifaces_defined = value;
683 public bool IsConstrained {
685 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
690 // Returns whether the type parameter is "known to be a reference type"
692 public bool IsReferenceType {
694 return (spec & SpecialConstraint.Class) != 0 || HasTypeConstraint;
698 public bool IsValueType { // TODO: Do I need this ?
700 // TODO MemberCache: probably wrong
701 return HasSpecialStruct;
705 public override string Name {
707 return definition.Name;
711 public bool IsMethodOwned {
713 return DeclaringType == null;
717 public SpecialConstraint SpecialConstraint {
727 // Types used to inflate the generic type
729 public new TypeSpec[] TypeArguments {
738 public Variance Variance {
746 public string DisplayDebugInfo ()
748 var s = GetSignatureForError ();
749 return IsMethodOwned ? s + "!!" : s + "!";
753 // Finds effective base class
755 public TypeSpec GetEffectiveBase ()
757 if (HasSpecialStruct) {
758 return TypeManager.value_type;
761 if (BaseType != null && targs == null)
765 if (HasTypeConstraint) {
766 Array.Resize (ref types, types.Length + 1);
767 types[types.Length - 1] = BaseType;
771 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
773 return TypeManager.object_type;
776 public override string GetSignatureForError ()
782 // Constraints have to match by definition but not position, used by
783 // partial classes or methods
785 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
787 if (spec != other.spec)
790 if (BaseType != other.BaseType)
793 if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
796 if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
803 // Constraints have to match by using same set of types, used by
804 // implicit interface implementation
806 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
808 if (spec != other.spec)
812 // It can be same base type or inflated type parameter
814 // interface I<T> { void Foo<U> where U : T; }
815 // class A : I<int> { void Foo<X> where X : int {} }
818 if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
819 if (other.targs == null)
823 foreach (var otarg in other.targs) {
824 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
834 // Check interfaces implementation -> definition
835 if (InterfacesDefined != null) {
836 foreach (var iface in InterfacesDefined) {
838 if (other.InterfacesDefined != null) {
839 foreach (var oiface in other.InterfacesDefined) {
840 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
850 if (other.targs != null) {
851 foreach (var otarg in other.targs) {
852 if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
864 // Check interfaces implementation <- definition
865 if (other.InterfacesDefined != null) {
866 if (InterfacesDefined == null)
869 foreach (var oiface in other.InterfacesDefined) {
871 foreach (var iface in InterfacesDefined) {
872 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
883 // Check type parameters implementation -> definition
885 if (other.targs == null)
888 foreach (var targ in targs) {
890 foreach (var otarg in other.targs) {
891 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
902 // Check type parameters implementation <- definition
903 if (other.targs != null) {
904 foreach (var otarg in other.targs) {
905 // Ignore inflated type arguments, were checked above
906 if (!otarg.IsGenericParameter)
913 foreach (var targ in targs) {
914 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
928 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
930 TypeParameterSpec[] constraints = null;
932 for (int i = 0; i < tparams.Length; ++i) {
934 if (tp.HasTypeConstraint || tp.Interfaces != null || tp.TypeArguments != null) {
935 if (constraints == null) {
936 constraints = new TypeParameterSpec[tparams.Length];
937 Array.Copy (tparams, constraints, constraints.Length);
940 constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator);
944 if (constraints == null)
945 constraints = tparams;
950 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
952 tps.BaseType = inflator.Inflate (BaseType);
953 if (ifaces != null) {
954 tps.ifaces = new List<TypeSpec> (ifaces.Count);
955 for (int i = 0; i < ifaces.Count; ++i)
956 tps.ifaces.Add (inflator.Inflate (ifaces[i]));
959 tps.targs = new TypeSpec[targs.Length];
960 for (int i = 0; i < targs.Length; ++i)
961 tps.targs[i] = inflator.Inflate (targs[i]);
965 public override MemberSpec InflateMember (TypeParameterInflator inflator)
967 var tps = (TypeParameterSpec) MemberwiseClone ();
968 InflateConstraints (inflator, tps);
973 // Populates type parameter members using type parameter constraints
974 // The trick here is to be called late enough but not too late to
975 // populate member cache with all members from other types
977 protected override void InitializeMemberCache (bool onlyTypes)
979 cache = new MemberCache ();
980 if (ifaces != null) {
981 foreach (var iface_type in Interfaces) {
982 cache.AddInterface (iface_type);
987 public bool IsConvertibleToInterface (TypeSpec iface)
989 if (Interfaces != null) {
990 foreach (var t in Interfaces) {
996 if (TypeArguments != null) {
997 foreach (var t in TypeArguments) {
998 if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1006 public override TypeSpec Mutate (TypeParameterMutator mutator)
1008 return mutator.Mutate (this);
1012 public struct TypeParameterInflator
1014 readonly TypeSpec type;
1015 readonly TypeParameterSpec[] tparams;
1016 readonly TypeSpec[] targs;
1018 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1019 : this (type, nested.tparams, nested.targs)
1023 public TypeParameterInflator (TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1025 if (tparams.Length != targs.Length)
1026 throw new ArgumentException ("Invalid arguments");
1028 this.tparams = tparams;
1034 // Type parameters to inflate
1036 public TypeParameterSpec[] TypeParameters {
1042 public TypeSpec Inflate (TypeSpec ts)
1044 var tp = ts as TypeParameterSpec;
1046 return Inflate (tp);
1048 var ac = ts as ArrayContainer;
1050 var et = Inflate (ac.Element);
1051 if (et != ac.Element)
1052 return ArrayContainer.MakeType (et, ac.Rank);
1058 // When inflating a nested type, inflate its parent first
1059 // in case it's using same type parameters (was inflated within the type)
1062 var parent = Inflate (ts.DeclaringType);
1063 if (ts.DeclaringType != parent) {
1065 // Keep the inflated type arguments
1067 var targs = ts.TypeArguments;
1070 // Parent was inflated, find the same type on inflated type
1071 // to use same cache for nested types on same generic parent
1073 // TODO: Should use BindingRestriction.DeclaredOnly or GetMember
1074 ts = MemberCache.FindNestedType (parent, ts.Name, targs.Length);
1077 // Handle the tricky case where parent shares local type arguments
1078 // which means inflating inflated type
1081 // public static Nested<T> Foo () { return null; }
1083 // public class Nested<U> {}
1086 // return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1088 if (targs.Length > 0) {
1089 var inflated_targs = new TypeSpec [targs.Length];
1090 for (var i = 0; i < targs.Length; ++i)
1091 inflated_targs[i] = Inflate (targs[i]);
1093 ts = ts.MakeGenericType (inflated_targs);
1100 // Inflate generic type
1102 return InflateTypeParameters (ts);
1107 public TypeSpec Inflate (TypeParameterSpec tp)
1109 for (int i = 0; i < tparams.Length; ++i)
1110 if (tparams [i] == tp)
1113 // This can happen when inflating nested types
1114 // without type arguments specified
1119 // Inflates generic types
1121 TypeSpec InflateTypeParameters (TypeSpec type)
1123 var targs = new TypeSpec[type.Arity];
1126 var gti = type as InflatedTypeSpec;
1129 // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1132 for (; i < targs.Length; ++i)
1133 targs[i] = Inflate (gti.TypeArguments[i]);
1135 return gti.GetDefinition ().MakeGenericType (targs);
1139 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1141 var args = type.MemberDefinition.TypeParameters;
1142 foreach (var ds_tp in args)
1143 targs[i++] = Inflate (ds_tp);
1145 return type.MakeGenericType (targs);
1148 public TypeSpec TypeInstance {
1149 get { return type; }
1154 // Before emitting any code we have to change all MVAR references to VAR
1155 // when the method is of generic type and has hoisted variables
1157 public class TypeParameterMutator
1159 TypeParameter[] mvar;
1160 TypeParameter[] var;
1161 Dictionary<TypeSpec, TypeSpec> mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1163 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1165 if (mvar.Length != var.Length)
1166 throw new ArgumentException ();
1172 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1174 if (type is InflatedTypeSpec) {
1175 if (type.DeclaringType == null)
1176 return type.GetDefinition ();
1178 var parent = GetMemberDeclaringType (type.DeclaringType);
1179 type = MemberCache.GetMember<TypeSpec> (parent, type);
1185 public TypeSpec Mutate (TypeSpec ts)
1188 if (mutated_typespec.TryGetValue (ts, out value))
1191 value = ts.Mutate (this);
1192 mutated_typespec.Add (ts, value);
1196 public FieldInfo Mutate (FieldSpec fs)
1199 return fs.GetMetaInfo ();
1202 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1204 for (int i = 0; i < mvar.Length; ++i) {
1205 if (mvar[i].Type == tp)
1212 public TypeSpec[] Mutate (TypeSpec[] targs)
1214 TypeSpec[] mutated = new TypeSpec[targs.Length];
1215 bool changed = false;
1216 for (int i = 0; i < targs.Length; ++i) {
1217 mutated[i] = Mutate (targs[i]);
1218 changed |= targs[i] != mutated[i];
1221 return changed ? mutated : targs;
1226 /// A TypeExpr which already resolved to a type parameter.
1228 public class TypeParameterExpr : TypeExpr {
1230 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1232 this.type = type_parameter.Type;
1233 this.eclass = ExprClass.TypeParameter;
1237 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1239 throw new NotSupportedException ();
1242 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1247 public override bool CheckAccessLevel (IMemberContext ds)
1253 public class InflatedTypeSpec : TypeSpec
1256 TypeParameterSpec[] constraints;
1257 readonly TypeSpec open_type;
1259 public InflatedTypeSpec (TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1260 : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1263 throw new ArgumentNullException ("targs");
1265 // this.state = openType.state;
1266 this.open_type = openType;
1272 public override TypeSpec BaseType {
1274 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1275 InitializeMemberCache (true);
1277 return base.BaseType;
1282 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1284 public TypeParameterSpec[] Constraints {
1286 if (constraints == null) {
1287 var inflator = new TypeParameterInflator (this, MemberDefinition.TypeParameters, targs);
1288 constraints = TypeParameterSpec.InflateConstraints (inflator, MemberDefinition.TypeParameters);
1295 public override IList<TypeSpec> Interfaces {
1298 InitializeMemberCache (true);
1300 return base.Interfaces;
1304 public override MemberCache MemberCacheTypes {
1307 InitializeMemberCache (true);
1314 // Types used to inflate the generic type
1316 public override TypeSpec[] TypeArguments {
1324 Type CreateMetaInfo (TypeParameterMutator mutator)
1327 // Converts nested type arguments into right order
1328 // Foo<string, bool>.Bar<int> => string, bool, int
1330 var all = new List<Type> ();
1331 TypeSpec type = this;
1332 TypeSpec definition = type;
1334 if (type.GetDefinition().IsGeneric) {
1336 type.TypeArguments != TypeSpec.EmptyTypes ?
1337 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1338 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1341 definition = definition.GetDefinition ();
1342 type = type.DeclaringType;
1343 } while (type != null);
1345 return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1348 public override ObsoleteAttribute GetAttributeObsolete ()
1350 return open_type.GetAttributeObsolete ();
1353 protected override bool IsNotCLSCompliant ()
1355 if (base.IsNotCLSCompliant ())
1358 foreach (var ta in TypeArguments) {
1359 if (ta.MemberDefinition.IsNotCLSCompliant ())
1366 public override TypeSpec GetDefinition ()
1371 public override Type GetMetaInfo ()
1374 info = CreateMetaInfo (null);
1379 public override string GetSignatureForError ()
1381 if (TypeManager.IsNullableType (open_type))
1382 return targs[0].GetSignatureForError () + "?";
1384 return base.GetSignatureForError ();
1387 protected override string GetTypeNameSignature ()
1389 if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1392 return "<" + TypeManager.CSharpName (targs) + ">";
1395 protected override void InitializeMemberCache (bool onlyTypes)
1398 cache = new MemberCache (onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache);
1400 TypeParameterSpec[] tparams_full;
1401 TypeSpec[] targs_full = targs;
1404 // Special case is needed when we are inflating an open type (nested type definition)
1405 // on inflated parent. Consider following case
1407 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1409 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1411 List<TypeSpec> merged_targs = null;
1412 List<TypeParameterSpec> merged_tparams = null;
1414 var type = DeclaringType;
1417 if (type.TypeArguments.Length > 0) {
1418 if (merged_targs == null) {
1419 merged_targs = new List<TypeSpec> ();
1420 merged_tparams = new List<TypeParameterSpec> ();
1421 if (targs.Length > 0) {
1422 merged_targs.AddRange (targs);
1423 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1426 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1427 merged_targs.AddRange (type.TypeArguments);
1429 type = type.DeclaringType;
1430 } while (type != null);
1432 if (merged_targs != null) {
1433 // Type arguments are not in the right order but it should not matter in this case
1434 targs_full = merged_targs.ToArray ();
1435 tparams_full = merged_tparams.ToArray ();
1436 } else if (targs.Length == 0) {
1437 tparams_full = TypeParameterSpec.EmptyTypes;
1439 tparams_full = open_type.MemberDefinition.TypeParameters;
1441 } else if (targs.Length == 0) {
1442 tparams_full = TypeParameterSpec.EmptyTypes;
1444 tparams_full = open_type.MemberDefinition.TypeParameters;
1447 var inflator = new TypeParameterInflator (this, tparams_full, targs_full);
1450 // Two stage inflate due to possible nested types recursive
1460 // When resolving type of `b' members of `B' cannot be
1461 // inflated because are not yet available in membercache
1463 if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1464 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1467 // Inflate any implemented interfaces
1469 if (open_type.Interfaces != null) {
1470 ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1471 foreach (var iface in open_type.Interfaces) {
1472 var iface_inflated = inflator.Inflate (iface);
1473 AddInterface (iface_inflated);
1478 // Handles the tricky case of recursive nested base generic type
1480 // class A<T> : Base<A<T>.Nested> {
1484 // When inflating A<T>. base type is not yet known, secondary
1485 // inflation is required (not common case) once base scope
1488 if (open_type.BaseType == null) {
1490 state |= StateFlags.PendingBaseTypeInflate;
1492 BaseType = inflator.Inflate (open_type.BaseType);
1494 } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1495 BaseType = inflator.Inflate (open_type.BaseType);
1496 state &= ~StateFlags.PendingBaseTypeInflate;
1500 state |= StateFlags.PendingMemberCacheMembers;
1504 var tc = open_type.MemberDefinition as TypeContainer;
1505 if (tc != null && !tc.HasMembersDefined)
1506 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1508 if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1509 BaseType = inflator.Inflate (open_type.BaseType);
1510 state &= ~StateFlags.PendingBaseTypeInflate;
1513 state &= ~StateFlags.PendingMemberCacheMembers;
1514 open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1517 public override TypeSpec Mutate (TypeParameterMutator mutator)
1519 var targs = TypeArguments;
1521 targs = mutator.Mutate (targs);
1523 var decl = DeclaringType;
1524 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1525 decl = mutator.Mutate (decl);
1527 if (targs == TypeArguments && decl == DeclaringType)
1530 var mutated = (InflatedTypeSpec) MemberwiseClone ();
1531 if (decl != DeclaringType) {
1532 // Gets back MethodInfo in case of metaInfo was inflated
1533 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1535 mutated.declaringType = decl;
1536 mutated.state |= StateFlags.PendingMetaInflate;
1539 if (targs != null) {
1540 mutated.targs = targs;
1541 mutated.info = null;
1550 // Tracks the type arguments when instantiating a generic type. It's used
1551 // by both type arguments and type parameters
1553 public class TypeArguments
1555 List<FullNamedExpression> args;
1558 public TypeArguments (params FullNamedExpression[] types)
1560 this.args = new List<FullNamedExpression> (types);
1563 public void Add (FullNamedExpression type)
1568 // TODO: Kill this monster
1569 public TypeParameterName[] GetDeclarations ()
1571 return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1575 /// We may only be used after Resolve() is called and return the fully
1578 // TODO: Not needed, just return type from resolve
1579 public TypeSpec[] Arguments {
1591 public virtual bool IsEmpty {
1597 public string GetSignatureForError()
1599 StringBuilder sb = new StringBuilder ();
1600 for (int i = 0; i < Count; ++i) {
1603 sb.Append (expr.GetSignatureForError ());
1609 return sb.ToString ();
1613 /// Resolve the type arguments.
1615 public virtual bool Resolve (IMemberContext ec)
1618 return atypes.Length != 0;
1620 int count = args.Count;
1623 atypes = new TypeSpec [count];
1625 for (int i = 0; i < count; i++){
1626 TypeExpr te = args[i].ResolveAsTypeTerminal (ec, false);
1632 atypes[i] = te.Type;
1634 if (te.Type.IsStatic) {
1635 ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1636 te.GetSignatureForError ());
1640 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1641 ec.Compiler.Report.Error (306, te.Location,
1642 "The type `{0}' may not be used as a type argument",
1643 te.GetSignatureForError ());
1649 atypes = TypeSpec.EmptyTypes;
1654 public TypeArguments Clone ()
1656 TypeArguments copy = new TypeArguments ();
1657 foreach (var ta in args)
1664 public class UnboundTypeArguments : TypeArguments
1666 public UnboundTypeArguments (int arity)
1667 : base (new FullNamedExpression[arity])
1671 public override bool IsEmpty {
1677 public override bool Resolve (IMemberContext ec)
1679 // Nothing to be resolved
1684 public class TypeParameterName : SimpleName
1686 Attributes attributes;
1689 public TypeParameterName (string name, Attributes attrs, Location loc)
1690 : this (name, attrs, Variance.None, loc)
1694 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1698 this.variance = variance;
1701 public Attributes OptAttributes {
1707 public Variance Variance {
1715 // A type expression of generic type with type arguments
1717 class GenericTypeExpr : TypeExpr
1721 bool constraints_checked;
1724 /// Instantiate the generic type `t' with the type arguments `args'.
1725 /// Use this constructor if you already know the fully resolved
1728 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1730 this.open_type = open_type;
1735 public TypeArguments TypeArguments {
1736 get { return args; }
1739 public override string GetSignatureForError ()
1741 return TypeManager.CSharpName (type);
1744 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1746 if (!args.Resolve (ec))
1749 TypeSpec[] atypes = args.Arguments;
1752 // Now bind the parameters
1754 type = open_type.MakeGenericType (atypes);
1757 // Check constraints when context is not method/base type
1759 if (!ec.HasUnresolvedConstraints)
1760 CheckConstraints (ec);
1766 // Checks the constraints of open generic type against type
1767 // arguments. Has to be called after all members have been defined
1769 public bool CheckConstraints (IMemberContext ec)
1771 if (constraints_checked)
1774 constraints_checked = true;
1776 var gtype = (InflatedTypeSpec) type;
1777 var constraints = gtype.Constraints;
1778 if (constraints == null)
1781 return ConstraintChecker.CheckAll (ec, open_type, args.Arguments, constraints, loc);
1784 public override bool CheckAccessLevel (IMemberContext mc)
1786 DeclSpace c = mc.CurrentMemberDefinition as DeclSpace;
1788 c = mc.CurrentMemberDefinition.Parent;
1790 return c.CheckAccessLevel (open_type);
1793 public bool HasDynamicArguments ()
1795 return HasDynamicArguments (args.Arguments);
1798 static bool HasDynamicArguments (TypeSpec[] args)
1800 for (int i = 0; i < args.Length; ++i) {
1803 if (item == InternalType.Dynamic)
1806 if (TypeManager.IsGenericType (item))
1807 return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1810 while (item.IsArray) {
1811 item = ((ArrayContainer) item).Element;
1814 if (item == InternalType.Dynamic)
1822 public override bool Equals (object obj)
1824 GenericTypeExpr cobj = obj as GenericTypeExpr;
1828 if ((type == null) || (cobj.type == null))
1831 return type == cobj.type;
1834 public override int GetHashCode ()
1836 return base.GetHashCode ();
1841 // Generic type with unbound type arguments, used for typeof (G<,,>)
1843 class GenericOpenTypeExpr : TypeExpr
1845 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
1847 this.type = type.GetDefinition ();
1851 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1857 static class ConstraintChecker
1860 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1861 /// after fully resolving the constructed type.
1863 public static bool CheckAll (IMemberContext mc, MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
1865 for (int i = 0; i < tparams.Length; i++) {
1866 if (!CheckConstraint (mc, context, targs [i], tparams [i], loc))
1873 static bool CheckConstraint (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
1876 // First, check the `class' and `struct' constraints.
1878 if (tparam.HasSpecialClass && !TypeManager.IsReferenceType (atype)) {
1879 mc.Compiler.Report.Error (452, loc,
1880 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
1881 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1885 if (tparam.HasSpecialStruct && (!TypeManager.IsValueType (atype) || TypeManager.IsNullableType (atype))) {
1886 mc.Compiler.Report.Error (453, loc,
1887 "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}'",
1888 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1893 // The class constraint comes next.
1895 if (tparam.HasTypeConstraint) {
1896 CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc);
1900 // Now, check the interfaces and type parameters constraints
1902 if (tparam.Interfaces != null) {
1903 if (TypeManager.IsNullableType (atype)) {
1904 mc.Compiler.Report.Error (313, loc,
1905 "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",
1906 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
1908 foreach (TypeSpec iface in tparam.Interfaces) {
1909 CheckConversion (mc, context, atype, tparam, iface, loc);
1915 // Finally, check the constructor constraint.
1917 if (!tparam.HasSpecialConstructor)
1920 if (!HasDefaultConstructor (atype)) {
1921 mc.Compiler.Report.SymbolRelatedToPreviousError (atype);
1922 mc.Compiler.Report.Error (310, loc,
1923 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
1924 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1931 static void CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
1933 var expr = new EmptyExpression (atype);
1934 if (!Convert.ImplicitStandardConversionExists (expr, ttype)) {
1935 mc.Compiler.Report.SymbolRelatedToPreviousError (tparam);
1936 if (TypeManager.IsValueType (atype)) {
1937 mc.Compiler.Report.Error (315, loc, "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}'",
1938 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
1939 } else if (atype.IsGenericParameter) {
1940 mc.Compiler.Report.Error (314, loc, "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}'",
1941 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
1943 mc.Compiler.Report.Error (311, loc, "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}'",
1944 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
1949 static bool HasDefaultConstructor (TypeSpec atype)
1951 var tp = atype as TypeParameterSpec;
1953 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
1956 if (atype.IsStruct || atype.IsEnum)
1959 if (atype.IsAbstract)
1962 var tdef = atype.GetDefinition ();
1965 // In some circumstances MemberCache is not yet populated and members
1966 // cannot be defined yet (recursive type new constraints)
1968 // class A<T> where T : B<T>, new () {}
1969 // class B<T> where T : A<T>, new () {}
1971 var tc = tdef.MemberDefinition as Class;
1973 if (tc.InstanceConstructors == null) {
1974 // Default ctor will be generated later
1978 foreach (var c in tc.InstanceConstructors) {
1979 if (c.ParameterInfo.IsEmpty) {
1980 if ((c.ModFlags & Modifiers.PUBLIC) != 0)
1988 var found = MemberCache.FindMember (tdef,
1989 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
1990 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
1992 return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
1997 /// A generic method definition.
1999 public class GenericMethod : DeclSpace
2001 ParametersCompiled parameters;
2003 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
2004 FullNamedExpression return_type, ParametersCompiled parameters)
2005 : base (ns, parent, name, null)
2007 this.parameters = parameters;
2010 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2011 FullNamedExpression return_type, ParametersCompiled parameters)
2012 : this (ns, parent, name, return_type, parameters)
2014 this.type_params = tparams;
2017 public override TypeParameter[] CurrentTypeParameters {
2019 return base.type_params;
2023 public override TypeBuilder DefineType ()
2025 throw new Exception ();
2028 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2030 throw new NotSupportedException ();
2033 public override bool Define ()
2035 throw new NotSupportedException ();
2039 /// Define and resolve the type parameters.
2040 /// We're called from Method.Define().
2042 public bool Define (MethodOrOperator m)
2044 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2045 string[] snames = new string [names.Length];
2046 for (int i = 0; i < names.Length; i++) {
2047 string type_argument_name = names[i].Name;
2048 int idx = parameters.GetParameterIndexByName (type_argument_name);
2053 b = new ToplevelBlock (Compiler, Location);
2055 b.Error_AlreadyDeclaredTypeParameter (parameters [i].Location,
2056 type_argument_name, "method parameter");
2059 if (m.Block != null) {
2060 var ikv = m.Block.GetKnownVariable (type_argument_name);
2062 ikv.Block.Error_AlreadyDeclaredTypeParameter (ikv.Location, type_argument_name, "local variable");
2065 snames[i] = type_argument_name;
2068 GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2069 for (int i = 0; i < TypeParameters.Length; i++)
2070 TypeParameters [i].Define (gen_params [i], null);
2075 public void EmitAttributes ()
2077 if (OptAttributes != null)
2078 OptAttributes.Emit ();
2081 public override string GetSignatureForError ()
2083 return base.GetSignatureForError () + parameters.GetSignatureForError ();
2086 public override AttributeTargets AttributeTargets {
2088 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2092 public override string DocCommentHeader {
2093 get { return "M:"; }
2096 public new void VerifyClsCompliance ()
2098 foreach (TypeParameter tp in TypeParameters) {
2099 tp.VerifyClsCompliance ();
2104 public partial class TypeManager
2106 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2108 var tp = t as TypeParameterSpec;
2110 Variance v = tp.Variance;
2111 if (expected == Variance.None && v != expected ||
2112 expected == Variance.Covariant && v == Variance.Contravariant ||
2113 expected == Variance.Contravariant && v == Variance.Covariant) {
2114 ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2120 if (t.TypeArguments.Length > 0) {
2121 var targs_definition = t.MemberDefinition.TypeParameters;
2122 TypeSpec[] targs = GetTypeArguments (t);
2123 for (int i = 0; i < targs.Length; ++i) {
2124 Variance v = targs_definition[i].Variance;
2125 CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2132 return CheckTypeVariance (GetElementType (t), expected, member);
2134 return Variance.None;
2138 /// Type inference. Try to infer the type arguments from `method',
2139 /// which is invoked with the arguments `arguments'. This is used
2140 /// when resolving an Invocation or a DelegateInvocation and the user
2141 /// did not explicitly specify type arguments.
2143 public static int InferTypeArguments (ResolveContext ec, Arguments arguments, ref MethodSpec method)
2145 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2146 TypeSpec[] i_args = ti.InferMethodArguments (ec, method);
2148 return ti.InferenceScore;
2150 if (i_args.Length == 0)
2153 method = method.MakeGenericMethod (i_args);
2158 abstract class ATypeInference
2160 protected readonly Arguments arguments;
2161 protected readonly int arg_count;
2163 protected ATypeInference (Arguments arguments)
2165 this.arguments = arguments;
2166 if (arguments != null)
2167 arg_count = arguments.Count;
2170 public static ATypeInference CreateInstance (Arguments arguments)
2172 return new TypeInference (arguments);
2175 public virtual int InferenceScore {
2177 return int.MaxValue;
2181 public abstract TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method);
2185 // Implements C# type inference
2187 class TypeInference : ATypeInference
2190 // Tracks successful rate of type inference
2192 int score = int.MaxValue;
2194 public TypeInference (Arguments arguments)
2199 public override int InferenceScore {
2205 public override TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2207 var method_generic_args = method.GenericDefinition.TypeParameters;
2208 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2209 if (!context.UnfixedVariableExists)
2210 return TypeSpec.EmptyTypes;
2212 AParametersCollection pd = method.Parameters;
2213 if (!InferInPhases (ec, context, pd))
2216 return context.InferredTypeArguments;
2220 // Implements method type arguments inference
2222 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2224 int params_arguments_start;
2225 if (methodParameters.HasParams) {
2226 params_arguments_start = methodParameters.Count - 1;
2228 params_arguments_start = arg_count;
2231 TypeSpec [] ptypes = methodParameters.Types;
2234 // The first inference phase
2236 TypeSpec method_parameter = null;
2237 for (int i = 0; i < arg_count; i++) {
2238 Argument a = arguments [i];
2242 if (i < params_arguments_start) {
2243 method_parameter = methodParameters.Types [i];
2244 } else if (i == params_arguments_start) {
2245 if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2246 method_parameter = methodParameters.Types [params_arguments_start];
2248 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2250 ptypes = (TypeSpec[]) ptypes.Clone ();
2251 ptypes [i] = method_parameter;
2255 // When a lambda expression, an anonymous method
2256 // is used an explicit argument type inference takes a place
2258 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2260 if (am.ExplicitTypeInference (ec, tic, method_parameter))
2266 score -= tic.ExactInference (a.Type, method_parameter);
2270 if (a.Expr.Type == InternalType.Null)
2273 if (TypeManager.IsValueType (method_parameter)) {
2274 score -= tic.LowerBoundInference (a.Type, method_parameter);
2279 // Otherwise an output type inference is made
2281 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2285 // Part of the second phase but because it happens only once
2286 // we don't need to call it in cycle
2288 bool fixed_any = false;
2289 if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2292 return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2295 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2297 bool fixed_any = false;
2298 if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2301 // If no further unfixed type variables exist, type inference succeeds
2302 if (!tic.UnfixedVariableExists)
2305 if (!fixed_any && fixDependent)
2308 // For all arguments where the corresponding argument output types
2309 // contain unfixed type variables but the input types do not,
2310 // an output type inference is made
2311 for (int i = 0; i < arg_count; i++) {
2313 // Align params arguments
2314 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2316 if (!TypeManager.IsDelegateType (t_i)) {
2317 if (t_i.GetDefinition () != TypeManager.expression_type)
2320 t_i = TypeManager.GetTypeArguments (t_i) [0];
2323 var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i);
2324 TypeSpec rtype = mi.ReturnType;
2326 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2327 score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2331 return DoSecondPhase (ec, tic, methodParameters, true);
2335 public class TypeInferenceContext
2344 class BoundInfo : IEquatable<BoundInfo>
2346 public readonly TypeSpec Type;
2347 public readonly BoundKind Kind;
2349 public BoundInfo (TypeSpec type, BoundKind kind)
2355 public override int GetHashCode ()
2357 return Type.GetHashCode ();
2360 #region IEquatable<BoundInfo> Members
2362 public bool Equals (BoundInfo other)
2364 return Type == other.Type && Kind == other.Kind;
2370 readonly TypeSpec[] unfixed_types;
2371 readonly TypeSpec[] fixed_types;
2372 readonly List<BoundInfo>[] bounds;
2375 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2376 public TypeInferenceContext (TypeSpec[] typeArguments)
2378 if (typeArguments.Length == 0)
2379 throw new ArgumentException ("Empty generic arguments");
2381 fixed_types = new TypeSpec [typeArguments.Length];
2382 for (int i = 0; i < typeArguments.Length; ++i) {
2383 if (typeArguments [i].IsGenericParameter) {
2384 if (bounds == null) {
2385 bounds = new List<BoundInfo> [typeArguments.Length];
2386 unfixed_types = new TypeSpec [typeArguments.Length];
2388 unfixed_types [i] = typeArguments [i];
2390 fixed_types [i] = typeArguments [i];
2396 // Used together with AddCommonTypeBound fo implement
2397 // 7.4.2.13 Finding the best common type of a set of expressions
2399 public TypeInferenceContext ()
2401 fixed_types = new TypeSpec [1];
2402 unfixed_types = new TypeSpec [1];
2403 unfixed_types[0] = InternalType.Arglist; // it can be any internal type
2404 bounds = new List<BoundInfo> [1];
2407 public TypeSpec[] InferredTypeArguments {
2413 public void AddCommonTypeBound (TypeSpec type)
2415 AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2418 void AddToBounds (BoundInfo bound, int index)
2421 // Some types cannot be used as type arguments
2423 if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2426 var a = bounds [index];
2428 a = new List<BoundInfo> (2);
2434 if (a.Contains (bound))
2440 bool AllTypesAreFixed (TypeSpec[] types)
2442 foreach (TypeSpec t in types) {
2443 if (t.IsGenericParameter) {
2449 if (TypeManager.IsGenericType (t))
2450 return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2457 // 26.3.3.8 Exact Inference
2459 public int ExactInference (TypeSpec u, TypeSpec v)
2461 // If V is an array type
2466 // TODO MemberCache: GetMetaInfo ()
2467 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2470 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2473 // If V is constructed type and U is constructed type
2474 if (TypeManager.IsGenericType (v)) {
2475 if (!TypeManager.IsGenericType (u))
2478 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2479 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2480 if (ga_u.Length != ga_v.Length)
2484 for (int i = 0; i < ga_u.Length; ++i)
2485 score += ExactInference (ga_u [i], ga_v [i]);
2487 return score > 0 ? 1 : 0;
2490 // If V is one of the unfixed type arguments
2491 int pos = IsUnfixed (v);
2495 AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2499 public bool FixAllTypes (ResolveContext ec)
2501 for (int i = 0; i < unfixed_types.Length; ++i) {
2502 if (!FixType (ec, i))
2509 // All unfixed type variables Xi are fixed for which all of the following hold:
2510 // a, There is at least one type variable Xj that depends on Xi
2511 // b, Xi has a non-empty set of bounds
2513 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2515 for (int i = 0; i < unfixed_types.Length; ++i) {
2516 if (unfixed_types[i] == null)
2519 if (bounds[i] == null)
2522 if (!FixType (ec, i))
2532 // All unfixed type variables Xi which depend on no Xj are fixed
2534 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2536 var types_to_fix = new List<TypeSpec> (unfixed_types);
2537 for (int i = 0; i < methodParameters.Length; ++i) {
2538 TypeSpec t = methodParameters[i];
2540 if (!TypeManager.IsDelegateType (t)) {
2541 if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
2544 t = TypeManager.GetTypeArguments (t) [0];
2547 if (t.IsGenericParameter)
2550 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2551 TypeSpec rtype = invoke.ReturnType;
2552 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2555 // Remove dependent types, they cannot be fixed yet
2556 RemoveDependentTypes (types_to_fix, rtype);
2559 foreach (TypeSpec t in types_to_fix) {
2563 int idx = IsUnfixed (t);
2564 if (idx >= 0 && !FixType (ec, idx)) {
2569 fixed_any = types_to_fix.Count > 0;
2576 public bool FixType (ResolveContext ec, int i)
2578 // It's already fixed
2579 if (unfixed_types[i] == null)
2580 throw new InternalErrorException ("Type argument has been already fixed");
2585 var candidates = bounds [i];
2586 if (candidates == null)
2589 if (candidates.Count == 1) {
2590 unfixed_types[i] = null;
2591 TypeSpec t = candidates[0].Type;
2592 if (t == InternalType.Null)
2595 fixed_types [i] = t;
2600 // Determines a unique type from which there is
2601 // a standard implicit conversion to all the other
2604 TypeSpec best_candidate = null;
2606 int candidates_count = candidates.Count;
2607 for (int ci = 0; ci < candidates_count; ++ci) {
2608 BoundInfo bound = candidates [ci];
2609 for (cii = 0; cii < candidates_count; ++cii) {
2613 BoundInfo cbound = candidates[cii];
2615 // Same type parameters with different bounds
2616 if (cbound.Type == bound.Type) {
2617 if (bound.Kind != BoundKind.Exact)
2623 if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2624 if (cbound.Kind == BoundKind.Lower) {
2625 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2631 if (cbound.Kind == BoundKind.Upper) {
2632 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2639 if (bound.Kind != BoundKind.Exact) {
2640 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2651 if (bound.Kind == BoundKind.Lower) {
2652 if (cbound.Kind == BoundKind.Lower) {
2653 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2657 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2665 if (bound.Kind == BoundKind.Upper) {
2666 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2670 throw new NotImplementedException ("variance conversion");
2674 if (cii != candidates_count)
2678 // We already have the best candidate, break if thet are different
2680 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
2682 if (best_candidate != null) {
2684 if (best_candidate == InternalType.Dynamic)
2687 if (bound.Type != InternalType.Dynamic && best_candidate != bound.Type)
2691 best_candidate = bound.Type;
2694 if (best_candidate == null)
2697 unfixed_types[i] = null;
2698 fixed_types[i] = best_candidate;
2703 // Uses inferred or partially infered types to inflate delegate type argument. Returns
2704 // null when type parameter was not yet inferres
2706 public TypeSpec InflateGenericArgument (TypeSpec parameter)
2708 var tp = parameter as TypeParameterSpec;
2711 // Type inference work on generic arguments (MVAR) only
2713 if (!tp.IsMethodOwned)
2716 return fixed_types [tp.DeclaredPosition] ?? parameter;
2719 var gt = parameter as InflatedTypeSpec;
2721 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
2722 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
2723 var inflated = InflateGenericArgument (gt.TypeArguments [ii]);
2724 if (inflated == null)
2727 inflated_targs[ii] = inflated;
2730 return gt.GetDefinition ().MakeGenericType (inflated_targs);
2737 // Tests whether all delegate input arguments are fixed and generic output type
2738 // requires output type inference
2740 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
2742 if (returnType.IsGenericParameter) {
2743 if (IsFixed (returnType))
2745 } else if (TypeManager.IsGenericType (returnType)) {
2746 if (TypeManager.IsDelegateType (returnType)) {
2747 invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType);
2748 return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2751 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
2753 // At least one unfixed return type has to exist
2754 if (AllTypesAreFixed (g_args))
2760 // All generic input arguments have to be fixed
2761 AParametersCollection d_parameters = invoke.Parameters;
2762 return AllTypesAreFixed (d_parameters.Types);
2765 bool IsFixed (TypeSpec type)
2767 return IsUnfixed (type) == -1;
2770 int IsUnfixed (TypeSpec type)
2772 if (!type.IsGenericParameter)
2775 //return unfixed_types[type.GenericParameterPosition] != null;
2776 for (int i = 0; i < unfixed_types.Length; ++i) {
2777 if (unfixed_types [i] == type)
2785 // 26.3.3.9 Lower-bound Inference
2787 public int LowerBoundInference (TypeSpec u, TypeSpec v)
2789 return LowerBoundInference (u, v, false);
2793 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2795 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
2797 // If V is one of the unfixed type arguments
2798 int pos = IsUnfixed (v);
2800 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
2804 // If U is an array type
2805 var u_ac = u as ArrayContainer;
2807 var v_ac = v as ArrayContainer;
2809 if (u_ac.Rank != v_ac.Rank)
2812 if (TypeManager.IsValueType (u_ac.Element))
2813 return ExactInference (u_ac.Element, v_ac.Element);
2815 return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
2821 if (TypeManager.IsGenericType (v)) {
2822 TypeSpec g_v = v.GetDefinition ();
2823 if (g_v != TypeManager.generic_ilist_type &&
2824 g_v != TypeManager.generic_icollection_type &&
2825 g_v != TypeManager.generic_ienumerable_type)
2828 var v_i = TypeManager.GetTypeArguments (v) [0];
2829 if (TypeManager.IsValueType (u_ac.Element))
2830 return ExactInference (u_ac.Element, v_i);
2832 return LowerBoundInference (u_ac.Element, v_i);
2834 } else if (TypeManager.IsGenericType (v)) {
2836 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2837 // such that U is identical to, inherits from (directly or indirectly),
2838 // or implements (directly or indirectly) C<U1..Uk>
2840 var u_candidates = new List<TypeSpec> ();
2841 var open_v = v.MemberDefinition;
2843 for (TypeSpec t = u; t != null; t = t.BaseType) {
2844 if (open_v == t.MemberDefinition)
2845 u_candidates.Add (t);
2847 if (t.Interfaces != null) {
2848 foreach (var iface in t.Interfaces) {
2849 if (open_v == iface.MemberDefinition)
2850 u_candidates.Add (iface);
2855 TypeSpec [] unique_candidate_targs = null;
2856 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
2857 foreach (TypeSpec u_candidate in u_candidates) {
2859 // The unique set of types U1..Uk means that if we have an interface I<T>,
2860 // class U : I<int>, I<long> then no type inference is made when inferring
2861 // type I<T> by applying type U because T could be int or long
2863 if (unique_candidate_targs != null) {
2864 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
2865 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
2866 unique_candidate_targs = second_unique_candidate_targs;
2871 // This should always cause type inference failure
2877 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
2880 if (unique_candidate_targs != null) {
2881 var ga_open_v = open_v.TypeParameters;
2883 for (int i = 0; i < unique_candidate_targs.Length; ++i) {
2884 Variance variance = ga_open_v [i].Variance;
2886 TypeSpec u_i = unique_candidate_targs [i];
2887 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
2888 if (ExactInference (u_i, ga_v [i]) == 0)
2891 bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
2892 (variance == Variance.Covariant && inversed);
2894 if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
2906 // 26.3.3.6 Output Type Inference
2908 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
2910 // If e is a lambda or anonymous method with inferred return type
2911 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2913 TypeSpec rt = ame.InferReturnType (ec, this, t);
2914 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2917 AParametersCollection pd = invoke.Parameters;
2918 return ame.Parameters.Count == pd.Count ? 1 : 0;
2921 TypeSpec rtype = invoke.ReturnType;
2922 return LowerBoundInference (rt, rtype) + 1;
2926 // if E is a method group and T is a delegate type or expression tree type
2927 // return type Tb with parameter types T1..Tk and return type Tb, and overload
2928 // resolution of E with the types T1..Tk yields a single method with return type U,
2929 // then a lower-bound inference is made from U for Tb.
2931 if (e is MethodGroupExpr) {
2932 if (!TypeManager.IsDelegateType (t)) {
2933 if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
2936 t = TypeManager.GetTypeArguments (t)[0];
2939 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2940 TypeSpec rtype = invoke.ReturnType;
2942 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2945 // LAMESPEC: Standard does not specify that all methodgroup arguments
2946 // has to be fixed but it does not specify how to do recursive type inference
2947 // either. We choose the simple option and infer return type only
2948 // if all delegate generic arguments are fixed.
2949 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
2950 for (int i = 0; i < param_types.Length; ++i) {
2951 var inflated = InflateGenericArgument (invoke.Parameters.Types[i]);
2952 if (inflated == null)
2955 param_types[i] = inflated;
2958 MethodGroupExpr mg = (MethodGroupExpr) e;
2959 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
2960 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
2964 return LowerBoundInference (mg.BestCandidate.ReturnType, rtype) + 1;
2968 // if e is an expression with type U, then
2969 // a lower-bound inference is made from U for T
2971 return LowerBoundInference (e.Type, t) * 2;
2974 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
2976 int idx = IsUnfixed (returnType);
2982 if (TypeManager.IsGenericType (returnType)) {
2983 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
2984 RemoveDependentTypes (types, t);
2989 public bool UnfixedVariableExists {
2991 if (unfixed_types == null)
2994 foreach (TypeSpec ut in unfixed_types)