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