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