Bug 15572. Lookup KnownTypeCollection element types in MSSimpleNamespace
[mono.git] / mcs / mcs / generic.cs
1 //
2 // generic.cs: Generics support
3 //
4 // Authors: Martin Baulig (martin@ximian.com)
5 //          Miguel de Icaza (miguel@ximian.com)
6 //          Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 //
14
15 using System;
16 using System.Collections.Generic;
17 using System.Text;
18 using System.Linq;
19
20 #if STATIC
21 using MetaType = IKVM.Reflection.Type;
22 using IKVM.Reflection;
23 using IKVM.Reflection.Emit;
24 #else
25 using MetaType = System.Type;
26 using System.Reflection;
27 using System.Reflection.Emit;
28 #endif
29
30 namespace Mono.CSharp {
31         public class VarianceDecl
32         {
33                 public VarianceDecl (Variance variance, Location loc)
34                 {
35                         this.Variance = variance;
36                         this.Location = loc;
37                 }
38
39                 public Variance Variance { get; private set; }
40                 public Location Location { get; private set; }
41
42                 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
43                 {
44                         var tp = t as TypeParameterSpec;
45                         if (tp != null) {
46                                 var v = tp.Variance;
47                                 if (expected == Variance.None && v != expected ||
48                                         expected == Variance.Covariant && v == Variance.Contravariant ||
49                                         expected == Variance.Contravariant && v == Variance.Covariant) {
50                                         ((TypeParameter) tp.MemberDefinition).ErrorInvalidVariance (member, expected);
51                                 }
52
53                                 return expected;
54                         }
55
56                         if (t.TypeArguments.Length > 0) {
57                                 var targs_definition = t.MemberDefinition.TypeParameters;
58                                 TypeSpec[] targs = TypeManager.GetTypeArguments (t);
59                                 for (int i = 0; i < targs.Length; ++i) {
60                                         var v = targs_definition[i].Variance;
61                                         CheckTypeVariance (targs[i], (Variance) ((int) v * (int) expected), member);
62                                 }
63
64                                 return expected;
65                         }
66
67                         var ac = t as ArrayContainer;
68                         if (ac != null)
69                                 return CheckTypeVariance (ac.Element, expected, member);
70
71                         return Variance.None;
72                 }
73         }
74
75         public enum Variance
76         {
77                 //
78                 // Don't add or modify internal values, they are used as -/+ calculation signs
79                 //
80                 None                    = 0,
81                 Covariant               = 1,
82                 Contravariant   = -1
83         }
84
85         [Flags]
86         public enum SpecialConstraint
87         {
88                 None            = 0,
89                 Constructor = 1 << 2,
90                 Class           = 1 << 3,
91                 Struct          = 1 << 4
92         }
93
94         public class SpecialContraintExpr : FullNamedExpression
95         {
96                 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
97                 {
98                         this.loc = loc;
99                         this.Constraint = constraint;
100                 }
101
102                 public SpecialConstraint Constraint { get; private set; }
103
104                 protected override Expression DoResolve (ResolveContext rc)
105                 {
106                         throw new NotImplementedException ();
107                 }
108
109                 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
110                 {
111                         throw new NotImplementedException ();
112                 }
113         }
114
115         //
116         // A set of parsed constraints for a type parameter
117         //
118         public class Constraints
119         {
120                 readonly SimpleMemberName tparam;
121                 readonly List<FullNamedExpression> constraints;
122                 readonly Location loc;
123                 bool resolved;
124                 bool resolving;
125                 
126                 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
127                 {
128                         this.tparam = tparam;
129                         this.constraints = constraints;
130                         this.loc = loc;
131                 }
132
133                 #region Properties
134
135                 public List<FullNamedExpression> TypeExpressions {
136                         get {
137                                 return constraints;
138                         }
139                 }
140
141                 public Location Location {
142                         get {
143                                 return loc;
144                         }
145                 }
146
147                 public SimpleMemberName TypeParameter {
148                         get {
149                                 return tparam;
150                         }
151                 }
152
153                 #endregion
154
155                 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
156                 {
157                         if (spec.HasSpecialClass && bb.IsStruct) {
158                                 context.Module.Compiler.Report.Error (455, loc,
159                                         "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
160                                         spec.Name, "class", bb.GetSignatureForError ());
161
162                                 return false;
163                         }
164
165                         return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
166                 }
167
168                 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
169                 {
170                         if (ba == bb)
171                                 return true;
172
173                         if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
174                                 return true;
175
176                         Error_ConflictingConstraints (context, spec, ba, bb, loc);
177                         return false;
178                 }
179
180                 public static void Error_ConflictingConstraints (IMemberContext context, TypeParameterSpec tp, TypeSpec ba, TypeSpec bb, Location loc)
181                 {
182                         context.Module.Compiler.Report.Error (455, loc,
183                                 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
184                                 tp.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
185                 }
186
187                 public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
188                 {
189                         foreach (var c in constraints) {
190                                 if (c == null)
191                                         continue;
192
193                                 var t = c.Type;
194                                 if (t == null)
195                                         continue;
196
197                                 if (obsoleteCheck) {
198                                         ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
199                                         if (obsolete_attr != null)
200                                                 AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
201                                 }
202
203                                 ConstraintChecker.Check (context, t, c.Location);
204                         }
205                 }
206
207                 //
208                 // Resolve the constraints types with only possible early checks, return
209                 // value `false' is reserved for recursive failure
210                 //
211                 public bool Resolve (IMemberContext context, TypeParameter tp)
212                 {
213                         if (resolved)
214                                 return true;
215
216                         if (resolving)
217                                 return false;
218
219                         resolving = true;
220                         var spec = tp.Type;
221                         List<TypeParameterSpec> tparam_types = null;
222                         bool iface_found = false;
223
224                         spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
225
226                         for (int i = 0; i < constraints.Count; ++i) {
227                                 var constraint = constraints[i];
228
229                                 if (constraint is SpecialContraintExpr) {
230                                         spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
231                                         if (spec.HasSpecialStruct)
232                                                 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
233
234                                         // Set to null as it does not have a type
235                                         constraints[i] = null;
236                                         continue;
237                                 }
238
239                                 var type = constraint.ResolveAsType (context);
240                                 if (type == null)
241                                         continue;
242
243                                 if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
244                                         context.Module.Compiler.Report.Error (1968, constraint.Location,
245                                                 "A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
246                                         continue;
247                                 }
248
249                                 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
250                                         context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
251                                         context.Module.Compiler.Report.Error (703, loc,
252                                                 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
253                                                 type.GetSignatureForError (), context.GetSignatureForError ());
254                                 }
255
256                                 if (type.IsInterface) {
257                                         if (!spec.AddInterface (type)) {
258                                                 context.Module.Compiler.Report.Error (405, constraint.Location,
259                                                         "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
260                                         }
261
262                                         iface_found = true;
263                                         continue;
264                                 }
265
266
267                                 var constraint_tp = type as TypeParameterSpec;
268                                 if (constraint_tp != null) {
269                                         if (tparam_types == null) {
270                                                 tparam_types = new List<TypeParameterSpec> (2);
271                                         } else if (tparam_types.Contains (constraint_tp)) {
272                                                 context.Module.Compiler.Report.Error (405, constraint.Location,
273                                                         "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
274                                                 continue;
275                                         }
276
277                                         //
278                                         // Checks whether each generic method parameter constraint type
279                                         // is valid with respect to T
280                                         //
281                                         if (tp.IsMethodTypeParameter) {
282                                                 VarianceDecl.CheckTypeVariance (type, Variance.Contravariant, context);
283                                         }
284
285                                         var tp_def = constraint_tp.MemberDefinition as TypeParameter;
286                                         if (tp_def != null && !tp_def.ResolveConstraints (context)) {
287                                                 context.Module.Compiler.Report.Error (454, constraint.Location,
288                                                         "Circular constraint dependency involving `{0}' and `{1}'",
289                                                         constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
290                                                 continue;
291                                         }
292
293                                         //
294                                         // Checks whether there are no conflicts between type parameter constraints
295                                         //
296                                         // class Foo<T, U>
297                                         //      where T : A
298                                         //      where U : B, T
299                                         //
300                                         // A and B are not convertible and only 1 class constraint is allowed
301                                         //
302                                         if (constraint_tp.HasTypeConstraint) {
303                                                 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
304                                                         if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
305                                                                 continue;
306                                                 } else {
307                                                         for (int ii = 0; ii < tparam_types.Count; ++ii) {
308                                                                 if (!tparam_types[ii].HasTypeConstraint)
309                                                                         continue;
310
311                                                                 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
312                                                                         break;
313                                                         }
314                                                 }
315                                         }
316
317                                         if (constraint_tp.HasSpecialStruct) {
318                                                 context.Module.Compiler.Report.Error (456, constraint.Location,
319                                                         "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
320                                                         constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
321                                                 continue;
322                                         }
323
324                                         tparam_types.Add (constraint_tp);
325                                         continue;
326                                 }
327
328                                 if (iface_found || spec.HasTypeConstraint) {
329                                         context.Module.Compiler.Report.Error (406, constraint.Location,
330                                                 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
331                                                 type.GetSignatureForError ());
332                                 }
333
334                                 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
335                                         context.Module.Compiler.Report.Error (450, constraint.Location,
336                                                 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
337                                                 type.GetSignatureForError ());
338                                 }
339
340                                 switch (type.BuiltinType) {
341                                 case BuiltinTypeSpec.Type.Array:
342                                 case BuiltinTypeSpec.Type.Delegate:
343                                 case BuiltinTypeSpec.Type.MulticastDelegate:
344                                 case BuiltinTypeSpec.Type.Enum:
345                                 case BuiltinTypeSpec.Type.ValueType:
346                                 case BuiltinTypeSpec.Type.Object:
347                                         context.Module.Compiler.Report.Error (702, constraint.Location,
348                                                 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
349                                         continue;
350                                 case BuiltinTypeSpec.Type.Dynamic:
351                                         context.Module.Compiler.Report.Error (1967, constraint.Location,
352                                                 "A constraint cannot be the dynamic type");
353                                         continue;
354                                 }
355
356                                 if (type.IsSealed || !type.IsClass) {
357                                         context.Module.Compiler.Report.Error (701, loc,
358                                                 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
359                                                 type.GetSignatureForError ());
360                                         continue;
361                                 }
362
363                                 if (type.IsStatic) {
364                                         context.Module.Compiler.Report.Error (717, constraint.Location,
365                                                 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
366                                                 type.GetSignatureForError ());
367                                 }
368
369                                 spec.BaseType = type;
370                         }
371
372                         if (tparam_types != null)
373                                 spec.TypeArguments = tparam_types.ToArray ();
374
375                         resolving = false;
376                         resolved = true;
377                         return true;
378                 }
379
380                 public void VerifyClsCompliance (Report report)
381                 {
382                         foreach (var c in constraints)
383                         {
384                                 if (c == null)
385                                         continue;
386
387                                 if (!c.Type.IsCLSCompliant ()) {
388                                         report.SymbolRelatedToPreviousError (c.Type);
389                                         report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
390                                                 c.Type.GetSignatureForError ());
391                                 }
392                         }
393                 }
394         }
395
396         //
397         // A type parameter for a generic type or generic method definition
398         //
399         public class TypeParameter : MemberCore, ITypeDefinition
400         {
401                 static readonly string[] attribute_target = { "type parameter" };
402                 
403                 Constraints constraints;
404                 GenericTypeParameterBuilder builder;
405                 readonly TypeParameterSpec spec;
406
407                 public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance Variance)
408                         : base (null, name, attrs)
409                 {
410                         this.constraints = constraints;
411                         this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, Variance, null);
412                 }
413
414                 //
415                 // Used by parser
416                 //
417                 public TypeParameter (MemberName name, Attributes attrs, VarianceDecl variance)
418                         : base (null, name, attrs)
419                 {
420                         var var = variance == null ? Variance.None : variance.Variance;
421                         this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, var, null);
422                         this.VarianceDecl = variance;
423                 }
424                 
425                 public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
426                         : base (null, name, attrs)
427                 {
428                         this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
429                                 BaseType = spec.BaseType,
430                                 InterfacesDefined = spec.InterfacesDefined,
431                                 TypeArguments = spec.TypeArguments
432                         };
433                 }
434                 
435                 #region Properties
436
437                 public override AttributeTargets AttributeTargets {
438                         get {
439                                 return AttributeTargets.GenericParameter;
440                         }
441                 }
442
443                 public Constraints Constraints {
444                         get {
445                                 return constraints;
446                         }
447                         set {
448                                 constraints = value;
449                         }
450                 }
451
452                 public IAssemblyDefinition DeclaringAssembly {
453                         get     {
454                                 return Module.DeclaringAssembly;
455                         }
456                 }
457
458                 public override string DocCommentHeader {
459                         get {
460                                 throw new InvalidOperationException (
461                                         "Unexpected attempt to get doc comment from " + this.GetType ());
462                         }
463                 }
464
465                 bool ITypeDefinition.IsComImport {
466                         get {
467                                 return false;
468                         }
469                 }
470
471                 bool ITypeDefinition.IsPartial {
472                         get {
473                                 return false;
474                         }
475                 }
476
477                 public bool IsMethodTypeParameter {
478                         get {
479                                 return spec.IsMethodOwned;
480                         }
481                 }
482
483                 bool ITypeDefinition.IsTypeForwarder {
484                         get {
485                                 return false;
486                         }
487                 }
488
489                 public string Name {
490                         get {
491                                 return MemberName.Name;
492                         }
493                 }
494
495                 public string Namespace {
496                         get {
497                                 return null;
498                         }
499                 }
500
501                 public TypeParameterSpec Type {
502                         get {
503                                 return spec;
504                         }
505                 }
506
507                 public int TypeParametersCount {
508                         get {
509                                 return 0;
510                         }
511                 }
512
513                 public TypeParameterSpec[] TypeParameters {
514                         get {
515                                 return null;
516                         }
517                 }
518
519                 public override string[] ValidAttributeTargets {
520                         get {
521                                 return attribute_target;
522                         }
523                 }
524
525                 public Variance Variance {
526                         get {
527                                 return spec.Variance;
528                         }
529                 }
530
531                 public VarianceDecl VarianceDecl { get; private set; }
532
533                 #endregion
534
535                 //
536                 // This is called for each part of a partial generic type definition.
537                 //
538                 // If partial type parameters constraints are not null and we don't
539                 // already have constraints they become our constraints. If we already
540                 // have constraints, we must check that they're same.
541                 //
542                 public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
543                 {
544                         if (builder == null)
545                                 throw new InvalidOperationException ();
546
547                         var new_constraints = tp.constraints;
548                         if (new_constraints == null)
549                                 return true;
550
551                         // TODO: could create spec only
552                         //tp.Define (null, -1, part.Definition);
553                         tp.spec.DeclaringType = part.Definition;
554                         if (!tp.ResolveConstraints (part))
555                                 return false;
556
557                         if (constraints != null)
558                                 return spec.HasSameConstraintsDefinition (tp.Type);
559
560                         // Copy constraint from resolved part to partial container
561                         spec.SpecialConstraint = tp.spec.SpecialConstraint;
562                         spec.InterfacesDefined = tp.spec.InterfacesDefined;
563                         spec.TypeArguments = tp.spec.TypeArguments;
564                         spec.BaseType = tp.spec.BaseType;
565                         
566                         return true;
567                 }
568
569                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
570                 {
571                         builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
572                 }
573
574                 public void CheckGenericConstraints (bool obsoleteCheck)
575                 {
576                         if (constraints != null)
577                                 constraints.CheckGenericConstraints (this, obsoleteCheck);
578                 }
579
580                 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
581                 {
582                         return new TypeParameter (spec, declaringSpec, MemberName, null);
583                 }
584
585                 public override bool Define ()
586                 {
587                         return true;
588                 }
589
590                 //
591                 // This is the first method which is called during the resolving
592                 // process; we're called immediately after creating the type parameters
593                 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
594                 // MethodBuilder).
595                 //
596                 public void Create (TypeSpec declaringType, TypeContainer parent)
597                 {
598                         if (builder != null)
599                                 throw new InternalErrorException ();
600
601                         // Needed to get compiler reference
602                         this.Parent = parent;
603                         spec.DeclaringType = declaringType;
604                 }
605
606                 public void Define (GenericTypeParameterBuilder type)
607                 {
608                         this.builder = type;
609                         spec.SetMetaInfo (type);
610                 }
611
612                 public void EmitConstraints (GenericTypeParameterBuilder builder)
613                 {
614                         var attr = GenericParameterAttributes.None;
615                         if (spec.Variance == Variance.Contravariant)
616                                 attr |= GenericParameterAttributes.Contravariant;
617                         else if (spec.Variance == Variance.Covariant)
618                                 attr |= GenericParameterAttributes.Covariant;
619
620                         if (spec.HasSpecialClass)
621                                 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
622                         else if (spec.HasSpecialStruct)
623                                 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
624
625                         if (spec.HasSpecialConstructor)
626                                 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
627
628                         if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
629                                 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
630
631                         if (spec.InterfacesDefined != null)
632                                 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
633
634                         if (spec.TypeArguments != null) {
635                                 var meta_constraints = new List<MetaType> (spec.TypeArguments.Length);
636                                 foreach (var c in spec.TypeArguments) {
637                                         //
638                                         // Inflated type parameters can collide with special constraint types, don't
639                                         // emit any such type parameter.
640                                         //
641                                         if (c.BuiltinType == BuiltinTypeSpec.Type.Object || c.BuiltinType == BuiltinTypeSpec.Type.ValueType)
642                                                 continue;
643
644                                         meta_constraints.Add (c.GetMetaInfo ());
645                                 }
646
647                                 builder.SetInterfaceConstraints (meta_constraints.ToArray ());
648                         }
649
650                         builder.SetGenericParameterAttributes (attr);
651                 }
652
653                 public override void Emit ()
654                 {
655                         EmitConstraints (builder);
656
657                         if (OptAttributes != null)
658                                 OptAttributes.Emit ();
659
660                         base.Emit ();
661                 }
662
663                 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
664                 {
665                         Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
666                         string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
667                         string gtype_variance;
668                         switch (expected) {
669                         case Variance.Contravariant: gtype_variance = "contravariantly"; break;
670                         case Variance.Covariant: gtype_variance = "covariantly"; break;
671                         default: gtype_variance = "invariantly"; break;
672                         }
673
674                         Delegate d = mc as Delegate;
675                         string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
676
677                         Report.Error (1961, Location,
678                                 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
679                                         GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
680                 }
681
682                 public TypeSpec GetAttributeCoClass ()
683                 {
684                         return null;
685                 }
686
687                 public string GetAttributeDefaultMember ()
688                 {
689                         throw new NotSupportedException ();
690                 }
691
692                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
693                 {
694                         throw new NotSupportedException ();
695                 }
696
697                 public override string GetSignatureForDocumentation ()
698                 {
699                         throw new NotImplementedException ();
700                 }
701
702                 public override string GetSignatureForError ()
703                 {
704                         return MemberName.Name;
705                 }
706
707                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
708                 {
709                         return spec.MemberDefinition.DeclaringAssembly == assembly;
710                 }
711
712                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
713                 {
714                         throw new NotSupportedException ("Not supported for compiled definition");
715                 }
716
717                 //
718                 // Resolves all type parameter constraints
719                 //
720                 public bool ResolveConstraints (IMemberContext context)
721                 {
722                         if (constraints != null)
723                                 return constraints.Resolve (context, this);
724
725                         if (spec.BaseType == null)
726                                 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
727
728                         return true;
729                 }
730
731                 public override bool IsClsComplianceRequired ()
732                 {
733                         return false;
734                 }
735
736                 public new void VerifyClsCompliance ()
737                 {
738                         if (constraints != null)
739                                 constraints.VerifyClsCompliance (Report);
740                 }
741
742                 public void WarningParentNameConflict (TypeParameter conflict)
743                 {
744                         conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
745                         conflict.Report.Warning (693, 3, Location,
746                                 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
747                                 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
748                 }
749         }
750
751         [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
752         public class TypeParameterSpec : TypeSpec
753         {
754                 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
755
756                 Variance variance;
757                 SpecialConstraint spec;
758                 int tp_pos;
759                 TypeSpec[] targs;
760                 TypeSpec[] ifaces_defined;
761
762                 //
763                 // Creates type owned type parameter
764                 //
765                 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
766                         : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
767                 {
768                         this.variance = variance;
769                         this.spec = spec;
770                         state &= ~StateFlags.Obsolete_Undetected;
771                         tp_pos = index;
772                 }
773
774                 //
775                 // Creates method owned type parameter
776                 //
777                 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
778                         : this (null, index, definition, spec, variance, info)
779                 {
780                 }
781
782                 #region Properties
783
784                 public int DeclaredPosition {
785                         get {
786                                 return tp_pos;
787                         }
788                         set {
789                                 tp_pos = value;
790                         }
791                 }
792
793                 public bool HasSpecialConstructor {
794                         get {
795                                 return (spec & SpecialConstraint.Constructor) != 0;
796                         }
797                 }
798
799                 public bool HasSpecialClass {
800                         get {
801                                 return (spec & SpecialConstraint.Class) != 0;
802                         }
803                 }
804
805                 public bool HasSpecialStruct {
806                         get {
807                                 return (spec & SpecialConstraint.Struct) != 0;
808                         }
809                 }
810
811                 public bool HasAnyTypeConstraint {
812                         get {
813                                 return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
814                         }
815                 }
816
817                 public bool HasTypeConstraint {
818                         get {
819                                 var bt = BaseType.BuiltinType;
820                                 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
821                         }
822                 }
823
824                 public override IList<TypeSpec> Interfaces {
825                         get {
826                                 if ((state & StateFlags.InterfacesExpanded) == 0) {
827                                         if (ifaces != null) {
828                                                 if (ifaces_defined == null)
829                                                         ifaces_defined = ifaces.ToArray ();
830
831                                                 for (int i = 0; i < ifaces_defined.Length; ++i ) {
832                                                         var iface_type = ifaces_defined[i];
833                                                         var td = iface_type.MemberDefinition as TypeDefinition;
834                                                         if (td != null)
835                                                                 td.DoExpandBaseInterfaces ();
836
837                                                         if (iface_type.Interfaces != null) {
838                                                                 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
839                                                                         var ii_iface_type = iface_type.Interfaces [ii];
840                                                                         AddInterface (ii_iface_type);
841                                                                 }
842                                                         }
843                                                 }
844                                         } else if (ifaces_defined == null) {
845                                                 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
846                                         }
847
848                                         //
849                                         // Include all base type interfaces too, see ImportTypeBase for details
850                                         //
851                                         if (BaseType != null) {
852                                                 var td = BaseType.MemberDefinition as TypeDefinition;
853                                                 if (td != null)
854                                                         td.DoExpandBaseInterfaces ();
855
856                                                 if (BaseType.Interfaces != null) {
857                                                         foreach (var iface in BaseType.Interfaces) {
858                                                                 AddInterface (iface);
859                                                         }
860                                                 }
861                                         }
862
863                                         state |= StateFlags.InterfacesExpanded;
864                                 }
865
866                                 return ifaces;
867                         }
868                 }
869
870                 //
871                 // Unexpanded interfaces list
872                 //
873                 public TypeSpec[] InterfacesDefined {
874                         get {
875                                 if (ifaces_defined == null) {
876                                         ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
877                                 }
878
879                                 return ifaces_defined.Length == 0 ? null : ifaces_defined;
880                         }
881                         set {
882                                 ifaces_defined = value;
883                                 if (value != null && value.Length != 0)
884                                         ifaces = new List<TypeSpec> (value);
885                         }
886                 }
887
888                 public bool IsConstrained {
889                         get {
890                                 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
891                         }
892                 }
893
894                 //
895                 // Returns whether the type parameter is known to be a reference type
896                 //
897                 public new bool IsReferenceType {
898                         get {
899                                 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
900                                         return (spec & SpecialConstraint.Class) != 0;
901
902                                 //
903                                 // Full check is needed (see IsValueType for details)
904                                 //
905                                 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
906                                         return true;
907
908                                 if (targs != null) {
909                                         foreach (var ta in targs) {
910                                                 //
911                                                 // Secondary special constraints are ignored (I am not sure why)
912                                                 //
913                                                 var tp = ta as TypeParameterSpec;
914                                                 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
915                                                         continue;
916
917                                                 if (TypeSpec.IsReferenceType (ta))
918                                                         return true;
919                                         }
920                                 }
921
922                                 return false;
923                         }
924                 }
925
926                 //
927                 // Returns whether the type parameter is known to be a value type
928                 //
929                 public new bool IsValueType {
930                         get {
931                                 //
932                                 // Even if structs/enums cannot be used directly as constraints
933                                 // they can apear as constraint type when inheriting base constraint
934                                 // which has dependant type parameter constraint which has been
935                                 // inflated using value type
936                                 //
937                                 // class A : B<int> { override void Foo<U> () {} }
938                                 // class B<T> { virtual void Foo<U> () where U : T {} }
939                                 //
940                                 if (HasSpecialStruct)
941                                         return true;
942
943                                 if (targs != null) {
944                                         foreach (var ta in targs) {
945                                                 if (TypeSpec.IsValueType (ta))
946                                                         return true;
947                                         }
948                                 }
949
950                                 return false;
951                         }
952                 }
953
954                 public override string Name {
955                         get {
956                                 return definition.Name;
957                         }
958                 }
959
960                 public bool IsMethodOwned {
961                         get {
962                                 return DeclaringType == null;
963                         }
964                 }
965
966                 public SpecialConstraint SpecialConstraint {
967                         get {
968                                 return spec;
969                         }
970                         set {
971                                 spec = value;
972                         }
973                 }
974
975                 //
976                 // Types used to inflate the generic type
977                 //
978                 public new TypeSpec[] TypeArguments {
979                         get {
980                                 return targs;
981                         }
982                         set {
983                                 targs = value;
984                         }
985                 }
986
987                 public Variance Variance {
988                         get {
989                                 return variance;
990                         }
991                 }
992
993                 #endregion
994
995                 public string DisplayDebugInfo ()
996                 {
997                         var s = GetSignatureForError ();
998                         return IsMethodOwned ? s + "!!" : s + "!";
999                 }
1000
1001                 //
1002                 // Finds effective base class. The effective base class is always a class-type
1003                 //
1004                 public TypeSpec GetEffectiveBase ()
1005                 {
1006                         if (HasSpecialStruct)
1007                                 return BaseType;
1008
1009                         //
1010                         // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
1011                         //
1012                         if (BaseType != null && targs == null) {
1013                                 //
1014                                 // 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.
1015                                 // 
1016                                 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
1017                                 //
1018                                 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
1019                                 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
1020                                 //
1021                                 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
1022                         }
1023
1024                         var types = targs;
1025                         if (HasTypeConstraint) {
1026                                 Array.Resize (ref types, types.Length + 1);
1027
1028                                 for (int i = 0; i < types.Length - 1; ++i) {
1029                                         types[i] = types[i].BaseType;
1030                                 }
1031
1032                                 types[types.Length - 1] = BaseType;
1033                         } else {
1034                                 types = types.Select (l => l.BaseType).ToArray ();
1035                         }
1036
1037                         if (types != null)
1038                                 return Convert.FindMostEncompassedType (types);
1039
1040                         return BaseType;
1041                 }
1042
1043                 public override string GetSignatureForDocumentation ()
1044                 {
1045                         var prefix = IsMethodOwned ? "``" : "`";
1046                         return prefix + DeclaredPosition;
1047                 }
1048
1049                 public override string GetSignatureForError ()
1050                 {
1051                         return Name;
1052                 }
1053
1054                 //
1055                 // Constraints have to match by definition but not position, used by
1056                 // partial classes or methods
1057                 //
1058                 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
1059                 {
1060                         if (spec != other.spec)
1061                                 return false;
1062
1063                         if (BaseType != other.BaseType)
1064                                 return false;
1065
1066                         if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
1067                                 return false;
1068
1069                         if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
1070                                 return false;
1071
1072                         return true;
1073                 }
1074
1075                 //
1076                 // Constraints have to match by using same set of types, used by
1077                 // implicit interface implementation
1078                 //
1079                 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
1080                 {
1081                         if (spec != other.spec)
1082                                 return false;
1083
1084                         //
1085                         // It can be same base type or inflated type parameter
1086                         //
1087                         // interface I<T> { void Foo<U> where U : T; }
1088                         // class A : I<int> { void Foo<X> where X : int {} }
1089                         //
1090                         bool found;
1091                         if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
1092                                 if (other.targs == null)
1093                                         return false;
1094
1095                                 found = false;
1096                                 foreach (var otarg in other.targs) {
1097                                         if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1098                                                 found = true;
1099                                                 break;
1100                                         }
1101                                 }
1102
1103                                 if (!found)
1104                                         return false;
1105                         }
1106
1107                         // Check interfaces implementation -> definition
1108                         if (InterfacesDefined != null) {
1109                                 //
1110                                 // Iterate over inflated interfaces
1111                                 //
1112                                 foreach (var iface in Interfaces) {
1113                                         found = false;
1114                                         if (other.InterfacesDefined != null) {
1115                                                 foreach (var oiface in other.Interfaces) {
1116                                                         if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1117                                                                 found = true;
1118                                                                 break;
1119                                                         }
1120                                                 }
1121                                         }
1122
1123                                         if (found)
1124                                                 continue;
1125
1126                                         if (other.targs != null) {
1127                                                 foreach (var otarg in other.targs) {
1128                                                         if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1129                                                                 found = true;
1130                                                                 break;
1131                                                         }
1132                                                 }
1133                                         }
1134
1135                                         if (!found)
1136                                                 return false;
1137                                 }
1138                         }
1139
1140                         // Check interfaces implementation <- definition
1141                         if (other.InterfacesDefined != null) {
1142                                 if (InterfacesDefined == null)
1143                                         return false;
1144
1145                                 //
1146                                 // Iterate over inflated interfaces
1147                                 //
1148                                 foreach (var oiface in other.Interfaces) {
1149                                         found = false;
1150                                         foreach (var iface in Interfaces) {
1151                                                 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1152                                                         found = true;
1153                                                         break;
1154                                                 }
1155                                         }
1156
1157                                         if (!found)
1158                                                 return false;
1159                                 }
1160                         }
1161
1162                         // Check type parameters implementation -> definition
1163                         if (targs != null) {
1164                                 if (other.targs == null)
1165                                         return false;
1166
1167                                 foreach (var targ in targs) {
1168                                         found = false;
1169                                         foreach (var otarg in other.targs) {
1170                                                 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1171                                                         found = true;
1172                                                         break;
1173                                                 }
1174                                         }
1175
1176                                         if (!found)
1177                                                 return false;
1178                                 }
1179                         }
1180
1181                         // Check type parameters implementation <- definition
1182                         if (other.targs != null) {
1183                                 foreach (var otarg in other.targs) {
1184                                         // Ignore inflated type arguments, were checked above
1185                                         if (!otarg.IsGenericParameter)
1186                                                 continue;
1187
1188                                         if (targs == null)
1189                                                 return false;
1190
1191                                         found = false;
1192                                         foreach (var targ in targs) {
1193                                                 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1194                                                         found = true;
1195                                                         break;
1196                                                 }
1197                                         }
1198
1199                                         if (!found)
1200                                                 return false;
1201                                 }                               
1202                         }
1203
1204                         return true;
1205                 }
1206
1207                 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1208                 {
1209                         return InflateConstraints (tparams, l => l, inflator);
1210                 }
1211
1212                 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1213                 {
1214                         TypeParameterSpec[] constraints = null;
1215                         TypeParameterInflator? inflator = null;
1216
1217                         for (int i = 0; i < tparams.Length; ++i) {
1218                                 var tp = tparams[i];
1219                                 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1220                                         if (constraints == null) {
1221                                                 constraints = new TypeParameterSpec[tparams.Length];
1222                                                 Array.Copy (tparams, constraints, constraints.Length);
1223                                         }
1224
1225                                         //
1226                                         // Using a factory to avoid possibly expensive inflator build up
1227                                         //
1228                                         if (inflator == null)
1229                                                 inflator = inflatorFactory (arg);
1230
1231                                         constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1232                                 }
1233                         }
1234
1235                         if (constraints == null)
1236                                 constraints = tparams;
1237
1238                         return constraints;
1239                 }
1240
1241                 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1242                 {
1243                         tps.BaseType = inflator.Inflate (BaseType);
1244
1245                         var defined = InterfacesDefined;
1246                         if (defined != null) {
1247                                 tps.ifaces_defined = new TypeSpec[defined.Length];
1248                                 for (int i = 0; i < defined.Length; ++i)
1249                                         tps.ifaces_defined [i] = inflator.Inflate (defined[i]);
1250                         } else if (ifaces_defined == TypeSpec.EmptyTypes) {
1251                                 tps.ifaces_defined = TypeSpec.EmptyTypes;
1252                         }
1253
1254                         var ifaces = Interfaces;
1255                         if (ifaces != null) {
1256                                 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1257                                 for (int i = 0; i < ifaces.Count; ++i)
1258                                         tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1259                                 tps.state |= StateFlags.InterfacesExpanded;
1260                         }
1261
1262                         if (targs != null) {
1263                                 tps.targs = new TypeSpec[targs.Length];
1264                                 for (int i = 0; i < targs.Length; ++i)
1265                                         tps.targs[i] = inflator.Inflate (targs[i]);
1266                         }
1267                 }
1268
1269                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1270                 {
1271                         var tps = (TypeParameterSpec) MemberwiseClone ();
1272 #if DEBUG
1273                         tps.ID += 1000000;
1274 #endif
1275
1276                         InflateConstraints (inflator, tps);
1277                         return tps;
1278                 }
1279
1280                 //
1281                 // Populates type parameter members using type parameter constraints
1282                 // The trick here is to be called late enough but not too late to
1283                 // populate member cache with all members from other types
1284                 //
1285                 protected override void InitializeMemberCache (bool onlyTypes)
1286                 {
1287                         cache = new MemberCache ();
1288
1289                         //
1290                         // For a type parameter the membercache is the union of the sets of members of the types
1291                         // specified as a primary constraint or secondary constraint
1292                         //
1293                         if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1294                                 cache.AddBaseType (BaseType);
1295
1296                         if (InterfacesDefined != null) {
1297                                 foreach (var iface_type in InterfacesDefined) {
1298                                         cache.AddInterface (iface_type);
1299                                 }
1300                         }
1301
1302                         if (targs != null) {
1303                                 foreach (var ta in targs) {
1304                                         var b_type = ta.BaseType;
1305                                         if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1306                                                 cache.AddBaseType (b_type);
1307
1308                                         var tps = ta as TypeParameterSpec;
1309                                         var ifaces = tps != null ? tps.InterfacesDefined : ta.Interfaces;
1310
1311                                         if (ifaces != null) {
1312                                                 foreach (var iface_type in ifaces) {
1313                                                         cache.AddInterface (iface_type);
1314                                                 }
1315                                         }
1316                                 }
1317                         }
1318                 }
1319
1320                 public bool IsConvertibleToInterface (TypeSpec iface)
1321                 {
1322                         if (Interfaces != null) {
1323                                 foreach (var t in Interfaces) {
1324                                         if (t == iface)
1325                                                 return true;
1326                                 }
1327                         }
1328
1329                         if (TypeArguments != null) {
1330                                 foreach (var t in TypeArguments) {
1331                                         if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1332                                                 return true;
1333                                 }
1334                         }
1335
1336                         return false;
1337                 }
1338
1339                 public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
1340                 {
1341                         var tps = md.TypeParameters;
1342                         for (int i = 0; i < md.TypeParametersCount; ++i) {
1343                                 if (tps[i].HasAnyTypeConstraint) {
1344                                         return true;
1345                                 }
1346                         }
1347
1348                         return false;
1349                 }
1350
1351                 public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
1352                 {
1353                         var tps = md.TypeParameters;
1354                         for (int i = 0; i < md.TypeParametersCount; ++i) {
1355                                 if (tps[i].IsConstrained) {
1356                                         return true;
1357                                 }
1358                         }
1359
1360                         return false;
1361                 }
1362
1363                 public bool HasDependencyOn (TypeSpec type)
1364                 {
1365                         if (TypeArguments != null) {
1366                                 foreach (var targ in TypeArguments) {
1367                                         if (TypeSpecComparer.Override.IsEqual (targ, type))
1368                                                 return true;
1369
1370                                         var tps = targ as TypeParameterSpec;
1371                                         if (tps != null && tps.HasDependencyOn (type))
1372                                                 return true;
1373                                 }
1374                         }
1375
1376                         return false;
1377                 }
1378
1379                 public override TypeSpec Mutate (TypeParameterMutator mutator)
1380                 {
1381                         return mutator.Mutate (this);
1382                 }
1383         }
1384
1385         public struct TypeParameterInflator
1386         {
1387                 readonly TypeSpec type;
1388                 readonly TypeParameterSpec[] tparams;
1389                 readonly TypeSpec[] targs;
1390                 readonly IModuleContext context;
1391
1392                 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1393                         : this (nested.context, type, nested.tparams, nested.targs)
1394                 {
1395                 }
1396
1397                 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1398                 {
1399                         if (tparams.Length != targs.Length)
1400                                 throw new ArgumentException ("Invalid arguments");
1401
1402                         this.context = context;
1403                         this.tparams = tparams;
1404                         this.targs = targs;
1405                         this.type = type;
1406                 }
1407
1408                 #region Properties
1409
1410                 public IModuleContext Context {
1411                         get {
1412                                 return context;
1413                         }
1414                 }
1415
1416                 public TypeSpec TypeInstance {
1417                         get {
1418                                 return type;
1419                         }
1420                 }
1421
1422                 //
1423                 // Type parameters to inflate
1424                 //
1425                 public TypeParameterSpec[] TypeParameters {
1426                         get {
1427                                 return tparams;
1428                         }
1429                 }
1430
1431                 #endregion
1432
1433                 public TypeSpec Inflate (TypeSpec type)
1434                 {
1435                         var tp = type as TypeParameterSpec;
1436                         if (tp != null)
1437                                 return Inflate (tp);
1438
1439                         var ac = type as ArrayContainer;
1440                         if (ac != null) {
1441                                 var et = Inflate (ac.Element);
1442                                 if (et != ac.Element)
1443                                         return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1444
1445                                 return ac;
1446                         }
1447
1448                         if (type.Kind == MemberKind.MissingType)
1449                                 return type;
1450
1451                         //
1452                         // When inflating a nested type, inflate its parent first
1453                         // in case it's using same type parameters (was inflated within the type)
1454                         //
1455                         TypeSpec[] targs;
1456                         int i = 0;
1457                         if (type.IsNested) {
1458                                 var parent = Inflate (type.DeclaringType);
1459
1460                                 //
1461                                 // Keep the inflated type arguments
1462                                 // 
1463                                 targs = type.TypeArguments;
1464
1465                                 //
1466                                 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1467                                 // because the import cache helps us to catch it. However, that means we have to look at
1468                                 // type definition to get type argument (they are in fact type parameter in this case)
1469                                 //
1470                                 if (targs.Length == 0 && type.Arity > 0)
1471                                         targs = type.MemberDefinition.TypeParameters;
1472
1473                                 //
1474                                 // Parent was inflated, find the same type on inflated type
1475                                 // to use same cache for nested types on same generic parent
1476                                 //
1477                                 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1478
1479                                 //
1480                                 // Handle the tricky case where parent shares local type arguments
1481                                 // which means inflating inflated type
1482                                 //
1483                                 // class Test<T> {
1484                                 //              public static Nested<T> Foo () { return null; }
1485                                 //
1486                                 //              public class Nested<U> {}
1487                                 //      }
1488                                 //
1489                                 //  return type of Test<string>.Foo() has to be Test<string>.Nested<string> 
1490                                 //
1491                                 if (targs.Length > 0) {
1492                                         var inflated_targs = new TypeSpec[targs.Length];
1493                                         for (; i < targs.Length; ++i)
1494                                                 inflated_targs[i] = Inflate (targs[i]);
1495
1496                                         type = type.MakeGenericType (context, inflated_targs);
1497                                 }
1498
1499                                 return type;
1500                         }
1501
1502                         // Nothing to do for non-generic type
1503                         if (type.Arity == 0)
1504                                 return type;
1505
1506                         targs = new TypeSpec[type.Arity];
1507
1508                         //
1509                         // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1510                         //
1511                         if (type is InflatedTypeSpec) {
1512                                 for (; i < targs.Length; ++i)
1513                                         targs[i] = Inflate (type.TypeArguments[i]);
1514
1515                                 type = type.GetDefinition ();
1516                         } else {
1517                                 //
1518                                 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1519                                 //
1520                                 var args = type.MemberDefinition.TypeParameters;
1521                                 foreach (var ds_tp in args)
1522                                         targs[i++] = Inflate (ds_tp);
1523                         }
1524
1525                         return type.MakeGenericType (context, targs);
1526                 }
1527
1528                 public TypeSpec Inflate (TypeParameterSpec tp)
1529                 {
1530                         for (int i = 0; i < tparams.Length; ++i)
1531                                 if (tparams [i] == tp)
1532                                         return targs[i];
1533
1534                         // This can happen when inflating nested types
1535                         // without type arguments specified
1536                         return tp;
1537                 }
1538         }
1539
1540         //
1541         // Before emitting any code we have to change all MVAR references to VAR
1542         // when the method is of generic type and has hoisted variables
1543         //
1544         public class TypeParameterMutator
1545         {
1546                 readonly TypeParameters mvar;
1547                 readonly TypeParameters var;
1548                 readonly TypeParameterSpec[] src;
1549                 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1550
1551                 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1552                 {
1553                         if (mvar.Count != var.Count)
1554                                 throw new ArgumentException ();
1555
1556                         this.mvar = mvar;
1557                         this.var = var;
1558                 }
1559
1560                 public TypeParameterMutator (TypeParameterSpec[] srcVar, TypeParameters destVar)
1561                 {
1562                         if (srcVar.Length != destVar.Count)
1563                                 throw new ArgumentException ();
1564
1565                         this.src = srcVar;
1566                         this.var = destVar;
1567                 }
1568
1569                 #region Properties
1570
1571                 public TypeParameters MethodTypeParameters {
1572                         get {
1573                                 return mvar;
1574                         }
1575                 }
1576
1577                 #endregion
1578
1579                 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1580                 {
1581                         if (type is InflatedTypeSpec) {
1582                                 if (type.DeclaringType == null)
1583                                         return type.GetDefinition ();
1584
1585                                 var parent = GetMemberDeclaringType (type.DeclaringType);
1586                                 type = MemberCache.GetMember<TypeSpec> (parent, type);
1587                         }
1588
1589                         return type;
1590                 }
1591
1592                 public TypeSpec Mutate (TypeSpec ts)
1593                 {
1594                         TypeSpec value;
1595                         if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1596                                 return value;
1597
1598                         value = ts.Mutate (this);
1599                         if (mutated_typespec == null)
1600                                 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1601
1602                         mutated_typespec.Add (ts, value);
1603                         return value;
1604                 }
1605
1606                 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1607                 {
1608                         if (mvar != null) {
1609                                 for (int i = 0; i < mvar.Count; ++i) {
1610                                         if (mvar[i].Type == tp)
1611                                                 return var[i].Type;
1612                                 }
1613                         } else {
1614                                 for (int i = 0; i < src.Length; ++i) {
1615                                         if (src[i] == tp)
1616                                                 return var[i].Type;
1617                                 }
1618                         }
1619
1620                         return tp;
1621                 }
1622
1623                 public TypeSpec[] Mutate (TypeSpec[] targs)
1624                 {
1625                         TypeSpec[] mutated = new TypeSpec[targs.Length];
1626                         bool changed = false;
1627                         for (int i = 0; i < targs.Length; ++i) {
1628                                 mutated[i] = Mutate (targs[i]);
1629                                 changed |= targs[i] != mutated[i];
1630                         }
1631
1632                         return changed ? mutated : targs;
1633                 }
1634         }
1635
1636         /// <summary>
1637         ///   A TypeExpr which already resolved to a type parameter.
1638         /// </summary>
1639         public class TypeParameterExpr : TypeExpression
1640         {
1641                 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1642                         : base (type_parameter.Type, loc)
1643                 {
1644                         this.eclass = ExprClass.TypeParameter;
1645                 }
1646         }
1647
1648         public class InflatedTypeSpec : TypeSpec
1649         {
1650                 TypeSpec[] targs;
1651                 TypeParameterSpec[] constraints;
1652                 readonly TypeSpec open_type;
1653                 readonly IModuleContext context;
1654
1655                 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1656                         : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1657                 {
1658                         if (targs == null)
1659                                 throw new ArgumentNullException ("targs");
1660
1661                         this.state &= ~SharedStateFlags;
1662                         this.state |= (openType.state & SharedStateFlags);
1663
1664                         this.context = context;
1665                         this.open_type = openType;
1666                         this.targs = targs;
1667
1668                         foreach (var arg in targs) {
1669                                 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1670                                         state |= StateFlags.HasDynamicElement;
1671                                         break;
1672                                 }
1673                         }
1674
1675                         if (open_type.Kind == MemberKind.MissingType)
1676                                 MemberCache = MemberCache.Empty;
1677
1678                         if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1679                                 state |= StateFlags.ConstraintsChecked;
1680                 }
1681
1682                 #region Properties
1683
1684                 public override TypeSpec BaseType {
1685                         get {
1686                                 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1687                                         InitializeMemberCache (true);
1688
1689                                 return base.BaseType;
1690                         }
1691                 }
1692
1693                 //
1694                 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1695                 //
1696                 public TypeParameterSpec[] Constraints {
1697                         get {
1698                                 if (constraints == null) {
1699                                         constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1700                                 }
1701
1702                                 return constraints;
1703                         }
1704                 }
1705
1706                 //
1707                 // Used to cache expensive constraints validation on constructed types
1708                 //
1709                 public bool HasConstraintsChecked {
1710                         get {
1711                                 return (state & StateFlags.ConstraintsChecked) != 0;
1712                         }
1713                         set {
1714                                 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1715                         }
1716                 }
1717
1718                 public override IList<TypeSpec> Interfaces {
1719                         get {
1720                                 if (cache == null)
1721                                         InitializeMemberCache (true);
1722
1723                                 return base.Interfaces;
1724                         }
1725                 }
1726
1727                 public override bool IsExpressionTreeType {
1728                         get {
1729                                 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1730                         }
1731                 }
1732
1733                 public override bool IsArrayGenericInterface {
1734                         get {
1735                                 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1736                         }
1737                 }
1738
1739                 public override bool IsGenericTask {
1740                         get {
1741                                 return (open_type.state & StateFlags.GenericTask) != 0;
1742                         }
1743                 }
1744
1745                 public override bool IsNullableType {
1746                         get {
1747                                 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1748                         }
1749                 }
1750
1751                 //
1752                 // Types used to inflate the generic  type
1753                 //
1754                 public override TypeSpec[] TypeArguments {
1755                         get {
1756                                 return targs;
1757                         }
1758                 }
1759
1760                 #endregion
1761
1762                 public override bool AddInterface (TypeSpec iface)
1763                 {
1764                         var inflator = CreateLocalInflator (context);
1765                         iface = inflator.Inflate (iface);
1766                         if (iface == null)
1767                                 return false;
1768
1769                         return base.AddInterface (iface);
1770                 }
1771
1772                 public static bool ContainsTypeParameter (TypeSpec type)
1773                 {
1774                         if (type.Kind == MemberKind.TypeParameter)
1775                                 return true;
1776
1777                         var element_container = type as ElementTypeSpec;
1778                         if (element_container != null)
1779                                 return ContainsTypeParameter (element_container.Element);
1780
1781                         foreach (var t in type.TypeArguments) {
1782                                 if (ContainsTypeParameter (t)) {
1783                                         return true;
1784                                 }
1785                         }
1786
1787                         return false;
1788                 }
1789
1790                 public TypeParameterInflator CreateLocalInflator (IModuleContext context)
1791                 {
1792                         TypeParameterSpec[] tparams_full;
1793                         TypeSpec[] targs_full = targs;
1794                         if (IsNested) {
1795                                 //
1796                                 // Special case is needed when we are inflating an open type (nested type definition)
1797                                 // on inflated parent. Consider following case
1798                                 //
1799                                 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1800                                 //
1801                                 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1802                                 //
1803                                 List<TypeSpec> merged_targs = null;
1804                                 List<TypeParameterSpec> merged_tparams = null;
1805
1806                                 var type = DeclaringType;
1807
1808                                 do {
1809                                         if (type.TypeArguments.Length > 0) {
1810                                                 if (merged_targs == null) {
1811                                                         merged_targs = new List<TypeSpec> ();
1812                                                         merged_tparams = new List<TypeParameterSpec> ();
1813                                                         if (targs.Length > 0) {
1814                                                                 merged_targs.AddRange (targs);
1815                                                                 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1816                                                         }
1817                                                 }
1818                                                 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1819                                                 merged_targs.AddRange (type.TypeArguments);
1820                                         }
1821                                         type = type.DeclaringType;
1822                                 } while (type != null);
1823
1824                                 if (merged_targs != null) {
1825                                         // Type arguments are not in the right order but it should not matter in this case
1826                                         targs_full = merged_targs.ToArray ();
1827                                         tparams_full = merged_tparams.ToArray ();
1828                                 } else if (targs.Length == 0) {
1829                                         tparams_full = TypeParameterSpec.EmptyTypes;
1830                                 } else {
1831                                         tparams_full = open_type.MemberDefinition.TypeParameters;
1832                                 }
1833                         } else if (targs.Length == 0) {
1834                                 tparams_full = TypeParameterSpec.EmptyTypes;
1835                         } else {
1836                                 tparams_full = open_type.MemberDefinition.TypeParameters;
1837                         }
1838
1839                         return new TypeParameterInflator (context, this, tparams_full, targs_full);
1840                 }
1841
1842                 MetaType CreateMetaInfo ()
1843                 {
1844                         //
1845                         // Converts nested type arguments into right order
1846                         // Foo<string, bool>.Bar<int> => string, bool, int
1847                         //
1848                         var all = new List<MetaType> ();
1849                         TypeSpec type = this;
1850                         TypeSpec definition = type;
1851                         do {
1852                                 if (type.GetDefinition().IsGeneric) {
1853                                         all.InsertRange (0,
1854                                                 type.TypeArguments != TypeSpec.EmptyTypes ?
1855                                                 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1856                                                 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1857                                 }
1858
1859                                 definition = definition.GetDefinition ();
1860                                 type = type.DeclaringType;
1861                         } while (type != null);
1862
1863                         return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1864                 }
1865
1866                 public override ObsoleteAttribute GetAttributeObsolete ()
1867                 {
1868                         return open_type.GetAttributeObsolete ();
1869                 }
1870
1871                 protected override bool IsNotCLSCompliant (out bool attrValue)
1872                 {
1873                         if (base.IsNotCLSCompliant (out attrValue))
1874                                 return true;
1875
1876                         foreach (var ta in TypeArguments) {
1877                                 if (ta.MemberDefinition.CLSAttributeValue == false)
1878                                         return true;
1879                         }
1880
1881                         return false;
1882                 }
1883
1884                 public override TypeSpec GetDefinition ()
1885                 {
1886                         return open_type;
1887                 }
1888
1889                 public override MetaType GetMetaInfo ()
1890                 {
1891                         if (info == null)
1892                                 info = CreateMetaInfo ();
1893
1894                         return info;
1895                 }
1896
1897                 public override string GetSignatureForError ()
1898                 {
1899                         if (IsNullableType)
1900                                 return targs[0].GetSignatureForError () + "?";
1901
1902                         return base.GetSignatureForError ();
1903                 }
1904
1905                 protected override string GetTypeNameSignature ()
1906                 {
1907                         if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1908                                 return null;
1909
1910                         return "<" + TypeManager.CSharpName (targs) + ">";
1911                 }
1912
1913                 public bool HasDynamicArgument ()
1914                 {
1915                         for (int i = 0; i < targs.Length; ++i) {
1916                                 var item = targs[i];
1917
1918                                 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1919                                         return true;
1920
1921                                 if (item is InflatedTypeSpec) {
1922                                         if (((InflatedTypeSpec) item).HasDynamicArgument ())
1923                                                 return true;
1924
1925                                         continue;
1926                                 }
1927
1928                                 if (item.IsArray) {
1929                                         while (item.IsArray) {
1930                                                 item = ((ArrayContainer) item).Element;
1931                                         }
1932
1933                                         if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1934                                                 return true;
1935                                 }
1936                         }
1937
1938                         return false;
1939                 }
1940
1941                 protected override void InitializeMemberCache (bool onlyTypes)
1942                 {
1943                         if (cache == null) {
1944                                 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1945
1946                                 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1947                                 // for imported type parameter constraints referencing nested type of this declaration
1948                                 if (cache == null)
1949                                         cache = new MemberCache (open_cache);
1950                         }
1951
1952                         var inflator = CreateLocalInflator (context);
1953
1954                         //
1955                         // Two stage inflate due to possible nested types recursive
1956                         // references
1957                         //
1958                         // class A<T> {
1959                         //    B b;
1960                         //    class B {
1961                         //      T Value;
1962                         //    }
1963                         // }
1964                         //
1965                         // When resolving type of `b' members of `B' cannot be 
1966                         // inflated because are not yet available in membercache
1967                         //
1968                         if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1969                                 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1970
1971                                 //
1972                                 // Inflate any implemented interfaces
1973                                 //
1974                                 if (open_type.Interfaces != null) {
1975                                         ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1976                                         foreach (var iface in open_type.Interfaces) {
1977                                                 var iface_inflated = inflator.Inflate (iface);
1978                                                 if (iface_inflated == null)
1979                                                         continue;
1980
1981                                                 base.AddInterface (iface_inflated);
1982                                         }
1983                                 }
1984
1985                                 //
1986                                 // Handles the tricky case of recursive nested base generic type
1987                                 //
1988                                 // class A<T> : Base<A<T>.Nested> {
1989                                 //    class Nested {}
1990                                 // }
1991                                 //
1992                                 // When inflating A<T>. base type is not yet known, secondary
1993                                 // inflation is required (not common case) once base scope
1994                                 // is known
1995                                 //
1996                                 if (open_type.BaseType == null) {
1997                                         if (IsClass)
1998                                                 state |= StateFlags.PendingBaseTypeInflate;
1999                                 } else {
2000                                         BaseType = inflator.Inflate (open_type.BaseType);
2001                                 }
2002                         } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2003                                 //
2004                                 // It can happen when resolving base type without being defined
2005                                 // which is not allowed to happen and will always lead to an error
2006                                 //
2007                                 // class B { class N {} }
2008                                 // class A<T> : A<B.N> {}
2009                                 //
2010                                 if (open_type.BaseType == null)
2011                                         return;
2012
2013                                 BaseType = inflator.Inflate (open_type.BaseType);
2014                                 state &= ~StateFlags.PendingBaseTypeInflate;
2015                         }
2016
2017                         if (onlyTypes) {
2018                                 state |= StateFlags.PendingMemberCacheMembers;
2019                                 return;
2020                         }
2021
2022                         var tc = open_type.MemberDefinition as TypeDefinition;
2023                         if (tc != null && !tc.HasMembersDefined) {
2024                                 //
2025                                 // Inflating MemberCache with undefined members
2026                                 //
2027                                 return;
2028                         }
2029
2030                         if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2031                                 BaseType = inflator.Inflate (open_type.BaseType);
2032                                 state &= ~StateFlags.PendingBaseTypeInflate;
2033                         }
2034
2035                         state &= ~StateFlags.PendingMemberCacheMembers;
2036                         open_type.MemberCache.InflateMembers (cache, open_type, inflator);
2037                 }
2038
2039                 public override TypeSpec Mutate (TypeParameterMutator mutator)
2040                 {
2041                         var targs = TypeArguments;
2042                         if (targs != null)
2043                                 targs = mutator.Mutate (targs);
2044
2045                         var decl = DeclaringType;
2046                         if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
2047                                 decl = mutator.Mutate (decl);
2048
2049                         if (targs == TypeArguments && decl == DeclaringType)
2050                                 return this;
2051
2052                         var mutated = (InflatedTypeSpec) MemberwiseClone ();
2053                         if (decl != DeclaringType) {
2054                                 // Gets back MethodInfo in case of metaInfo was inflated
2055                                 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
2056
2057                                 mutated.declaringType = decl;
2058                                 mutated.state |= StateFlags.PendingMetaInflate;
2059                         }
2060
2061                         if (targs != null) {
2062                                 mutated.targs = targs;
2063                                 mutated.info = null;
2064                         }
2065
2066                         return mutated;
2067                 }
2068         }
2069
2070
2071         //
2072         // Tracks the type arguments when instantiating a generic type. It's used
2073         // by both type arguments and type parameters
2074         //
2075         public class TypeArguments
2076         {
2077                 List<FullNamedExpression> args;
2078                 TypeSpec[] atypes;
2079
2080                 public TypeArguments (params FullNamedExpression[] types)
2081                 {
2082                         this.args = new List<FullNamedExpression> (types);
2083                 }
2084
2085                 public void Add (FullNamedExpression type)
2086                 {
2087                         args.Add (type);
2088                 }
2089
2090                 /// <summary>
2091                 ///   We may only be used after Resolve() is called and return the fully
2092                 ///   resolved types.
2093                 /// </summary>
2094                 // TODO: Not needed, just return type from resolve
2095                 public TypeSpec[] Arguments {
2096                         get {
2097                                 return atypes;
2098                         }
2099                         set {
2100                                 atypes = value;
2101                         }
2102                 }
2103
2104                 public int Count {
2105                         get {
2106                                 return args.Count;
2107                         }
2108                 }
2109
2110                 public virtual bool IsEmpty {
2111                         get {
2112                                 return false;
2113                         }
2114                 }
2115
2116                 public List<FullNamedExpression> TypeExpressions {
2117                         get {
2118                                 return this.args;
2119                         }
2120                 }
2121
2122                 public string GetSignatureForError()
2123                 {
2124                         StringBuilder sb = new StringBuilder ();
2125                         for (int i = 0; i < Count; ++i) {
2126                                 var expr = args[i];
2127                                 if (expr != null)
2128                                         sb.Append (expr.GetSignatureForError ());
2129
2130                                 if (i + 1 < Count)
2131                                         sb.Append (',');
2132                         }
2133
2134                         return sb.ToString ();
2135                 }
2136
2137                 /// <summary>
2138                 ///   Resolve the type arguments.
2139                 /// </summary>
2140                 public virtual bool Resolve (IMemberContext ec)
2141                 {
2142                         if (atypes != null)
2143                             return atypes.Length != 0;
2144
2145                         int count = args.Count;
2146                         bool ok = true;
2147
2148                         atypes = new TypeSpec [count];
2149
2150                         for (int i = 0; i < count; i++){
2151                                 var te = args[i].ResolveAsType (ec);
2152                                 if (te == null) {
2153                                         ok = false;
2154                                         continue;
2155                                 }
2156
2157                                 atypes[i] = te;
2158
2159                                 if (te.IsStatic) {
2160                                         ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
2161                                                 te.GetSignatureForError ());
2162                                         ok = false;
2163                                 }
2164
2165                                 if (te.IsPointer || te.IsSpecialRuntimeType) {
2166                                         ec.Module.Compiler.Report.Error (306, args[i].Location,
2167                                                 "The type `{0}' may not be used as a type argument",
2168                                                 te.GetSignatureForError ());
2169                                         ok = false;
2170                                 }
2171                         }
2172
2173                         if (!ok)
2174                                 atypes = TypeSpec.EmptyTypes;
2175
2176                         return ok;
2177                 }
2178
2179                 public TypeArguments Clone ()
2180                 {
2181                         TypeArguments copy = new TypeArguments ();
2182                         foreach (var ta in args)
2183                                 copy.args.Add (ta);
2184
2185                         return copy;
2186                 }
2187         }
2188
2189         public class UnboundTypeArguments : TypeArguments
2190         {
2191                 public UnboundTypeArguments (int arity)
2192                         : base (new FullNamedExpression[arity])
2193                 {
2194                 }
2195
2196                 public override bool IsEmpty {
2197                         get {
2198                                 return true;
2199                         }
2200                 }
2201
2202                 public override bool Resolve (IMemberContext ec)
2203                 {
2204                         // Nothing to be resolved
2205                         return true;
2206                 }
2207         }
2208
2209         public class TypeParameters
2210         {
2211                 List<TypeParameter> names;
2212                 TypeParameterSpec[] types;
2213
2214                 public TypeParameters ()
2215                 {
2216                         names = new List<TypeParameter> ();
2217                 }
2218
2219                 public TypeParameters (int count)
2220                 {
2221                         names = new List<TypeParameter> (count);
2222                 }
2223
2224                 #region Properties
2225
2226                 public int Count {
2227                         get {
2228                                 return names.Count;
2229                         }
2230                 }
2231
2232                 public TypeParameterSpec[] Types {
2233                         get {
2234                                 return types;
2235                         }
2236                 }
2237
2238                 #endregion
2239
2240                 public void Add (TypeParameter tparam)
2241                 {
2242                         names.Add (tparam);
2243                 }
2244
2245                 public void Add (TypeParameters tparams)
2246                 {
2247                         names.AddRange (tparams.names);
2248                 }
2249
2250                 public void Create (TypeSpec declaringType, int parentOffset, TypeContainer parent)
2251                 {
2252                         types = new TypeParameterSpec[Count];
2253                         for (int i = 0; i < types.Length; ++i) {
2254                                 var tp = names[i];
2255
2256                                 tp.Create (declaringType, parent);
2257                                 types[i] = tp.Type;
2258                                 types[i].DeclaredPosition = i + parentOffset;
2259
2260                                 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2261                                         parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2262                                 }
2263                         }
2264                 }
2265
2266                 public void Define (GenericTypeParameterBuilder[] builders)
2267                 {
2268                         for (int i = 0; i < types.Length; ++i) {
2269                                 var tp = names[i];
2270                                 tp.Define (builders [types [i].DeclaredPosition]);
2271                         }
2272                 }
2273
2274                 public TypeParameter this[int index] {
2275                         get {
2276                                 return names [index];
2277                         }
2278                         set {
2279                                 names[index] = value;
2280                         }
2281                 }
2282
2283                 public TypeParameter Find (string name)
2284                 {
2285                         foreach (var tp in names) {
2286                                 if (tp.Name == name)
2287                                         return tp;
2288                         }
2289
2290                         return null;
2291                 }
2292
2293                 public string[] GetAllNames ()
2294                 {
2295                         return names.Select (l => l.Name).ToArray ();
2296                 }
2297
2298                 public string GetSignatureForError ()
2299                 {
2300                         StringBuilder sb = new StringBuilder ();
2301                         for (int i = 0; i < Count; ++i) {
2302                                 if (i > 0)
2303                                         sb.Append (',');
2304
2305                                 var name = names[i];
2306                                 if (name != null)
2307                                         sb.Append (name.GetSignatureForError ());
2308                         }
2309
2310                         return sb.ToString ();
2311                 }
2312
2313
2314                 public void CheckPartialConstraints (Method part)
2315                 {
2316                         var partTypeParameters = part.CurrentTypeParameters;
2317
2318                         for (int i = 0; i < Count; i++) {
2319                                 var tp_a = names[i];
2320                                 var tp_b = partTypeParameters [i];
2321                                 if (tp_a.Constraints == null) {
2322                                         if (tp_b.Constraints == null)
2323                                                 continue;
2324                                 } else if (tp_b.Constraints != null && tp_a.Type.HasSameConstraintsDefinition (tp_b.Type)) {
2325                                         continue;
2326                                 }
2327
2328                                 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition.Location, "");
2329                                 part.Compiler.Report.Error (761, part.Location,
2330                                         "Partial method declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2331                                         part.GetSignatureForError (), partTypeParameters[i].GetSignatureForError ());
2332                         }
2333                 }
2334
2335                 public void UpdateConstraints (TypeDefinition part)
2336                 {
2337                         var partTypeParameters = part.MemberName.TypeParameters;
2338
2339                         for (int i = 0; i < Count; i++) {
2340                                 var tp = names [i];
2341                                 if (tp.AddPartialConstraints (part, partTypeParameters [i]))
2342                                         continue;
2343
2344                                 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition);
2345                                 part.Compiler.Report.Error (265, part.Location,
2346                                         "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2347                                         part.GetSignatureForError (), tp.GetSignatureForError ());
2348                         }
2349                 }
2350
2351                 public void VerifyClsCompliance ()
2352                 {
2353                         foreach (var tp in names) {
2354                                 tp.VerifyClsCompliance ();
2355                         }
2356                 }
2357         }
2358
2359         //
2360         // A type expression of generic type with type arguments
2361         //
2362         class GenericTypeExpr : TypeExpr
2363         {
2364                 TypeArguments args;
2365                 TypeSpec open_type;
2366
2367                 /// <summary>
2368                 ///   Instantiate the generic type `t' with the type arguments `args'.
2369                 ///   Use this constructor if you already know the fully resolved
2370                 ///   generic type.
2371                 /// </summary>          
2372                 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2373                 {
2374                         this.open_type = open_type;
2375                         loc = l;
2376                         this.args = args;
2377                 }
2378
2379                 public override string GetSignatureForError ()
2380                 {
2381                         return type.GetSignatureForError ();
2382                 }
2383
2384                 public override TypeSpec ResolveAsType (IMemberContext mc)
2385                 {
2386                         if (eclass != ExprClass.Unresolved)
2387                                 return type;
2388
2389                         if (!args.Resolve (mc))
2390                                 return null;
2391
2392                         TypeSpec[] atypes = args.Arguments;
2393
2394                         //
2395                         // Now bind the parameters
2396                         //
2397                         var inflated = open_type.MakeGenericType (mc, atypes);
2398                         type = inflated;
2399                         eclass = ExprClass.Type;
2400
2401                         //
2402                         // The constraints can be checked only when full type hierarchy is known
2403                         //
2404                         if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2405                                 var constraints = inflated.Constraints;
2406                                 if (constraints != null) {
2407                                         var cc = new ConstraintChecker (mc);
2408                                         if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2409                                                 inflated.HasConstraintsChecked = true;
2410                                         }
2411                                 }
2412                         }
2413
2414                         return type;
2415                 }
2416
2417                 public override bool Equals (object obj)
2418                 {
2419                         GenericTypeExpr cobj = obj as GenericTypeExpr;
2420                         if (cobj == null)
2421                                 return false;
2422
2423                         if ((type == null) || (cobj.type == null))
2424                                 return false;
2425
2426                         return type == cobj.type;
2427                 }
2428
2429                 public override int GetHashCode ()
2430                 {
2431                         return base.GetHashCode ();
2432                 }
2433         }
2434
2435         //
2436         // Generic type with unbound type arguments, used for typeof (G<,,>)
2437         //
2438         class GenericOpenTypeExpr : TypeExpression
2439         {
2440                 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2441                         : base (type.GetDefinition (), loc)
2442                 {
2443                 }
2444         }
2445
2446         struct ConstraintChecker
2447         {
2448                 IMemberContext mc;
2449                 bool recursive_checks;
2450
2451                 public ConstraintChecker (IMemberContext ctx)
2452                 {
2453                         this.mc = ctx;
2454                         recursive_checks = false;
2455                 }
2456
2457                 //
2458                 // Checks the constraints of open generic type against type
2459                 // arguments. This version is used for types which could not be
2460                 // checked immediatelly during construction because the type
2461                 // hierarchy was not yet fully setup (before Emit phase)
2462                 //
2463                 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2464                 {
2465                         //
2466                         // Check declaring type first if there is any
2467                         //
2468                         if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2469                                 return false;
2470
2471                         while (type is ElementTypeSpec)
2472                                 type = ((ElementTypeSpec) type).Element;
2473
2474                         if (type.Arity == 0)
2475                                 return true;
2476
2477                         var gtype = type as InflatedTypeSpec;
2478                         if (gtype == null)
2479                                 return true;
2480
2481                         var constraints = gtype.Constraints;
2482                         if (constraints == null)
2483                                 return true;
2484
2485                         if (gtype.HasConstraintsChecked)
2486                                 return true;
2487
2488                         var cc = new ConstraintChecker (mc);
2489                         cc.recursive_checks = true;
2490
2491                         if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2492                                 gtype.HasConstraintsChecked = true;
2493                                 return true;
2494                         }
2495
2496                         return false;
2497                 }
2498
2499                 //
2500                 // Checks all type arguments againts type parameters constraints
2501                 // NOTE: It can run in probing mode when `this.mc' is null
2502                 //
2503                 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2504                 {
2505                         for (int i = 0; i < tparams.Length; i++) {
2506                                 var targ = targs[i];
2507                                 if (!CheckConstraint (context, targ, tparams [i], loc))
2508                                         return false;
2509
2510                                 if (!recursive_checks)
2511                                         continue;
2512
2513                                 if (!Check (mc, targ, loc))
2514                                         return false;
2515                         }
2516
2517                         return true;
2518                 }
2519
2520                 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2521                 {
2522                         //
2523                         // First, check the `class' and `struct' constraints.
2524                         //
2525                         if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2526                                 if (mc != null) {
2527                                         mc.Module.Compiler.Report.Error (452, loc,
2528                                                 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2529                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2530                                 }
2531
2532                                 return false;
2533                         }
2534
2535                         if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2536                                 if (mc != null) {
2537                                         mc.Module.Compiler.Report.Error (453, loc,
2538                                                 "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}'",
2539                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2540                                 }
2541
2542                                 return false;
2543                         }
2544
2545                         bool ok = true;
2546
2547                         //
2548                         // Check the class constraint
2549                         //
2550                         if (tparam.HasTypeConstraint) {
2551                                 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2552                                         if (mc == null)
2553                                                 return false;
2554
2555                                         ok = false;
2556                                 }
2557                         }
2558
2559                         //
2560                         // Check the interfaces constraints
2561                         //
2562                         if (tparam.InterfacesDefined != null) {
2563                                 foreach (TypeSpec iface in tparam.InterfacesDefined) {
2564                                         if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2565                                                 if (mc == null)
2566                                                         return false;
2567
2568                                                 ok = false;
2569                                                 break;
2570                                         }
2571                                 }
2572                         }
2573
2574                         //
2575                         // Check the type parameter constraint
2576                         //
2577                         if (tparam.TypeArguments != null) {
2578                                 foreach (var ta in tparam.TypeArguments) {
2579                                         if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2580                                                 if (mc == null)
2581                                                         return false;
2582
2583                                                 ok = false;
2584                                                 break;
2585                                         }
2586                                 }
2587                         }
2588
2589                         //
2590                         // Finally, check the constructor constraint.
2591                         //
2592                         if (!tparam.HasSpecialConstructor)
2593                                 return ok;
2594
2595                         if (!HasDefaultConstructor (atype)) {
2596                                 if (mc != null) {
2597                                         mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2598                                         mc.Module.Compiler.Report.Error (310, loc,
2599                                                 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2600                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2601                                 }
2602                                 return false;
2603                         }
2604
2605                         return ok;
2606                 }
2607
2608                 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2609                 {
2610                         for (int i = 0; i < targs.Length; ++i) {
2611                                 var targ = targs [i];
2612                                 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2613                                         return true;
2614
2615                                 if (HasDynamicTypeArgument (targ.TypeArguments))
2616                                         return true;
2617                         }
2618
2619                         return false;
2620                 }
2621
2622                 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2623                 {
2624                         if (atype == ttype)
2625                                 return true;
2626
2627                         if (atype.IsGenericParameter) {
2628                                 var tps = (TypeParameterSpec) atype;
2629                                 if (tps.HasDependencyOn (ttype))
2630                                         return true;
2631
2632                                 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2633                                         return true;
2634
2635                         } else if (TypeSpec.IsValueType (atype)) {
2636                                 if (atype.IsNullableType) {
2637                                         //
2638                                         // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2639                                         //
2640                                         if (TypeSpec.IsBaseClass (atype, ttype, false))
2641                                                 return true;
2642                                 } else {
2643                                         if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2644                                                 return true;
2645                                 }
2646                         } else {
2647                                 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2648                                         return true;
2649                         }
2650
2651                         if (mc != null) {
2652                                 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2653                                 if (atype.IsGenericParameter) {
2654                                         mc.Module.Compiler.Report.Error (314, loc,
2655                                                 "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}'",
2656                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2657                                 } else if (TypeSpec.IsValueType (atype)) {
2658                                         if (atype.IsNullableType) {
2659                                                 if (ttype.IsInterface) {
2660                                                         mc.Module.Compiler.Report.Error (313, loc,
2661                                                                 "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 `{3}'",
2662                                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2663                                                 } else {
2664                                                         mc.Module.Compiler.Report.Error (312, loc,
2665                                                                 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' does not satisfy constraint `{3}'",
2666                                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2667                                                 }
2668                                         } else {
2669                                                 mc.Module.Compiler.Report.Error (315, loc,
2670                                                         "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}'",
2671                                                         atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2672                                         }
2673                                 } else {
2674                                         mc.Module.Compiler.Report.Error (311, loc,
2675                                                 "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}'",
2676                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2677                                 }
2678                         }
2679
2680                         return false;
2681                 }
2682
2683                 static bool HasDefaultConstructor (TypeSpec atype)
2684                 {
2685                         var tp = atype as TypeParameterSpec;
2686                         if (tp != null) {
2687                                 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2688                         }
2689
2690                         if (atype.IsStruct || atype.IsEnum)
2691                                 return true;
2692
2693                         if (atype.IsAbstract)
2694                                 return false;
2695
2696                         var tdef = atype.GetDefinition ();
2697
2698                         var found = MemberCache.FindMember (tdef,
2699                                 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2700                                 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2701
2702                         return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2703                 }
2704         }
2705
2706         //
2707         // Implements C# type inference
2708         //
2709         class TypeInference
2710         {
2711                 //
2712                 // Tracks successful rate of type inference
2713                 //
2714                 int score = int.MaxValue;
2715                 readonly Arguments arguments;
2716                 readonly int arg_count;
2717
2718                 public TypeInference (Arguments arguments)
2719                 {
2720                         this.arguments = arguments;
2721                         if (arguments != null)
2722                                 arg_count = arguments.Count;
2723                 }
2724
2725                 public int InferenceScore {
2726                         get {
2727                                 return score;
2728                         }
2729                 }
2730
2731                 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2732                 {
2733                         var method_generic_args = method.GenericDefinition.TypeParameters;
2734                         TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2735                         if (!context.UnfixedVariableExists)
2736                                 return TypeSpec.EmptyTypes;
2737
2738                         AParametersCollection pd = method.Parameters;
2739                         if (!InferInPhases (ec, context, pd))
2740                                 return null;
2741
2742                         return context.InferredTypeArguments;
2743                 }
2744
2745                 //
2746                 // Implements method type arguments inference
2747                 //
2748                 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2749                 {
2750                         int params_arguments_start;
2751                         if (methodParameters.HasParams) {
2752                                 params_arguments_start = methodParameters.Count - 1;
2753                         } else {
2754                                 params_arguments_start = arg_count;
2755                         }
2756
2757                         TypeSpec [] ptypes = methodParameters.Types;
2758                         
2759                         //
2760                         // The first inference phase
2761                         //
2762                         TypeSpec method_parameter = null;
2763                         for (int i = 0; i < arg_count; i++) {
2764                                 Argument a = arguments [i];
2765                                 if (a == null)
2766                                         continue;
2767                                 
2768                                 if (i < params_arguments_start) {
2769                                         method_parameter = methodParameters.Types [i];
2770                                 } else if (i == params_arguments_start) {
2771                                         if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2772                                                 method_parameter = methodParameters.Types [params_arguments_start];
2773                                         else
2774                                                 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2775
2776                                         ptypes = (TypeSpec[]) ptypes.Clone ();
2777                                         ptypes [i] = method_parameter;
2778                                 }
2779
2780                                 //
2781                                 // When a lambda expression, an anonymous method
2782                                 // is used an explicit argument type inference takes a place
2783                                 //
2784                                 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2785                                 if (am != null) {
2786                                         if (am.ExplicitTypeInference (tic, method_parameter))
2787                                                 --score; 
2788                                         continue;
2789                                 }
2790
2791                                 if (a.IsByRef) {
2792                                         score -= tic.ExactInference (a.Type, method_parameter);
2793                                         continue;
2794                                 }
2795
2796                                 if (a.Expr.Type == InternalType.NullLiteral)
2797                                         continue;
2798
2799                                 if (TypeSpec.IsValueType (method_parameter)) {
2800                                         score -= tic.LowerBoundInference (a.Type, method_parameter);
2801                                         continue;
2802                                 }
2803
2804                                 //
2805                                 // Otherwise an output type inference is made
2806                                 //
2807                                 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2808                         }
2809
2810                         //
2811                         // Part of the second phase but because it happens only once
2812                         // we don't need to call it in cycle
2813                         //
2814                         bool fixed_any = false;
2815                         if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2816                                 return false;
2817
2818                         return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2819                 }
2820
2821                 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2822                 {
2823                         bool fixed_any = false;
2824                         if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2825                                 return false;
2826
2827                         // If no further unfixed type variables exist, type inference succeeds
2828                         if (!tic.UnfixedVariableExists)
2829                                 return true;
2830
2831                         if (!fixed_any && fixDependent)
2832                                 return false;
2833                         
2834                         // For all arguments where the corresponding argument output types
2835                         // contain unfixed type variables but the input types do not,
2836                         // an output type inference is made
2837                         for (int i = 0; i < arg_count; i++) {
2838                                 
2839                                 // Align params arguments
2840                                 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2841                                 
2842                                 if (!t_i.IsDelegate) {
2843                                         if (!t_i.IsExpressionTreeType)
2844                                                 continue;
2845
2846                                         t_i = TypeManager.GetTypeArguments (t_i) [0];
2847                                 }
2848
2849                                 var mi = Delegate.GetInvokeMethod (t_i);
2850                                 TypeSpec rtype = mi.ReturnType;
2851
2852                                 if (tic.IsReturnTypeNonDependent (mi, rtype)) {
2853                                         // It can be null for default arguments
2854                                         if (arguments[i] == null)
2855                                                 continue;
2856
2857                                         score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2858                                 }
2859                         }
2860
2861
2862                         return DoSecondPhase (ec, tic, methodParameters, true);
2863                 }
2864         }
2865
2866         public class TypeInferenceContext
2867         {
2868                 protected enum BoundKind
2869                 {
2870                         Exact   = 0,
2871                         Lower   = 1,
2872                         Upper   = 2
2873                 }
2874
2875                 struct BoundInfo : IEquatable<BoundInfo>
2876                 {
2877                         public readonly TypeSpec Type;
2878                         public readonly BoundKind Kind;
2879
2880                         public BoundInfo (TypeSpec type, BoundKind kind)
2881                         {
2882                                 this.Type = type;
2883                                 this.Kind = kind;
2884                         }
2885                         
2886                         public override int GetHashCode ()
2887                         {
2888                                 return Type.GetHashCode ();
2889                         }
2890
2891                         public Expression GetTypeExpression ()
2892                         {
2893                                 return new TypeExpression (Type, Location.Null);
2894                         }
2895
2896                         #region IEquatable<BoundInfo> Members
2897
2898                         public bool Equals (BoundInfo other)
2899                         {
2900                                 return Type == other.Type && Kind == other.Kind;
2901                         }
2902
2903                         #endregion
2904                 }
2905
2906                 readonly TypeSpec[] tp_args;
2907                 readonly TypeSpec[] fixed_types;
2908                 readonly List<BoundInfo>[] bounds;
2909                 bool failed;
2910
2911                 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2912                 public TypeInferenceContext (TypeSpec[] typeArguments)
2913                 {
2914                         if (typeArguments.Length == 0)
2915                                 throw new ArgumentException ("Empty generic arguments");
2916
2917                         fixed_types = new TypeSpec [typeArguments.Length];
2918                         for (int i = 0; i < typeArguments.Length; ++i) {
2919                                 if (typeArguments [i].IsGenericParameter) {
2920                                         if (bounds == null) {
2921                                                 bounds = new List<BoundInfo> [typeArguments.Length];
2922                                                 tp_args = new TypeSpec [typeArguments.Length];
2923                                         }
2924                                         tp_args [i] = typeArguments [i];
2925                                 } else {
2926                                         fixed_types [i] = typeArguments [i];
2927                                 }
2928                         }
2929                 }
2930
2931                 // 
2932                 // Used together with AddCommonTypeBound fo implement
2933                 // 7.4.2.13 Finding the best common type of a set of expressions
2934                 //
2935                 public TypeInferenceContext ()
2936                 {
2937                         fixed_types = new TypeSpec [1];
2938                         tp_args = new TypeSpec [1];
2939                         tp_args[0] = InternalType.Arglist; // it can be any internal type
2940                         bounds = new List<BoundInfo> [1];
2941                 }
2942
2943                 public TypeSpec[] InferredTypeArguments {
2944                         get {
2945                                 return fixed_types;
2946                         }
2947                 }
2948
2949                 public void AddCommonTypeBound (TypeSpec type)
2950                 {
2951                         AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, false);
2952                 }
2953
2954                 public void AddCommonTypeBoundAsync (TypeSpec type)
2955                 {
2956                         AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, true);
2957                 }
2958
2959                 void AddToBounds (BoundInfo bound, int index, bool voidAllowed)
2960                 {
2961                         //
2962                         // Some types cannot be used as type arguments
2963                         //
2964                         if ((bound.Type.Kind == MemberKind.Void && !voidAllowed) || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2965                                 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
2966                                 return;
2967
2968                         var a = bounds [index];
2969                         if (a == null) {
2970                                 a = new List<BoundInfo> (2);
2971                                 a.Add (bound);
2972                                 bounds [index] = a;
2973                                 return;
2974                         }
2975
2976                         if (a.Contains (bound))
2977                                 return;
2978
2979                         a.Add (bound);
2980                 }
2981                 
2982                 bool AllTypesAreFixed (TypeSpec[] types)
2983                 {
2984                         foreach (TypeSpec t in types) {
2985                                 if (t.IsGenericParameter) {
2986                                         if (!IsFixed (t))
2987                                                 return false;
2988                                         continue;
2989                                 }
2990
2991                                 if (TypeManager.IsGenericType (t))
2992                                         return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2993                         }
2994                         
2995                         return true;
2996                 }               
2997
2998                 //
2999                 // 26.3.3.8 Exact Inference
3000                 //
3001                 public int ExactInference (TypeSpec u, TypeSpec v)
3002                 {
3003                         // If V is an array type
3004                         if (v.IsArray) {
3005                                 if (!u.IsArray)
3006                                         return 0;
3007
3008                                 var ac_u = (ArrayContainer) u;
3009                                 var ac_v = (ArrayContainer) v;
3010                                 if (ac_u.Rank != ac_v.Rank)
3011                                         return 0;
3012
3013                                 return ExactInference (ac_u.Element, ac_v.Element);
3014                         }
3015
3016                         // If V is constructed type and U is constructed type
3017                         if (TypeManager.IsGenericType (v)) {
3018                                 if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
3019                                         return 0;
3020
3021                                 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
3022                                 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
3023                                 if (ga_u.Length != ga_v.Length)
3024                                         return 0;
3025
3026                                 int score = 0;
3027                                 for (int i = 0; i < ga_u.Length; ++i)
3028                                         score += ExactInference (ga_u [i], ga_v [i]);
3029
3030                                 return System.Math.Min (1, score);
3031                         }
3032
3033                         // If V is one of the unfixed type arguments
3034                         int pos = IsUnfixed (v);
3035                         if (pos == -1)
3036                                 return 0;
3037
3038                         AddToBounds (new BoundInfo (u, BoundKind.Exact), pos, false);
3039                         return 1;
3040                 }
3041
3042                 public bool FixAllTypes (ResolveContext ec)
3043                 {
3044                         for (int i = 0; i < tp_args.Length; ++i) {
3045                                 if (!FixType (ec, i))
3046                                         return false;
3047                         }
3048                         return true;
3049                 }
3050
3051                 //
3052                 // All unfixed type variables Xi are fixed for which all of the following hold:
3053                 // a, There is at least one type variable Xj that depends on Xi
3054                 // b, Xi has a non-empty set of bounds
3055                 // 
3056                 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
3057                 {
3058                         for (int i = 0; i < tp_args.Length; ++i) {
3059                                 if (fixed_types[i] != null)
3060                                         continue;
3061
3062                                 if (bounds[i] == null)
3063                                         continue;
3064
3065                                 if (!FixType (ec, i))
3066                                         return false;
3067                                 
3068                                 fixed_any = true;
3069                         }
3070
3071                         return true;
3072                 }
3073
3074                 //
3075                 // All unfixed type variables Xi which depend on no Xj are fixed
3076                 //
3077                 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
3078                 {
3079                         var types_to_fix = new List<TypeSpec> (tp_args);
3080                         for (int i = 0; i < methodParameters.Length; ++i) {
3081                                 TypeSpec t = methodParameters[i];
3082
3083                                 if (!t.IsDelegate) {
3084                                         if (!t.IsExpressionTreeType)
3085                                                 continue;
3086
3087                                         t =  TypeManager.GetTypeArguments (t) [0];
3088                                 }
3089
3090                                 if (t.IsGenericParameter)
3091                                         continue;
3092
3093                                 var invoke = Delegate.GetInvokeMethod (t);
3094                                 TypeSpec rtype = invoke.ReturnType;
3095                                 while (rtype.IsArray)
3096                                         rtype = ((ArrayContainer) rtype).Element;
3097
3098                                 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3099                                         continue;
3100
3101                                 // Remove dependent types, they cannot be fixed yet
3102                                 RemoveDependentTypes (types_to_fix, rtype);
3103                         }
3104
3105                         foreach (TypeSpec t in types_to_fix) {
3106                                 if (t == null)
3107                                         continue;
3108
3109                                 int idx = IsUnfixed (t);
3110                                 if (idx >= 0 && !FixType (ec, idx)) {
3111                                         return false;
3112                                 }
3113                         }
3114
3115                         fixed_any = types_to_fix.Count > 0;
3116                         return true;
3117                 }
3118
3119                 //
3120                 // 26.3.3.10 Fixing
3121                 //
3122                 public bool FixType (ResolveContext ec, int i)
3123                 {
3124                         // It's already fixed
3125                         if (fixed_types[i] != null)
3126                                 throw new InternalErrorException ("Type argument has been already fixed");
3127
3128                         if (failed)
3129                                 return false;
3130
3131                         var candidates = bounds [i];
3132                         if (candidates == null)
3133                                 return false;
3134
3135                         if (candidates.Count == 1) {
3136                                 TypeSpec t = candidates[0].Type;
3137                                 if (t == InternalType.NullLiteral)
3138                                         return false;
3139
3140                                 fixed_types [i] = t;
3141                                 return true;
3142                         }
3143
3144                         //
3145                         // The set of candidate types Uj starts out as the set of
3146                         // all types in the set of bounds for Xi
3147                         //
3148                         var applicable = new bool [candidates.Count];
3149                         for (int ci = 0; ci < applicable.Length; ++ci)
3150                                 applicable [ci] = true;
3151
3152                         for (int ci = 0; ci < applicable.Length; ++ci) {
3153                                 var bound = candidates [ci];
3154                                 int cii = 0;
3155
3156                                 switch (bound.Kind) {
3157                                 case BoundKind.Exact:
3158                                         for (; cii != applicable.Length; ++cii) {
3159                                                 if (ci == cii)
3160                                                         continue;
3161
3162                                                 if (!applicable[cii])
3163                                                         break;
3164
3165                                                 //
3166                                                 // For each exact bound U of Xi all types Uj which are not identical
3167                                                 // to U are removed from the candidate set
3168                                                 //
3169                                                 if (candidates [cii].Type != bound.Type)
3170                                                         applicable[cii] = false;
3171                                         }
3172
3173                                         break;
3174                                 case BoundKind.Lower:
3175                                         for (; cii != applicable.Length; ++cii) {
3176                                                 if (ci == cii)
3177                                                         continue;
3178
3179                                                 if (!applicable[cii])
3180                                                         break;
3181
3182                                                 //
3183                                                 // For each lower bound U of Xi all types Uj to which there is not an implicit conversion
3184                                                 // from U are removed from the candidate set
3185                                                 //
3186                                                 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), candidates [cii].Type)) {
3187                                                         applicable[cii] = false;
3188                                                 }
3189                                         }
3190
3191                                         break;
3192
3193                                 case BoundKind.Upper:
3194                                         for (; cii != applicable.Length; ++cii) {
3195                                                 if (ci == cii)
3196                                                         continue;
3197
3198                                                 if (!applicable[cii])
3199                                                         break;
3200
3201                                                 //
3202                                                 // For each upper bound U of Xi all types Uj from which there is not an implicit conversion
3203                                                 // to U are removed from the candidate set
3204                                                 //
3205                                                 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3206                                                         applicable[cii] = false;
3207                                         }
3208
3209                                         break;
3210                                 }
3211                         }
3212
3213                         TypeSpec best_candidate = null;
3214                         for (int ci = 0; ci < applicable.Length; ++ci) {
3215                                 if (!applicable[ci])
3216                                         continue;
3217
3218                                 var bound = candidates [ci];
3219                                 if (bound.Type == best_candidate)
3220                                         continue;
3221
3222                                 int cii = 0;
3223                                 for (; cii < applicable.Length; ++cii) {
3224                                         if (ci == cii)
3225                                                 continue;
3226
3227                                         if (!applicable[cii])
3228                                                 continue;
3229
3230                                         if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3231                                                 break;
3232                                 }
3233
3234                                 if (cii != applicable.Length)
3235                                         continue;
3236
3237                                 //
3238                                 // We already have the best candidate, break if it's different (non-unique)
3239                                 //
3240                                 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3241                                 //
3242                                 if (best_candidate != null) {
3243
3244                                         if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3245                                                 continue;
3246
3247                                         if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3248                                                 return false;
3249                                 }
3250
3251                                 best_candidate = bound.Type;
3252                         }
3253
3254                         if (best_candidate == null)
3255                                 return false;
3256
3257                         fixed_types[i] = best_candidate;
3258                         return true;
3259                 }
3260
3261                 public bool HasBounds (int pos)
3262                 {
3263                         return bounds[pos] != null;
3264                 }
3265                 
3266                 //
3267                 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3268                 // null when type parameter has not been fixed
3269                 //
3270                 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3271                 {
3272                         var tp = parameter as TypeParameterSpec;
3273                         if (tp != null) {
3274                                 //
3275                                 // Type inference works on generic arguments (MVAR) only
3276                                 //
3277                                 if (!tp.IsMethodOwned)
3278                                         return parameter;
3279
3280                                 //
3281                                 // Ensure the type parameter belongs to same container
3282                                 //
3283                                 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3284                                         return fixed_types[tp.DeclaredPosition] ?? parameter;
3285
3286                                 return parameter;
3287                         }
3288
3289                         var gt = parameter as InflatedTypeSpec;
3290                         if (gt != null) {
3291                                 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3292                                 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3293                                         var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3294                                         if (inflated == null)
3295                                                 return null;
3296
3297                                         inflated_targs[ii] = inflated;
3298                                 }
3299
3300                                 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3301                         }
3302
3303                         var ac = parameter as ArrayContainer;
3304                         if (ac != null) {
3305                                 var inflated = InflateGenericArgument (context, ac.Element);
3306                                 if (inflated != ac.Element)
3307                                         return ArrayContainer.MakeType (context.Module, inflated);
3308                         }
3309
3310                         return parameter;
3311                 }
3312                 
3313                 //
3314                 // Tests whether all delegate input arguments are fixed and generic output type
3315                 // requires output type inference 
3316                 //
3317                 public bool IsReturnTypeNonDependent (MethodSpec invoke, TypeSpec returnType)
3318                 {
3319                         AParametersCollection d_parameters = invoke.Parameters;
3320
3321                         if (d_parameters.IsEmpty)
3322                                 return true;
3323
3324                         while (returnType.IsArray)
3325                                 returnType = ((ArrayContainer) returnType).Element;
3326
3327                         if (returnType.IsGenericParameter) {
3328                                 if (IsFixed (returnType))
3329                                     return false;
3330                         } else if (TypeManager.IsGenericType (returnType)) {
3331                                 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3332                                 
3333                                 // At least one unfixed return type has to exist 
3334                                 if (AllTypesAreFixed (g_args))
3335                                         return false;
3336                         } else {
3337                                 return false;
3338                         }
3339
3340                         // All generic input arguments have to be fixed
3341                         return AllTypesAreFixed (d_parameters.Types);
3342                 }
3343
3344                 bool IsFixed (TypeSpec type)
3345                 {
3346                         return IsUnfixed (type) == -1;
3347                 }               
3348
3349                 int IsUnfixed (TypeSpec type)
3350                 {
3351                         if (!type.IsGenericParameter)
3352                                 return -1;
3353
3354                         for (int i = 0; i < tp_args.Length; ++i) {
3355                                 if (tp_args[i] == type) {
3356                                         if (fixed_types[i] != null)
3357                                                 break;
3358
3359                                         return i;
3360                                 }
3361                         }
3362
3363                         return -1;
3364                 }
3365
3366                 //
3367                 // 26.3.3.9 Lower-bound Inference
3368                 //
3369                 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3370                 {
3371                         return LowerBoundInference (u, v, false);
3372                 }
3373
3374                 //
3375                 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3376                 //
3377                 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3378                 {
3379                         // If V is one of the unfixed type arguments
3380                         int pos = IsUnfixed (v);
3381                         if (pos != -1) {
3382                                 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos, false);
3383                                 return 1;
3384                         }                       
3385
3386                         // If U is an array type
3387                         var u_ac = u as ArrayContainer;
3388                         if (u_ac != null) {
3389                                 var v_ac = v as ArrayContainer;
3390                                 if (v_ac != null) {
3391                                         if (u_ac.Rank != v_ac.Rank)
3392                                                 return 0;
3393
3394                                         if (TypeSpec.IsValueType (u_ac.Element))
3395                                                 return ExactInference (u_ac.Element, v_ac.Element);
3396
3397                                         return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3398                                 }
3399
3400                                 if (u_ac.Rank != 1 || !v.IsArrayGenericInterface)
3401                                         return 0;
3402
3403                                 var v_i = TypeManager.GetTypeArguments (v) [0];
3404                                 if (TypeSpec.IsValueType (u_ac.Element))
3405                                         return ExactInference (u_ac.Element, v_i);
3406
3407                                 return LowerBoundInference (u_ac.Element, v_i);
3408                         }
3409                         
3410                         if (v.IsGenericOrParentIsGeneric) {
3411                                 //
3412                                 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3413                                 // such that U is identical to, inherits from (directly or indirectly),
3414                                 // or implements (directly or indirectly) C<U1..Uk>
3415                                 //
3416                                 var u_candidates = new List<TypeSpec> ();
3417                                 var open_v = v.MemberDefinition;
3418
3419                                 for (TypeSpec t = u; t != null; t = t.BaseType) {
3420                                         if (open_v == t.MemberDefinition)
3421                                                 u_candidates.Add (t);
3422
3423                                         //
3424                                         // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3425                                         // that would complicate the process a lot, instead I treat them as dynamic
3426                                         //
3427                                         if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3428                                                 u_candidates.Add (t);
3429                                 }
3430
3431                                 if (u.Interfaces != null) {
3432                                         foreach (var iface in u.Interfaces) {
3433                                                 if (open_v == iface.MemberDefinition)
3434                                                         u_candidates.Add (iface);
3435                                         }
3436                                 }
3437
3438                                 TypeSpec[] unique_candidate_targs = null;
3439                                 var ga_v = TypeSpec.GetAllTypeArguments (v);
3440                                 foreach (TypeSpec u_candidate in u_candidates) {
3441                                         //
3442                                         // The unique set of types U1..Uk means that if we have an interface I<T>,
3443                                         // class U : I<int>, I<long> then no type inference is made when inferring
3444                                         // type I<T> by applying type U because T could be int or long
3445                                         //
3446                                         if (unique_candidate_targs != null) {
3447                                                 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3448                                                 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3449                                                         unique_candidate_targs = second_unique_candidate_targs;
3450                                                         continue;
3451                                                 }
3452
3453                                                 //
3454                                                 // This should always cause type inference failure
3455                                                 //
3456                                                 failed = true;
3457                                                 return 1;
3458                                         }
3459
3460                                         //
3461                                         // A candidate is dynamic type expression, to simplify things use dynamic
3462                                         // for all type parameter of this type. For methods like this one
3463                                         // 
3464                                         // void M<T, U> (IList<T>, IList<U[]>)
3465                                         //
3466                                         // dynamic becomes both T and U when the arguments are of dynamic type
3467                                         //
3468                                         if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3469                                                 unique_candidate_targs = new TypeSpec[ga_v.Length];
3470                                                 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3471                                                         unique_candidate_targs[i] = u_candidate;
3472                                         } else {
3473                                                 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3474                                         }
3475                                 }
3476
3477                                 if (unique_candidate_targs != null) {
3478                                         int score = 0;
3479                                         int tp_index = -1;
3480                                         TypeParameterSpec[] tps = null;
3481
3482                                         for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3483                                                 if (tp_index < 0) {
3484                                                         while (v.Arity == 0)
3485                                                                 v = v.DeclaringType;
3486
3487                                                         tps = v.MemberDefinition.TypeParameters;
3488                                                         tp_index = tps.Length - 1;
3489                                                 }
3490
3491                                                 Variance variance = tps [tp_index--].Variance;
3492
3493                                                 TypeSpec u_i = unique_candidate_targs [i];
3494                                                 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3495                                                         if (ExactInference (u_i, ga_v [i]) == 0)
3496                                                                 ++score;
3497                                                 } else {
3498                                                         bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3499                                                                 (variance == Variance.Covariant && inversed);
3500
3501                                                         if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3502                                                                 ++score;
3503                                                 }
3504                                         }
3505
3506                                         return score;
3507                                 }
3508                         }
3509
3510                         return 0;
3511                 }
3512
3513                 //
3514                 // 26.3.3.6 Output Type Inference
3515                 //
3516                 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3517                 {
3518                         // If e is a lambda or anonymous method with inferred return type
3519                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3520                         if (ame != null) {
3521                                 TypeSpec rt = ame.InferReturnType (ec, this, t);
3522                                 var invoke = Delegate.GetInvokeMethod (t);
3523
3524                                 if (rt == null) {
3525                                         AParametersCollection pd = invoke.Parameters;
3526                                         return ame.Parameters.Count == pd.Count ? 1 : 0;
3527                                 }
3528
3529                                 TypeSpec rtype = invoke.ReturnType;
3530                                 return LowerBoundInference (rt, rtype) + 1;
3531                         }
3532
3533                         //
3534                         // if E is a method group and T is a delegate type or expression tree type
3535                         // return type Tb with parameter types T1..Tk and return type Tb, and overload
3536                         // resolution of E with the types T1..Tk yields a single method with return type U,
3537                         // then a lower-bound inference is made from U for Tb.
3538                         //
3539                         if (e is MethodGroupExpr) {
3540                                 if (!t.IsDelegate) {
3541                                         if (!t.IsExpressionTreeType)
3542                                                 return 0;
3543
3544                                         t = TypeManager.GetTypeArguments (t)[0];
3545                                 }
3546
3547                                 var invoke = Delegate.GetInvokeMethod (t);
3548                                 TypeSpec rtype = invoke.ReturnType;
3549
3550                                 if (!IsReturnTypeNonDependent (invoke, rtype))
3551                                         return 0;
3552
3553                                 // LAMESPEC: Standard does not specify that all methodgroup arguments
3554                                 // has to be fixed but it does not specify how to do recursive type inference
3555                                 // either. We choose the simple option and infer return type only
3556                                 // if all delegate generic arguments are fixed.
3557                                 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3558                                 for (int i = 0; i < param_types.Length; ++i) {
3559                                         var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3560                                         if (inflated == null)
3561                                                 return 0;
3562
3563                                         param_types[i] = inflated;
3564                                 }
3565
3566                                 MethodGroupExpr mg = (MethodGroupExpr) e;
3567                                 Arguments args = DelegateCreation.CreateDelegateMethodArguments (ec, invoke.Parameters, param_types, e.Location);
3568                                 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3569                                 if (mg == null)
3570                                         return 0;
3571
3572                                 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3573                         }
3574
3575                         //
3576                         // if e is an expression with type U, then
3577                         // a lower-bound inference is made from U for T
3578                         //
3579                         return LowerBoundInference (e.Type, t) * 2;
3580                 }
3581
3582                 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3583                 {
3584                         int idx = IsUnfixed (returnType);
3585                         if (idx >= 0) {
3586                                 types [idx] = null;
3587                                 return;
3588                         }
3589
3590                         if (TypeManager.IsGenericType (returnType)) {
3591                                 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3592                                         RemoveDependentTypes (types, t);
3593                                 }
3594                         }
3595                 }
3596
3597                 public bool UnfixedVariableExists {
3598                         get {
3599                                 foreach (TypeSpec ut in fixed_types) {
3600                                         if (ut == null)
3601                                                 return true;
3602                                 }
3603
3604                                 return false;
3605                         }
3606                 }
3607         }
3608 }