Merge branch 'master' of http://github.com/mono/mono
[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 //
13 using System;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Globalization;
17 using System.Collections.Generic;
18 using System.Text;
19 using System.Linq;
20         
21 namespace Mono.CSharp {
22         public enum Variance
23         {
24                 //
25                 // Don't add or modify internal values, they are used as -/+ calculation signs
26                 //
27                 None                    = 0,
28                 Covariant               = 1,
29                 Contravariant   = -1
30         }
31
32         [Flags]
33         public enum SpecialConstraint
34         {
35                 None            = 0,
36                 Constructor = 1 << 2,
37                 Class           = 1 << 3,
38                 Struct          = 1 << 4
39         }
40
41         public class SpecialContraintExpr : FullNamedExpression
42         {
43                 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
44                 {
45                         this.loc = loc;
46                         this.Constraint = constraint;
47                 }
48
49                 public SpecialConstraint Constraint { get; private set; }
50
51                 protected override Expression DoResolve (ResolveContext rc)
52                 {
53                         throw new NotImplementedException ();
54                 }
55         }
56
57         //
58         // A set of parsed constraints for a type parameter
59         //
60         public class Constraints
61         {
62                 SimpleMemberName tparam;
63                 List<FullNamedExpression> constraints;
64                 Location loc;
65                 bool resolved;
66                 bool resolving;
67                 
68                 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
69                 {
70                         this.tparam = tparam;
71                         this.constraints = constraints;
72                         this.loc = loc;
73                 }
74
75                 #region Properties
76
77                 public Location Location {
78                         get {
79                                 return loc;
80                         }
81                 }
82
83                 public SimpleMemberName TypeParameter {
84                         get {
85                                 return tparam;
86                         }
87                 }
88
89                 #endregion
90
91                 bool CheckConflictingInheritedConstraint (TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
92                 {
93                         if (!TypeManager.IsSubclassOf (ba, bb) && !TypeManager.IsSubclassOf (bb, ba)) {
94                                 context.Compiler.Report.Error (455, loc,
95                                         "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
96                                         tparam.Value,
97                                         ba.GetSignatureForError (), bb.GetSignatureForError ());
98                                 return false;
99                         }
100
101                         return true;
102                 }
103
104                 public void CheckGenericConstraints (IMemberContext context)
105                 {
106                         foreach (var c in constraints) {
107                                 var ge = c as GenericTypeExpr;
108                                 if (ge != null)
109                                         ge.CheckConstraints (context);
110                         }
111                 }
112
113                 //
114                 // Resolve the constraints types with only possible early checks, return
115                 // value `false' is reserved for recursive failure
116                 //
117                 public bool Resolve (IMemberContext context, TypeParameter tp)
118                 {
119                         if (resolved)
120                                 return true;
121
122                         if (resolving)
123                                 return false;
124
125                         resolving = true;
126                         var spec = tp.Type;
127                         List<TypeParameterSpec> tparam_types = null;
128                         bool iface_found = false;
129
130                         spec.BaseType = TypeManager.object_type;
131
132                         for (int i = 0; i < constraints.Count; ++i) {
133                                 var constraint = constraints[i];
134
135                                 if (constraint is SpecialContraintExpr) {
136                                         spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
137                                         if (spec.HasSpecialStruct)
138                                                 spec.BaseType = TypeManager.value_type;
139
140                                         // Set to null as it does not have a type
141                                         constraints[i] = null;
142                                         continue;
143                                 }
144
145                                 var type_expr = constraints[i] = constraint.ResolveAsTypeTerminal (context, false);
146                                 if (type_expr == null)
147                                         continue;
148
149                                 var gexpr = type_expr as GenericTypeExpr;
150                                 if (gexpr != null && gexpr.HasDynamicArguments ()) {
151                                         context.Compiler.Report.Error (1968, constraint.Location,
152                                                 "A constraint cannot be the dynamic type `{0}'", gexpr.GetSignatureForError ());
153                                         continue;
154                                 }
155
156                                 var type = type_expr.Type;
157
158                                 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
159                                         context.Compiler.Report.SymbolRelatedToPreviousError (type);
160                                         context.Compiler.Report.Error (703, loc,
161                                                 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
162                                                 type.GetSignatureForError (), context.GetSignatureForError ());
163                                 }
164
165                                 if (type.IsInterface) {
166                                         if (!spec.AddInterface (type)) {
167                                                 context.Compiler.Report.Error (405, constraint.Location,
168                                                         "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
169                                         }
170
171                                         iface_found = true;
172                                         continue;
173                                 }
174
175
176                                 var constraint_tp = type as TypeParameterSpec;
177                                 if (constraint_tp != null) {
178                                         if (tparam_types == null) {
179                                                 tparam_types = new List<TypeParameterSpec> (2);
180                                         } else if (tparam_types.Contains (constraint_tp)) {
181                                                 context.Compiler.Report.Error (405, constraint.Location,
182                                                         "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
183                                                 continue;
184                                         }
185
186                                         //
187                                         // Checks whether each generic method parameter constraint type
188                                         // is valid with respect to T
189                                         //
190                                         if (tp.IsMethodTypeParameter) {
191                                                 TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
192                                         }
193
194                                         var tp_def = constraint_tp.MemberDefinition as TypeParameter;
195                                         if (tp_def != null && !tp_def.ResolveConstraints (context)) {
196                                                 context.Compiler.Report.Error (454, constraint.Location,
197                                                         "Circular constraint dependency involving `{0}' and `{1}'",
198                                                         constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
199                                                 continue;
200                                         }
201
202                                         //
203                                         // Checks whether there are no conflicts between type parameter constraints
204                                         //
205                                         // class Foo<T, U>
206                                         //      where T : A
207                                         //      where U : B, T
208                                         //
209                                         // A and B are not convertible and only 1 class constraint is allowed
210                                         //
211                                         if (constraint_tp.HasTypeConstraint) {
212                                                 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
213                                                         if (!CheckConflictingInheritedConstraint (spec.BaseType, constraint_tp.BaseType, context, constraint.Location))
214                                                                 continue;
215                                                 } else {
216                                                         for (int ii = 0; ii < tparam_types.Count; ++ii) {
217                                                                 if (!tparam_types[ii].HasTypeConstraint)
218                                                                         continue;
219
220                                                                 if (!CheckConflictingInheritedConstraint (tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
221                                                                         break;
222                                                         }
223                                                 }
224                                         }
225
226                                         if (constraint_tp.HasSpecialStruct) {
227                                                 context.Compiler.Report.Error (456, constraint.Location,
228                                                         "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
229                                                         constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
230                                                 continue;
231                                         }
232
233                                         tparam_types.Add (constraint_tp);
234                                         continue;
235                                 }
236
237                                 if (iface_found || spec.HasTypeConstraint) {
238                                         context.Compiler.Report.Error (406, constraint.Location,
239                                                 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
240                                                 type.GetSignatureForError ());
241                                 }
242
243                                 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
244                                         context.Compiler.Report.Error (450, type_expr.Location,
245                                                 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
246                                                 type.GetSignatureForError ());
247                                 }
248
249                                 if (type == InternalType.Dynamic) {
250                                         context.Compiler.Report.Error (1967, constraint.Location, "A constraint cannot be the dynamic type");
251                                         continue;
252                                 }
253
254                                 if (type.IsSealed || !type.IsClass) {
255                                         context.Compiler.Report.Error (701, loc,
256                                                 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
257                                                 TypeManager.CSharpName (type));
258                                         continue;
259                                 }
260
261                                 if (type.IsStatic) {
262                                         context.Compiler.Report.Error (717, constraint.Location,
263                                                 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
264                                                 type.GetSignatureForError ());
265                                 } else if (type == TypeManager.array_type || type == TypeManager.delegate_type ||
266                                                         type == TypeManager.enum_type || type == TypeManager.value_type ||
267                                                         type == TypeManager.object_type || type == TypeManager.multicast_delegate_type) {
268                                         context.Compiler.Report.Error (702, constraint.Location,
269                                                 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
270                                         continue;
271                                 }
272
273                                 spec.BaseType = type;
274                         }
275
276                         if (tparam_types != null)
277                                 spec.TypeArguments = tparam_types.ToArray ();
278
279                         resolving = false;
280                         resolved = true;
281                         return true;
282                 }
283
284                 public void VerifyClsCompliance (Report report)
285                 {
286                         foreach (var c in constraints)
287                         {
288                                 if (c == null)
289                                         continue;
290
291                                 if (!c.Type.IsCLSCompliant ()) {
292                                         report.SymbolRelatedToPreviousError (c.Type);
293                                         report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
294                                                 c.Type.GetSignatureForError ());
295                                 }
296                         }
297                 }
298         }
299
300         //
301         // A type parameter for a generic type or generic method definition
302         //
303         public class TypeParameter : MemberCore, ITypeDefinition
304         {
305                 static readonly string[] attribute_target = new string [] { "type parameter" };
306                 
307                 Constraints constraints;
308                 GenericTypeParameterBuilder builder;
309                 TypeParameterSpec spec;
310
311                 public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
312                         : base (parent, name, attrs)
313                 {
314                         this.constraints = constraints;
315                         this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
316                 }
317
318                 public TypeParameter (TypeParameterSpec spec, DeclSpace parent, TypeSpec parentSpec, MemberName name, Attributes attrs)
319                         : base (parent, name, attrs)
320                 {
321                         this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
322                                 BaseType = spec.BaseType,
323                                 InterfacesDefined = spec.InterfacesDefined,
324                                 TypeArguments = spec.TypeArguments
325                         };
326                 }
327
328                 #region Properties
329
330                 public override AttributeTargets AttributeTargets {
331                         get {
332                                 return AttributeTargets.GenericParameter;
333                         }
334                 }
335
336                 public override string DocCommentHeader {
337                         get {
338                                 throw new InvalidOperationException (
339                                         "Unexpected attempt to get doc comment from " + this.GetType ());
340                         }
341                 }
342
343                 public bool IsMethodTypeParameter {
344                         get {
345                                 return spec.IsMethodOwned;
346                         }
347                 }
348
349                 public string Namespace {
350                         get {
351                                 return null;
352                         }
353                 }
354
355                 public TypeParameterSpec Type {
356                         get {
357                                 return spec;
358                         }
359                 }
360
361                 public int TypeParametersCount {
362                         get {
363                                 return 0;
364                         }
365                 }
366
367                 public TypeParameterSpec[] TypeParameters {
368                         get {
369                                 return null;
370                         }
371                 }
372
373                 public override string[] ValidAttributeTargets {
374                         get {
375                                 return attribute_target;
376                         }
377                 }
378
379                 public Variance Variance {
380                         get {
381                                 return spec.Variance;
382                         }
383                 }
384
385                 #endregion
386
387                 //
388                 // This is called for each part of a partial generic type definition.
389                 //
390                 // If partial type parameters constraints are not null and we don't
391                 // already have constraints they become our constraints. If we already
392                 // have constraints, we must check that they're the same.
393                 //
394                 public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
395                 {
396                         if (builder == null)
397                                 throw new InvalidOperationException ();
398
399                         var new_constraints = tp.constraints;
400                         if (new_constraints == null)
401                                 return true;
402
403                         // TODO: could create spec only
404                         //tp.Define (null, -1, part.Definition);
405                         tp.spec.DeclaringType = part.Definition;
406                         if (!tp.ResolveConstraints (part))
407                                 return false;
408
409                         if (constraints != null)
410                                 return spec.HasSameConstraintsDefinition (tp.Type);
411
412                         // Copy constraint from resolved part to partial container
413                         spec.SpecialConstraint = tp.spec.SpecialConstraint;
414                         spec.InterfacesDefined = tp.spec.InterfacesDefined;
415                         spec.TypeArguments = tp.spec.TypeArguments;
416                         spec.BaseType = tp.spec.BaseType;
417                         
418                         return true;
419                 }
420
421                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
422                 {
423                         builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
424                 }
425
426                 public void CheckGenericConstraints ()
427                 {
428                         if (constraints != null)
429                                 constraints.CheckGenericConstraints (this);
430                 }
431
432                 public TypeParameter CreateHoistedCopy (TypeContainer declaringType, TypeSpec declaringSpec)
433                 {
434                         return new TypeParameter (spec, declaringType, declaringSpec, MemberName, null);
435                 }
436
437                 public override bool Define ()
438                 {
439                         return true;
440                 }
441
442                 //
443                 // This is the first method which is called during the resolving
444                 // process; we're called immediately after creating the type parameters
445                 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
446                 // MethodBuilder).
447                 //
448                 public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
449                 {
450                         if (builder != null)
451                                 throw new InternalErrorException ();
452
453                         this.builder = type;
454                         spec.DeclaringType = declaringType;
455                         spec.SetMetaInfo (type);
456                 }
457
458                 public void EmitConstraints (GenericTypeParameterBuilder builder)
459                 {
460                         var attr = GenericParameterAttributes.None;
461                         if (spec.Variance == Variance.Contravariant)
462                                 attr |= GenericParameterAttributes.Contravariant;
463                         else if (spec.Variance == Variance.Covariant)
464                                 attr |= GenericParameterAttributes.Covariant;
465
466                         if (spec.HasSpecialClass)
467                                 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
468                         else if (spec.HasSpecialStruct)
469                                 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
470
471                         if (spec.HasSpecialConstructor)
472                                 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
473
474                         if (spec.BaseType != TypeManager.object_type)
475                                 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
476
477                         if (spec.InterfacesDefined != null)
478                                 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
479
480                         if (spec.TypeArguments != null)
481                                 builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
482
483                         builder.SetGenericParameterAttributes (attr);
484                 }
485
486                 public override void Emit ()
487                 {
488                         EmitConstraints (builder);
489
490                         if (OptAttributes != null)
491                                 OptAttributes.Emit ();
492
493                         base.Emit ();
494                 }
495
496                 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
497                 {
498                         Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
499                         string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
500                         string gtype_variance;
501                         switch (expected) {
502                         case Variance.Contravariant: gtype_variance = "contravariantly"; break;
503                         case Variance.Covariant: gtype_variance = "covariantly"; break;
504                         default: gtype_variance = "invariantly"; break;
505                         }
506
507                         Delegate d = mc as Delegate;
508                         string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
509
510                         Report.Error (1961, Location,
511                                 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
512                                         GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
513                 }
514
515                 public TypeSpec GetAttributeCoClass ()
516                 {
517                         return null;
518                 }
519
520                 public string GetAttributeDefaultMember ()
521                 {
522                         throw new NotSupportedException ();
523                 }
524
525                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
526                 {
527                         throw new NotSupportedException ();
528                 }
529
530                 public override string GetSignatureForError ()
531                 {
532                         return MemberName.Name;
533                 }
534
535                 public MemberCache LoadMembers (TypeSpec declaringType)
536                 {
537                         throw new NotSupportedException ("Not supported for compiled definition");
538                 }
539
540                 //
541                 // Resolves all type parameter constraints
542                 //
543                 public bool ResolveConstraints (IMemberContext context)
544                 {
545                         if (constraints != null)
546                                 return constraints.Resolve (context, this);
547
548                         if (spec.BaseType == null)
549                                 spec.BaseType = TypeManager.object_type;
550
551                         return true;
552                 }
553
554                 public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
555                 {
556                         foreach (var tp in tparams) {
557                                 if (tp.Name == name)
558                                         return tp;
559                         }
560
561                         return null;
562                 }
563
564                 public override bool IsClsComplianceRequired ()
565                 {
566                         return false;
567                 }
568
569                 public new void VerifyClsCompliance ()
570                 {
571                         if (constraints != null)
572                                 constraints.VerifyClsCompliance (Report);
573                 }
574         }
575
576         [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
577         public class TypeParameterSpec : TypeSpec
578         {
579                 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
580
581                 Variance variance;
582                 SpecialConstraint spec;
583                 readonly int tp_pos;
584                 TypeSpec[] targs;
585                 TypeSpec[] ifaces_defined;
586
587                 //
588                 // Creates type owned type parameter
589                 //
590                 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
591                         : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
592                 {
593                         this.variance = variance;
594                         this.spec = spec;
595                         state &= ~StateFlags.Obsolete_Undetected;
596                         tp_pos = index;
597                 }
598
599                 //
600                 // Creates method owned type parameter
601                 //
602                 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
603                         : this (null, index, definition, spec, variance, info)
604                 {
605                 }
606
607                 #region Properties
608
609                 public int DeclaredPosition {
610                         get {
611                                 return tp_pos;
612                         }
613                 }
614
615                 public bool HasSpecialConstructor {
616                         get {
617                                 return (spec & SpecialConstraint.Constructor) != 0;
618                         }
619                 }
620
621                 public bool HasSpecialClass {
622                         get {
623                                 return (spec & SpecialConstraint.Class) != 0;
624                         }
625                 }
626
627                 public bool HasSpecialStruct {
628                         get {
629                                 return (spec & SpecialConstraint.Struct) != 0;
630                         }
631                 }
632
633                 public bool HasTypeConstraint {
634                         get {
635                                 return BaseType != TypeManager.object_type && BaseType != TypeManager.value_type;
636                         }
637                 }
638
639                 public override IList<TypeSpec> Interfaces {
640                         get {
641                                 if ((state & StateFlags.InterfacesExpanded) == 0) {
642                                         if (ifaces != null) {
643                                                 for (int i = 0; i < ifaces.Count; ++i ) {
644                                                         var iface_type = ifaces[i];
645                                                         if (iface_type.Interfaces != null) {
646                                                                 if (ifaces_defined == null)
647                                                                         ifaces_defined = ifaces.ToArray ();
648
649                                                                 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
650                                                                         var ii_iface_type = iface_type.Interfaces [ii];
651
652                                                                         AddInterface (ii_iface_type);
653                                                                 }
654                                                         }
655                                                 }
656                                         }
657
658                                         if (ifaces_defined == null && ifaces != null)
659                                                 ifaces_defined = ifaces.ToArray ();
660
661                                         state |= StateFlags.InterfacesExpanded;
662                                 }
663
664                                 return ifaces;
665                         }
666                 }
667
668                 //
669                 // Unexpanded interfaces list
670                 //
671                 public TypeSpec[] InterfacesDefined {
672                         get {
673                                 if (ifaces_defined == null && ifaces != null)
674                                         ifaces_defined = ifaces.ToArray ();
675
676                                 return ifaces_defined;
677                         }
678                         set {
679                                 ifaces_defined = value;
680                         }
681                 }
682
683                 public bool IsConstrained {
684                         get {
685                                 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
686                         }
687                 }
688
689                 //
690                 // Returns whether the type parameter is "known to be a reference type"
691                 //
692                 public bool IsReferenceType {
693                         get {
694                                 return (spec & SpecialConstraint.Class) != 0 || HasTypeConstraint;
695                         }
696                 }
697
698                 public bool IsValueType {       // TODO: Do I need this ?
699                         get {
700                                 // TODO MemberCache: probably wrong
701                                 return HasSpecialStruct;
702                         }
703                 }
704
705                 public override string Name {
706                         get {
707                                 return definition.Name;
708                         }
709                 }
710
711                 public bool IsMethodOwned {
712                         get {
713                                 return DeclaringType == null;
714                         }
715                 }
716
717                 public SpecialConstraint SpecialConstraint {
718                         get {
719                                 return spec;
720                         }
721                         set {
722                                 spec = value;
723                         }
724                 }
725
726                 //
727                 // Types used to inflate the generic type
728                 //
729                 public new TypeSpec[] TypeArguments {
730                         get {
731                                 return targs;
732                         }
733                         set {
734                                 targs = value;
735                         }
736                 }
737
738                 public Variance Variance {
739                         get {
740                                 return variance;
741                         }
742                 }
743
744                 #endregion
745
746                 public string DisplayDebugInfo ()
747                 {
748                         var s = GetSignatureForError ();
749                         return IsMethodOwned ? s + "!!" : s + "!";
750                 }
751
752                 //
753                 // Finds effective base class
754                 //
755                 public TypeSpec GetEffectiveBase ()
756                 {
757                         if (HasSpecialStruct) {
758                                 return TypeManager.value_type;
759                         }
760
761                         if (BaseType != null && targs == null)
762                                 return BaseType;
763
764                         var types = targs;
765                         if (HasTypeConstraint) {
766                                 Array.Resize (ref types, types.Length + 1);
767                                 types[types.Length - 1] = BaseType;
768                         }
769
770                         if (types != null)
771                                 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
772
773                         return TypeManager.object_type;
774                 }
775
776                 public override string GetSignatureForError ()
777                 {
778                         return Name;
779                 }
780
781                 //
782                 // Constraints have to match by definition but not position, used by
783                 // partial classes or methods
784                 //
785                 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
786                 {
787                         if (spec != other.spec)
788                                 return false;
789
790                         if (BaseType != other.BaseType)
791                                 return false;
792
793                         if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
794                                 return false;
795
796                         if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
797                                 return false;
798
799                         return true;
800                 }
801
802                 //
803                 // Constraints have to match by using same set of types, used by
804                 // implicit interface implementation
805                 //
806                 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
807                 {
808                         if (spec != other.spec)
809                                 return false;
810
811                         //
812                         // It can be same base type or inflated type parameter
813                         //
814                         // interface I<T> { void Foo<U> where U : T; }
815                         // class A : I<int> { void Foo<X> where X : int {} }
816                         //
817                         bool found;
818                         if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
819                                 if (other.targs == null)
820                                         return false;
821
822                                 found = false;
823                                 foreach (var otarg in other.targs) {
824                                         if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
825                                                 found = true;
826                                                 break;
827                                         }
828                                 }
829
830                                 if (!found)
831                                         return false;
832                         }
833
834                         // Check interfaces implementation -> definition
835                         if (InterfacesDefined != null) {
836                                 foreach (var iface in InterfacesDefined) {
837                                         found = false;
838                                         if (other.InterfacesDefined != null) {
839                                                 foreach (var oiface in other.InterfacesDefined) {
840                                                         if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
841                                                                 found = true;
842                                                                 break;
843                                                         }
844                                                 }
845                                         }
846
847                                         if (found)
848                                                 continue;
849
850                                         if (other.targs != null) {
851                                                 foreach (var otarg in other.targs) {
852                                                         if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
853                                                                 found = true;
854                                                                 break;
855                                                         }
856                                                 }
857                                         }
858
859                                         if (!found)
860                                                 return false;
861                                 }
862                         }
863
864                         // Check interfaces implementation <- definition
865                         if (other.InterfacesDefined != null) {
866                                 if (InterfacesDefined == null)
867                                         return false;
868
869                                 foreach (var oiface in other.InterfacesDefined) {
870                                         found = false;
871                                         foreach (var iface in InterfacesDefined) {
872                                                 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
873                                                         found = true;
874                                                         break;
875                                                 }
876                                         }
877
878                                         if (!found)
879                                                 return false;
880                                 }
881                         }
882
883                         // Check type parameters implementation -> definition
884                         if (targs != null) {
885                                 if (other.targs == null)
886                                         return false;
887
888                                 foreach (var targ in targs) {
889                                         found = false;
890                                         foreach (var otarg in other.targs) {
891                                                 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
892                                                         found = true;
893                                                         break;
894                                                 }
895                                         }
896
897                                         if (!found)
898                                                 return false;
899                                 }
900                         }
901
902                         // Check type parameters implementation <- definition
903                         if (other.targs != null) {
904                                 foreach (var otarg in other.targs) {
905                                         // Ignore inflated type arguments, were checked above
906                                         if (!otarg.IsGenericParameter)
907                                                 continue;
908
909                                         if (targs == null)
910                                                 return false;
911
912                                         found = false;
913                                         foreach (var targ in targs) {
914                                                 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
915                                                         found = true;
916                                                         break;
917                                                 }
918                                         }
919
920                                         if (!found)
921                                                 return false;
922                                 }                               
923                         }
924
925                         return true;
926                 }
927
928                 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
929                 {
930                         TypeParameterSpec[] constraints = null;
931
932                         for (int i = 0; i < tparams.Length; ++i) {
933                                 var tp = tparams[i];
934                                 if (tp.HasTypeConstraint || tp.Interfaces != null || tp.TypeArguments != null) {
935                                         if (constraints == null) {
936                                                 constraints = new TypeParameterSpec[tparams.Length];
937                                                 Array.Copy (tparams, constraints, constraints.Length);
938                                         }
939
940                                         constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator);
941                                 }
942                         }
943
944                         if (constraints == null)
945                                 constraints = tparams;
946
947                         return constraints;
948                 }
949
950                 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
951                 {
952                         tps.BaseType = inflator.Inflate (BaseType);
953                         if (ifaces != null) {
954                                 tps.ifaces = new List<TypeSpec> (ifaces.Count);
955                                 for (int i = 0; i < ifaces.Count; ++i)
956                                         tps.ifaces.Add (inflator.Inflate (ifaces[i]));
957                         }
958                         if (targs != null) {
959                                 tps.targs = new TypeSpec[targs.Length];
960                                 for (int i = 0; i < targs.Length; ++i)
961                                         tps.targs[i] = inflator.Inflate (targs[i]);
962                         }
963                 }
964
965                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
966                 {
967                         var tps = (TypeParameterSpec) MemberwiseClone ();
968                         InflateConstraints (inflator, tps);
969                         return tps;
970                 }
971
972                 //
973                 // Populates type parameter members using type parameter constraints
974                 // The trick here is to be called late enough but not too late to
975                 // populate member cache with all members from other types
976                 //
977                 protected override void InitializeMemberCache (bool onlyTypes)
978                 {
979                         cache = new MemberCache ();
980                         if (ifaces != null) {
981                                 foreach (var iface_type in Interfaces) {
982                                         cache.AddInterface (iface_type);
983                                 }
984                         }
985                 }
986
987                 public bool IsConvertibleToInterface (TypeSpec iface)
988                 {
989                         if (Interfaces != null) {
990                                 foreach (var t in Interfaces) {
991                                         if (t == iface)
992                                                 return true;
993                                 }
994                         }
995
996                         if (TypeArguments != null) {
997                                 foreach (var t in TypeArguments) {
998                                         if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
999                                                 return true;
1000                                 }
1001                         }
1002
1003                         return false;
1004                 }
1005
1006                 public override TypeSpec Mutate (TypeParameterMutator mutator)
1007                 {
1008                         return mutator.Mutate (this);
1009                 }
1010         }
1011
1012         public struct TypeParameterInflator
1013         {
1014                 readonly TypeSpec type;
1015                 readonly TypeParameterSpec[] tparams;
1016                 readonly TypeSpec[] targs;
1017
1018                 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1019                         : this (type, nested.tparams, nested.targs)
1020                 {
1021                 }
1022
1023                 public TypeParameterInflator (TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1024                 {
1025                         if (tparams.Length != targs.Length)
1026                                 throw new ArgumentException ("Invalid arguments");
1027
1028                         this.tparams = tparams;
1029                         this.targs = targs;
1030                         this.type = type;
1031                 }
1032
1033                 //
1034                 // Type parameters to inflate
1035                 //
1036                 public TypeParameterSpec[] TypeParameters {
1037                         get {
1038                                 return tparams;
1039                         }
1040                 }
1041
1042                 public TypeSpec Inflate (TypeSpec ts)
1043                 {
1044                         var tp = ts as TypeParameterSpec;
1045                         if (tp != null)
1046                                 return Inflate (tp);
1047
1048                         var ac = ts as ArrayContainer;
1049                         if (ac != null) {
1050                                 var et = Inflate (ac.Element);
1051                                 if (et != ac.Element)
1052                                         return ArrayContainer.MakeType (et, ac.Rank);
1053
1054                                 return ac;
1055                         }
1056
1057                         //
1058                         // When inflating a nested type, inflate its parent first
1059                         // in case it's using same type parameters (was inflated within the type)
1060                         //
1061                         if (ts.IsNested) {
1062                                 var parent = Inflate (ts.DeclaringType);
1063                                 if (ts.DeclaringType != parent) {
1064                                         //
1065                                         // Keep the inflated type arguments
1066                                         // 
1067                                         var targs = ts.TypeArguments;
1068
1069                                         //
1070                                         // Parent was inflated, find the same type on inflated type
1071                                         // to use same cache for nested types on same generic parent
1072                                         //
1073                                         // TODO: Should use BindingRestriction.DeclaredOnly or GetMember
1074                                         ts = MemberCache.FindNestedType (parent, ts.Name, targs.Length);
1075
1076                                         //
1077                                         // Handle the tricky case where parent shares local type arguments
1078                                         // which means inflating inflated type
1079                                         //
1080                                         // class Test<T> {
1081                                         //              public static Nested<T> Foo () { return null; }
1082                                         //
1083                                         //              public class Nested<U> {}
1084                                         //      }
1085                                         //
1086                                         //  return type of Test<string>.Foo() has to be Test<string>.Nested<string> 
1087                                         //
1088                                         if (targs.Length > 0) {
1089                                                 var inflated_targs = new TypeSpec [targs.Length];
1090                                                 for (var i = 0; i < targs.Length; ++i)
1091                                                         inflated_targs[i] = Inflate (targs[i]);
1092
1093                                                 ts = ts.MakeGenericType (inflated_targs);
1094                                         }
1095
1096                                         return ts;
1097                                 }
1098                         }
1099
1100                         // Inflate generic type
1101                         if (ts.Arity > 0)
1102                                 return InflateTypeParameters (ts);
1103
1104                         return ts;
1105                 }
1106
1107                 public TypeSpec Inflate (TypeParameterSpec tp)
1108                 {
1109                         for (int i = 0; i < tparams.Length; ++i)
1110                                 if (tparams [i] == tp)
1111                                         return targs[i];
1112
1113                         // This can happen when inflating nested types
1114                         // without type arguments specified
1115                         return tp;
1116                 }
1117
1118                 //
1119                 // Inflates generic types
1120                 //
1121                 TypeSpec InflateTypeParameters (TypeSpec type)
1122                 {
1123                         var targs = new TypeSpec[type.Arity];
1124                         var i = 0;
1125
1126                         var gti = type as InflatedTypeSpec;
1127
1128                         //
1129                         // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1130                         //
1131                         if (gti != null) {
1132                                 for (; i < targs.Length; ++i)
1133                                         targs[i] = Inflate (gti.TypeArguments[i]);
1134
1135                                 return gti.GetDefinition ().MakeGenericType (targs);
1136                         }
1137
1138                         //
1139                         // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1140                         //
1141                         var args = type.MemberDefinition.TypeParameters;
1142                         foreach (var ds_tp in args)
1143                                 targs[i++] = Inflate (ds_tp);
1144
1145                         return type.MakeGenericType (targs);
1146                 }
1147
1148                 public TypeSpec TypeInstance {
1149                         get { return type; }
1150                 }
1151         }
1152
1153         //
1154         // Before emitting any code we have to change all MVAR references to VAR
1155         // when the method is of generic type and has hoisted variables
1156         //
1157         public class TypeParameterMutator
1158         {
1159                 TypeParameter[] mvar;
1160                 TypeParameter[] var;
1161                 Dictionary<TypeSpec, TypeSpec> mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1162
1163                 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1164                 {
1165                         if (mvar.Length != var.Length)
1166                                 throw new ArgumentException ();
1167
1168                         this.mvar = mvar;
1169                         this.var = var;
1170                 }
1171
1172                 public TypeSpec Mutate (TypeSpec ts)
1173                 {
1174                         TypeSpec value;
1175                         if (mutated_typespec.TryGetValue (ts, out value))
1176                                 return value;
1177
1178                         value = ts.Mutate (this);
1179                         mutated_typespec.Add (ts, value);
1180                         return value;
1181                 }
1182
1183                 public FieldInfo Mutate (FieldSpec fs)
1184                 {
1185                         // TODO:
1186                         return fs.GetMetaInfo ();
1187                 }
1188
1189                 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1190                 {
1191                         for (int i = 0; i < mvar.Length; ++i) {
1192                                 if (mvar[i].Type == tp)
1193                                         return var[i].Type;
1194                         }
1195
1196                         return tp;
1197                 }
1198
1199                 public TypeSpec[] Mutate (TypeSpec[] targs)
1200                 {
1201                         TypeSpec[] mutated = new TypeSpec[targs.Length];
1202                         bool changed = false;
1203                         for (int i = 0; i < targs.Length; ++i) {
1204                                 mutated[i] = Mutate (targs[i]);
1205                                 changed |= targs[i] != mutated[i];
1206                         }
1207
1208                         return changed ? mutated : targs;
1209                 }
1210         }
1211
1212         /// <summary>
1213         ///   A TypeExpr which already resolved to a type parameter.
1214         /// </summary>
1215         public class TypeParameterExpr : TypeExpr {
1216                 
1217                 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1218                 {
1219                         this.type = type_parameter.Type;
1220                         this.eclass = ExprClass.TypeParameter;
1221                         this.loc = loc;
1222                 }
1223
1224                 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1225                 {
1226                         throw new NotSupportedException ();
1227                 }
1228
1229                 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1230                 {
1231                         return this;
1232                 }
1233
1234                 public override bool CheckAccessLevel (IMemberContext ds)
1235                 {
1236                         return true;
1237                 }
1238         }
1239
1240         public class InflatedTypeSpec : TypeSpec
1241         {
1242                 TypeSpec[] targs;
1243                 TypeParameterSpec[] constraints;
1244                 readonly TypeSpec open_type;
1245
1246                 public InflatedTypeSpec (TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1247                         : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1248                 {
1249                         if (targs == null)
1250                                 throw new ArgumentNullException ("targs");
1251
1252 //                      this.state = openType.state;
1253                         this.open_type = openType;
1254                         this.targs = targs;
1255                 }
1256
1257                 #region Properties
1258
1259                 public override TypeSpec BaseType {
1260                         get {
1261                                 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1262                                         InitializeMemberCache (true);
1263
1264                                 return base.BaseType;
1265                         }
1266                 }
1267
1268                 //
1269                 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1270                 //
1271                 public TypeParameterSpec[] Constraints {
1272                         get {
1273                                 if (constraints == null) {
1274                                         var inflator = new TypeParameterInflator (this, MemberDefinition.TypeParameters, targs);
1275                                         constraints = TypeParameterSpec.InflateConstraints (inflator, MemberDefinition.TypeParameters);
1276                                 }
1277
1278                                 return constraints;
1279                         }
1280                 }
1281
1282                 public override IList<TypeSpec> Interfaces {
1283                         get {
1284                                 if (cache == null)
1285                                         InitializeMemberCache (true);
1286
1287                                 return base.Interfaces;
1288                         }
1289                 }
1290
1291                 public override MemberCache MemberCacheTypes {
1292                         get {
1293                                 if (cache == null)
1294                                         InitializeMemberCache (true);
1295
1296                                 return cache;
1297                         }
1298                 }
1299
1300                 //
1301                 // Types used to inflate the generic  type
1302                 //
1303                 public override TypeSpec[] TypeArguments {
1304                         get {
1305                                 return targs;
1306                         }
1307                 }
1308
1309                 #endregion
1310
1311                 Type CreateMetaInfo (TypeParameterMutator mutator)
1312                 {
1313                         //
1314                         // Converts nested type arguments into right order
1315                         // Foo<string, bool>.Bar<int> => string, bool, int
1316                         //
1317                         var all = new List<Type> ();
1318                         TypeSpec type = this;
1319                         TypeSpec definition = type;
1320                         do {
1321                                 if (type.GetDefinition().IsGeneric) {
1322                                         all.InsertRange (0,
1323                                                 type.TypeArguments != TypeSpec.EmptyTypes ?
1324                                                 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1325                                                 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1326                                 }
1327
1328                                 definition = definition.GetDefinition ();
1329                                 type = type.DeclaringType;
1330                         } while (type != null);
1331
1332                         return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1333                 }
1334
1335                 public override ObsoleteAttribute GetAttributeObsolete ()
1336                 {
1337                         return open_type.GetAttributeObsolete ();
1338                 }
1339
1340                 protected override bool IsNotCLSCompliant ()
1341                 {
1342                         if (base.IsNotCLSCompliant ())
1343                                 return true;
1344
1345                         foreach (var ta in TypeArguments) {
1346                                 if (ta.MemberDefinition.IsNotCLSCompliant ())
1347                                         return true;
1348                         }
1349
1350                         return false;
1351                 }
1352
1353                 public override TypeSpec GetDefinition ()
1354                 {
1355                         return open_type;
1356                 }
1357
1358                 public override Type GetMetaInfo ()
1359                 {
1360                         if (info == null)
1361                                 info = CreateMetaInfo (null);
1362
1363                         return info;
1364                 }
1365
1366                 public override string GetSignatureForError ()
1367                 {
1368                         if (TypeManager.IsNullableType (open_type))
1369                                 return targs[0].GetSignatureForError () + "?";
1370
1371                         if (MemberDefinition is AnonymousTypeClass)
1372                                 return ((AnonymousTypeClass) MemberDefinition).GetSignatureForError ();
1373
1374                         return base.GetSignatureForError ();
1375                 }
1376
1377                 protected override string GetTypeNameSignature ()
1378                 {
1379                         if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1380                                 return null;
1381
1382                         return "<" + TypeManager.CSharpName (targs) + ">";
1383                 }
1384
1385                 protected override void InitializeMemberCache (bool onlyTypes)
1386                 {
1387                         if (cache == null)
1388                                 cache = new MemberCache (onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache);
1389
1390                         TypeParameterSpec[] tparams_full;
1391                         TypeSpec[] targs_full = targs;
1392                         if (IsNested) {
1393                                 //
1394                                 // Special case is needed when we are inflating an open type (nested type definition)
1395                                 // on inflated parent. Consider following case
1396                                 //
1397                                 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1398                                 //
1399                                 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1400                                 //
1401                                 List<TypeSpec> merged_targs = null;
1402                                 List<TypeParameterSpec> merged_tparams = null;
1403
1404                                 var type = DeclaringType;
1405
1406                                 do {
1407                                         if (type.TypeArguments.Length > 0) {
1408                                                 if (merged_targs == null) {
1409                                                         merged_targs = new List<TypeSpec> ();
1410                                                         merged_tparams = new List<TypeParameterSpec> ();
1411                                                         if (targs.Length > 0) {
1412                                                                 merged_targs.AddRange (targs);
1413                                                                 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1414                                                         }
1415                                                 }
1416                                                 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1417                                                 merged_targs.AddRange (type.TypeArguments);
1418                                         }
1419                                         type = type.DeclaringType;
1420                                 } while (type != null);
1421
1422                                 if (merged_targs != null) {
1423                                         // Type arguments are not in the right order but it should not matter in this case
1424                                         targs_full = merged_targs.ToArray ();
1425                                         tparams_full = merged_tparams.ToArray ();
1426                                 } else if (targs.Length == 0) {
1427                                         tparams_full = TypeParameterSpec.EmptyTypes;
1428                                 } else {
1429                                         tparams_full = open_type.MemberDefinition.TypeParameters;
1430                                 }
1431                         } else if (targs.Length == 0) {
1432                                 tparams_full = TypeParameterSpec.EmptyTypes;
1433                         } else {
1434                                 tparams_full = open_type.MemberDefinition.TypeParameters;
1435                         }
1436
1437                         var inflator = new TypeParameterInflator (this, tparams_full, targs_full);
1438
1439                         //
1440                         // Two stage inflate due to possible nested types recursive
1441                         // references
1442                         //
1443                         // class A<T> {
1444                         //    B b;
1445                         //    class B {
1446                         //      T Value;
1447                         //    }
1448                         // }
1449                         //
1450                         // When resolving type of `b' members of `B' cannot be 
1451                         // inflated because are not yet available in membercache
1452                         //
1453                         if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1454                                 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1455
1456                                 //
1457                                 // Inflate any implemented interfaces
1458                                 //
1459                                 if (open_type.Interfaces != null) {
1460                                         ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1461                                         foreach (var iface in open_type.Interfaces) {
1462                                                 var iface_inflated = inflator.Inflate (iface);
1463                                                 AddInterface (iface_inflated);
1464                                         }
1465                                 }
1466
1467                                 //
1468                                 // Handles the tricky case of recursive nested base generic type
1469                                 //
1470                                 // class A<T> : Base<A<T>.Nested> {
1471                                 //    class Nested {}
1472                                 // }
1473                                 //
1474                                 // When inflating A<T>. base type is not yet known, secondary
1475                                 // inflation is required (not common case) once base scope
1476                                 // is known
1477                                 //
1478                                 if (open_type.BaseType == null) {
1479                                         if (IsClass)
1480                                                 state |= StateFlags.PendingBaseTypeInflate;
1481                                 } else {
1482                                         BaseType = inflator.Inflate (open_type.BaseType);
1483                                 }
1484                         } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1485                                 BaseType = inflator.Inflate (open_type.BaseType);
1486                                 state &= ~StateFlags.PendingBaseTypeInflate;
1487                         }
1488
1489                         if (onlyTypes) {
1490                                 state |= StateFlags.PendingMemberCacheMembers;
1491                                 return;
1492                         }
1493
1494                         var tc = open_type.MemberDefinition as TypeContainer;
1495                         if (tc != null && !tc.HasMembersDefined)
1496                                 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1497
1498                         if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1499                                 BaseType = inflator.Inflate (open_type.BaseType);
1500                                 state &= ~StateFlags.PendingBaseTypeInflate;
1501                         }
1502
1503                         state &= ~StateFlags.PendingMemberCacheMembers;
1504                         open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1505                 }
1506
1507                 public override TypeSpec Mutate (TypeParameterMutator mutator)
1508                 {
1509                         var targs = TypeArguments;
1510                         if (targs != null)
1511                                 targs = mutator.Mutate (targs);
1512
1513                         var decl = DeclaringType;
1514                         if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1515                                 decl = mutator.Mutate (decl);
1516
1517                         if (targs == TypeArguments && decl == DeclaringType)
1518                                 return this;
1519
1520                         var mutated = (InflatedTypeSpec) MemberwiseClone ();
1521                         if (decl != DeclaringType) {
1522                                 // Gets back MethodInfo in case of metaInfo was inflated
1523                                 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1524
1525                                 mutated.declaringType = decl;
1526                                 mutated.state |= StateFlags.PendingMetaInflate;
1527                         }
1528
1529                         if (targs != null) {
1530                                 mutated.targs = targs;
1531                                 mutated.info = null;
1532                         }
1533
1534                         return mutated;
1535                 }
1536         }
1537
1538
1539         //
1540         // Tracks the type arguments when instantiating a generic type. It's used
1541         // by both type arguments and type parameters
1542         //
1543         public class TypeArguments
1544         {
1545                 List<FullNamedExpression> args;
1546                 TypeSpec[] atypes;
1547
1548                 public TypeArguments (params FullNamedExpression[] types)
1549                 {
1550                         this.args = new List<FullNamedExpression> (types);
1551                 }
1552
1553                 public void Add (FullNamedExpression type)
1554                 {
1555                         args.Add (type);
1556                 }
1557
1558                 // TODO: Kill this monster
1559                 public TypeParameterName[] GetDeclarations ()
1560                 {
1561                         return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1562                 }
1563
1564                 /// <summary>
1565                 ///   We may only be used after Resolve() is called and return the fully
1566                 ///   resolved types.
1567                 /// </summary>
1568                 // TODO: Not needed, just return type from resolve
1569                 public TypeSpec[] Arguments {
1570                         get {
1571                                 return atypes;
1572                         }
1573                 }
1574
1575                 public int Count {
1576                         get {
1577                                 return args.Count;
1578                         }
1579                 }
1580
1581                 public virtual bool IsEmpty {
1582                         get {
1583                                 return false;
1584                         }
1585                 }
1586
1587                 public string GetSignatureForError()
1588                 {
1589                         StringBuilder sb = new StringBuilder ();
1590                         for (int i = 0; i < Count; ++i) {
1591                                 var expr = args[i];
1592                                 if (expr != null)
1593                                         sb.Append (expr.GetSignatureForError ());
1594
1595                                 if (i + 1 < Count)
1596                                         sb.Append (',');
1597                         }
1598
1599                         return sb.ToString ();
1600                 }
1601
1602                 /// <summary>
1603                 ///   Resolve the type arguments.
1604                 /// </summary>
1605                 public virtual bool Resolve (IMemberContext ec)
1606                 {
1607                         if (atypes != null)
1608                             return atypes.Length != 0;
1609
1610                         int count = args.Count;
1611                         bool ok = true;
1612
1613                         atypes = new TypeSpec [count];
1614
1615                         for (int i = 0; i < count; i++){
1616                                 TypeExpr te = args[i].ResolveAsTypeTerminal (ec, false);
1617                                 if (te == null) {
1618                                         ok = false;
1619                                         continue;
1620                                 }
1621
1622                                 atypes[i] = te.Type;
1623
1624                                 if (te.Type.IsStatic) {
1625                                         ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1626                                                 te.GetSignatureForError ());
1627                                         ok = false;
1628                                 }
1629
1630                                 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1631                                         ec.Compiler.Report.Error (306, te.Location,
1632                                                 "The type `{0}' may not be used as a type argument",
1633                                                 te.GetSignatureForError ());
1634                                         ok = false;
1635                                 }
1636                         }
1637
1638                         if (!ok)
1639                                 atypes = TypeSpec.EmptyTypes;
1640
1641                         return ok;
1642                 }
1643
1644                 public TypeArguments Clone ()
1645                 {
1646                         TypeArguments copy = new TypeArguments ();
1647                         foreach (var ta in args)
1648                                 copy.args.Add (ta);
1649
1650                         return copy;
1651                 }
1652         }
1653
1654         public class UnboundTypeArguments : TypeArguments
1655         {
1656                 public UnboundTypeArguments (int arity)
1657                         : base (new FullNamedExpression[arity])
1658                 {
1659                 }
1660
1661                 public override bool IsEmpty {
1662                         get {
1663                                 return true;
1664                         }
1665                 }
1666
1667                 public override bool Resolve (IMemberContext ec)
1668                 {
1669                         // Nothing to be resolved
1670                         return true;
1671                 }
1672         }
1673
1674         public class TypeParameterName : SimpleName
1675         {
1676                 Attributes attributes;
1677                 Variance variance;
1678
1679                 public TypeParameterName (string name, Attributes attrs, Location loc)
1680                         : this (name, attrs, Variance.None, loc)
1681                 {
1682                 }
1683
1684                 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1685                         : base (name, loc)
1686                 {
1687                         attributes = attrs;
1688                         this.variance = variance;
1689                 }
1690
1691                 public Attributes OptAttributes {
1692                         get {
1693                                 return attributes;
1694                         }
1695                 }
1696
1697                 public Variance Variance {
1698                         get {
1699                                 return variance;
1700                         }
1701                 }
1702         }
1703
1704         //
1705         // A type expression of generic type with type arguments
1706         //
1707         class GenericTypeExpr : TypeExpr
1708         {
1709                 TypeArguments args;
1710                 TypeSpec open_type;
1711                 bool constraints_checked;
1712
1713                 /// <summary>
1714                 ///   Instantiate the generic type `t' with the type arguments `args'.
1715                 ///   Use this constructor if you already know the fully resolved
1716                 ///   generic type.
1717                 /// </summary>          
1718                 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1719                 {
1720                         this.open_type = open_type;
1721                         loc = l;
1722                         this.args = args;
1723                 }
1724
1725                 public TypeArguments TypeArguments {
1726                         get { return args; }
1727                 }
1728
1729                 public override string GetSignatureForError ()
1730                 {
1731                         return TypeManager.CSharpName (type);
1732                 }
1733
1734                 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1735                 {
1736                         if (!args.Resolve (ec))
1737                                 return null;
1738
1739                         TypeSpec[] atypes = args.Arguments;
1740
1741                         //
1742                         // Now bind the parameters
1743                         //
1744                         type = open_type.MakeGenericType (atypes);
1745
1746                         //
1747                         // Check constraints when context is not method/base type
1748                         //
1749                         if (!ec.HasUnresolvedConstraints)
1750                                 CheckConstraints (ec);
1751
1752                         return this;
1753                 }
1754
1755                 //
1756                 // Checks the constraints of open generic type against type
1757                 // arguments. Has to be called onafter all members are defined
1758                 //
1759                 public bool CheckConstraints (IMemberContext ec)
1760                 {
1761                         if (constraints_checked)
1762                                 return true;
1763
1764                         constraints_checked = true;
1765
1766                         var gtype = (InflatedTypeSpec) type;
1767                         var constraints = gtype.Constraints;
1768                         if (constraints == null)
1769                                 return true;
1770
1771                         return ConstraintChecker.CheckAll (ec, open_type, args.Arguments, constraints, loc);
1772                 }
1773         
1774                 public override bool CheckAccessLevel (IMemberContext mc)
1775                 {
1776                         DeclSpace c = mc.CurrentMemberDefinition as DeclSpace;
1777                         if (c == null)
1778                                 c = mc.CurrentMemberDefinition.Parent;
1779
1780                         return c.CheckAccessLevel (open_type);
1781                 }
1782
1783                 public bool HasDynamicArguments ()
1784                 {
1785                         return HasDynamicArguments (args.Arguments);
1786                 }
1787
1788                 static bool HasDynamicArguments (TypeSpec[] args)
1789                 {
1790                         foreach (var item in args) {
1791                                 if (item == InternalType.Dynamic)
1792                                         return true;
1793
1794                                 if (TypeManager.IsGenericType (item))
1795                                         return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1796                         }
1797
1798                         return false;
1799                 }
1800
1801                 public override bool Equals (object obj)
1802                 {
1803                         GenericTypeExpr cobj = obj as GenericTypeExpr;
1804                         if (cobj == null)
1805                                 return false;
1806
1807                         if ((type == null) || (cobj.type == null))
1808                                 return false;
1809
1810                         return type == cobj.type;
1811                 }
1812
1813                 public override int GetHashCode ()
1814                 {
1815                         return base.GetHashCode ();
1816                 }
1817         }
1818
1819         //
1820         // Generic type with unbound type arguments, used for typeof (G<,,>)
1821         //
1822         class GenericOpenTypeExpr : TypeExpr
1823         {
1824                 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
1825                 {
1826                         this.type = type.GetDefinition ();
1827                         this.loc = loc;
1828                 }
1829
1830                 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1831                 {
1832                         return this;
1833                 }
1834         }
1835
1836         static class ConstraintChecker
1837         {
1838                 /// <summary>
1839                 ///   Check the constraints; we're called from ResolveAsTypeTerminal()
1840                 ///   after fully resolving the constructed type.
1841                 /// </summary>
1842                 public static bool CheckAll (IMemberContext mc, MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
1843                 {
1844                         for (int i = 0; i < tparams.Length; i++) {
1845                                 if (!CheckConstraint (mc, context, targs [i], tparams [i], loc))
1846                                         return false;
1847                         }
1848
1849                         return true;
1850                 }
1851
1852                 static bool CheckConstraint (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
1853                 {
1854                         //
1855                         // First, check the `class' and `struct' constraints.
1856                         //
1857                         if (tparam.HasSpecialClass && !TypeManager.IsReferenceType (atype)) {
1858                                 mc.Compiler.Report.Error (452, loc,
1859                                         "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
1860                                         TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1861                                 return false;
1862                         }
1863
1864                         if (tparam.HasSpecialStruct && (!TypeManager.IsValueType (atype) || TypeManager.IsNullableType (atype))) {
1865                                 mc.Compiler.Report.Error (453, loc,
1866                                         "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}'",
1867                                         TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1868                                 return false;
1869                         }
1870
1871                         //
1872                         // The class constraint comes next.
1873                         //
1874                         if (tparam.HasTypeConstraint) {
1875                                 CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc);
1876                         }
1877
1878                         //
1879                         // Now, check the interfaces and type parameters constraints
1880                         //
1881                         if (tparam.Interfaces != null) {
1882                                 if (TypeManager.IsNullableType (atype)) {
1883                                         mc.Compiler.Report.Error (313, loc,
1884                                                 "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",
1885                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
1886                                 } else {
1887                                         foreach (TypeSpec iface in tparam.Interfaces) {
1888                                                 CheckConversion (mc, context, atype, tparam, iface, loc);
1889                                         }
1890                                 }
1891                         }
1892
1893                         //
1894                         // Finally, check the constructor constraint.
1895                         //
1896                         if (!tparam.HasSpecialConstructor)
1897                                 return true;
1898
1899                         if (!HasDefaultConstructor (atype)) {
1900                                 mc.Compiler.Report.SymbolRelatedToPreviousError (atype);
1901                                 mc.Compiler.Report.Error (310, loc,
1902                                         "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
1903                                         TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1904                                 return false;
1905                         }
1906
1907                         return true;
1908                 }
1909
1910                 static void CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
1911                 {
1912                         var expr = new EmptyExpression (atype);
1913                         if (!Convert.ImplicitStandardConversionExists (expr, ttype)) {
1914                                 mc.Compiler.Report.SymbolRelatedToPreviousError (tparam);
1915                                 if (TypeManager.IsValueType (atype)) {
1916                                         mc.Compiler.Report.Error (315, loc, "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing conversion from `{0}' to `{3}'",
1917                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
1918                                 } else if (atype.IsGenericParameter) {
1919                                         mc.Compiler.Report.Error (314, loc, "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing or type parameter conversion from `{0}' to `{3}'",
1920                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
1921                                 } else {
1922                                         mc.Compiler.Report.Error (311, loc, "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'",
1923                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
1924                                 }
1925                         }
1926                 }
1927
1928                 static bool HasDefaultConstructor (TypeSpec atype)
1929                 {
1930                         var tp = atype as TypeParameterSpec;
1931                         if (tp != null) {
1932                                 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
1933                         }
1934
1935                         if (atype.IsStruct || atype.IsEnum)
1936                                 return true;
1937
1938                         if (atype.IsAbstract)
1939                                 return false;
1940
1941                         var tdef = atype.GetDefinition ();
1942
1943                         //
1944                         // In some circumstances MemberCache is not yet populated and members
1945                         // cannot be defined yet (recursive type new constraints)
1946                         //
1947                         // class A<T> where T : B<T>, new () {}
1948                         // class B<T> where T : A<T>, new () {}
1949                         //
1950                         var tc = tdef.MemberDefinition as Class;
1951                         if (tc != null) {
1952                                 if (tc.InstanceConstructors == null) {
1953                                         // Default ctor will be generated later
1954                                         return true;
1955                                 }
1956
1957                                 foreach (var c in tc.InstanceConstructors) {
1958                                         if (c.ParameterInfo.IsEmpty) {
1959                                                 if ((c.ModFlags & Modifiers.PUBLIC) != 0)
1960                                                         return true;
1961                                         }
1962                                 }
1963
1964                                 return false;
1965                         }
1966
1967                         var found = MemberCache.FindMember (tdef,
1968                                 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
1969                                 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
1970
1971                         return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
1972                 }
1973         }
1974
1975         /// <summary>
1976         ///   A generic method definition.
1977         /// </summary>
1978         public class GenericMethod : DeclSpace
1979         {
1980                 ParametersCompiled parameters;
1981
1982                 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1983                                       FullNamedExpression return_type, ParametersCompiled parameters)
1984                         : base (ns, parent, name, null)
1985                 {
1986                         this.parameters = parameters;
1987                 }
1988
1989                 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
1990                                           FullNamedExpression return_type, ParametersCompiled parameters)
1991                         : this (ns, parent, name, return_type, parameters)
1992                 {
1993                         this.type_params = tparams;
1994                 }
1995
1996                 public override TypeParameter[] CurrentTypeParameters {
1997                         get {
1998                                 return base.type_params;
1999                         }
2000                 }
2001
2002                 public override TypeBuilder DefineType ()
2003                 {
2004                         throw new Exception ();
2005                 }
2006
2007                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2008                 {
2009                         throw new NotSupportedException ();
2010                 }
2011
2012                 public override bool Define ()
2013                 {
2014                         throw new NotSupportedException ();
2015                 }
2016
2017                 /// <summary>
2018                 ///   Define and resolve the type parameters.
2019                 ///   We're called from Method.Define().
2020                 /// </summary>
2021                 public bool Define (MethodOrOperator m)
2022                 {
2023                         TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2024                         string[] snames = new string [names.Length];
2025                         for (int i = 0; i < names.Length; i++) {
2026                                 string type_argument_name = names[i].Name;
2027                                 int idx = parameters.GetParameterIndexByName (type_argument_name);
2028
2029                                 if (idx >= 0) {
2030                                         var b = m.Block;
2031                                         if (b == null)
2032                                                 b = new ToplevelBlock (Compiler, Location);
2033
2034                                         b.Error_AlreadyDeclaredTypeParameter (parameters [i].Location,
2035                                                 type_argument_name, "method parameter");
2036                                 }
2037
2038                                 if (m.Block != null) {
2039                                         var ikv = m.Block.GetKnownVariable (type_argument_name);
2040                                         if (ikv != null)
2041                                                 ikv.Block.Error_AlreadyDeclaredTypeParameter (ikv.Location, type_argument_name, "local variable");
2042                                 }
2043                                 
2044                                 snames[i] = type_argument_name;
2045                         }
2046
2047                         GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2048                         for (int i = 0; i < TypeParameters.Length; i++)
2049                                 TypeParameters [i].Define (gen_params [i], null);
2050
2051                         return true;
2052                 }
2053
2054                 public void EmitAttributes ()
2055                 {
2056                         if (OptAttributes != null)
2057                                 OptAttributes.Emit ();
2058                 }
2059
2060                 public override string GetSignatureForError ()
2061                 {
2062                         return base.GetSignatureForError () + parameters.GetSignatureForError ();
2063                 }
2064
2065                 public override AttributeTargets AttributeTargets {
2066                         get {
2067                                 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2068                         }
2069                 }
2070
2071                 public override string DocCommentHeader {
2072                         get { return "M:"; }
2073                 }
2074
2075                 public new void VerifyClsCompliance ()
2076                 {
2077                         foreach (TypeParameter tp in TypeParameters) {
2078                                 tp.VerifyClsCompliance ();
2079                         }
2080                 }
2081         }
2082
2083         public partial class TypeManager
2084         {
2085                 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2086                 {
2087                         var tp = t as TypeParameterSpec;
2088                         if (tp != null) {
2089                                 Variance v = tp.Variance;
2090                                 if (expected == Variance.None && v != expected ||
2091                                         expected == Variance.Covariant && v == Variance.Contravariant ||
2092                                         expected == Variance.Contravariant && v == Variance.Covariant) {
2093                                         ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2094                                 }
2095
2096                                 return expected;
2097                         }
2098
2099                         if (t.TypeArguments.Length > 0) {
2100                                 var targs_definition = t.MemberDefinition.TypeParameters;
2101                                 TypeSpec[] targs = GetTypeArguments (t);
2102                                 for (int i = 0; i < targs.Length; ++i) {
2103                                         Variance v = targs_definition[i].Variance;
2104                                         CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2105                                 }
2106
2107                                 return expected;
2108                         }
2109
2110                         if (t.IsArray)
2111                                 return CheckTypeVariance (GetElementType (t), expected, member);
2112
2113                         return Variance.None;
2114                 }
2115
2116                 /// <summary>
2117                 ///   Type inference.  Try to infer the type arguments from `method',
2118                 ///   which is invoked with the arguments `arguments'.  This is used
2119                 ///   when resolving an Invocation or a DelegateInvocation and the user
2120                 ///   did not explicitly specify type arguments.
2121                 /// </summary>
2122                 public static int InferTypeArguments (ResolveContext ec, Arguments arguments, ref MethodSpec method)
2123                 {
2124                         ATypeInference ti = ATypeInference.CreateInstance (arguments);
2125                         TypeSpec[] i_args = ti.InferMethodArguments (ec, method);
2126                         if (i_args == null)
2127                                 return ti.InferenceScore;
2128
2129                         if (i_args.Length == 0)
2130                                 return 0;
2131
2132                         method = method.MakeGenericMethod (i_args);
2133                         return 0;
2134                 }
2135         }
2136
2137         abstract class ATypeInference
2138         {
2139                 protected readonly Arguments arguments;
2140                 protected readonly int arg_count;
2141
2142                 protected ATypeInference (Arguments arguments)
2143                 {
2144                         this.arguments = arguments;
2145                         if (arguments != null)
2146                                 arg_count = arguments.Count;
2147                 }
2148
2149                 public static ATypeInference CreateInstance (Arguments arguments)
2150                 {
2151                         return new TypeInference (arguments);
2152                 }
2153
2154                 public virtual int InferenceScore {
2155                         get {
2156                                 return int.MaxValue;
2157                         }
2158                 }
2159
2160                 public abstract TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method);
2161         }
2162
2163         //
2164         // Implements C# type inference
2165         //
2166         class TypeInference : ATypeInference
2167         {
2168                 //
2169                 // Tracks successful rate of type inference
2170                 //
2171                 int score = int.MaxValue;
2172
2173                 public TypeInference (Arguments arguments)
2174                         : base (arguments)
2175                 {
2176                 }
2177
2178                 public override int InferenceScore {
2179                         get {
2180                                 return score;
2181                         }
2182                 }
2183
2184                 public override TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2185                 {
2186                         var method_generic_args = method.GenericDefinition.TypeParameters;
2187                         TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2188                         if (!context.UnfixedVariableExists)
2189                                 return TypeSpec.EmptyTypes;
2190
2191                         AParametersCollection pd = method.Parameters;
2192                         if (!InferInPhases (ec, context, pd))
2193                                 return null;
2194
2195                         return context.InferredTypeArguments;
2196                 }
2197
2198                 //
2199                 // Implements method type arguments inference
2200                 //
2201                 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2202                 {
2203                         int params_arguments_start;
2204                         if (methodParameters.HasParams) {
2205                                 params_arguments_start = methodParameters.Count - 1;
2206                         } else {
2207                                 params_arguments_start = arg_count;
2208                         }
2209
2210                         TypeSpec [] ptypes = methodParameters.Types;
2211                         
2212                         //
2213                         // The first inference phase
2214                         //
2215                         TypeSpec method_parameter = null;
2216                         for (int i = 0; i < arg_count; i++) {
2217                                 Argument a = arguments [i];
2218                                 if (a == null)
2219                                         continue;
2220                                 
2221                                 if (i < params_arguments_start) {
2222                                         method_parameter = methodParameters.Types [i];
2223                                 } else if (i == params_arguments_start) {
2224                                         if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2225                                                 method_parameter = methodParameters.Types [params_arguments_start];
2226                                         else
2227                                                 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2228
2229                                         ptypes = (TypeSpec[]) ptypes.Clone ();
2230                                         ptypes [i] = method_parameter;
2231                                 }
2232
2233                                 //
2234                                 // When a lambda expression, an anonymous method
2235                                 // is used an explicit argument type inference takes a place
2236                                 //
2237                                 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2238                                 if (am != null) {
2239                                         if (am.ExplicitTypeInference (ec, tic, method_parameter))
2240                                                 --score; 
2241                                         continue;
2242                                 }
2243
2244                                 if (a.IsByRef) {
2245                                         score -= tic.ExactInference (a.Type, method_parameter);
2246                                         continue;
2247                                 }
2248
2249                                 if (a.Expr.Type == InternalType.Null)
2250                                         continue;
2251
2252                                 if (TypeManager.IsValueType (method_parameter)) {
2253                                         score -= tic.LowerBoundInference (a.Type, method_parameter);
2254                                         continue;
2255                                 }
2256
2257                                 //
2258                                 // Otherwise an output type inference is made
2259                                 //
2260                                 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2261                         }
2262
2263                         //
2264                         // Part of the second phase but because it happens only once
2265                         // we don't need to call it in cycle
2266                         //
2267                         bool fixed_any = false;
2268                         if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2269                                 return false;
2270
2271                         return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2272                 }
2273
2274                 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2275                 {
2276                         bool fixed_any = false;
2277                         if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2278                                 return false;
2279
2280                         // If no further unfixed type variables exist, type inference succeeds
2281                         if (!tic.UnfixedVariableExists)
2282                                 return true;
2283
2284                         if (!fixed_any && fixDependent)
2285                                 return false;
2286                         
2287                         // For all arguments where the corresponding argument output types
2288                         // contain unfixed type variables but the input types do not,
2289                         // an output type inference is made
2290                         for (int i = 0; i < arg_count; i++) {
2291                                 
2292                                 // Align params arguments
2293                                 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2294                                 
2295                                 if (!TypeManager.IsDelegateType (t_i)) {
2296                                         if (t_i.GetDefinition () != TypeManager.expression_type)
2297                                                 continue;
2298
2299                                         t_i = TypeManager.GetTypeArguments (t_i) [0];
2300                                 }
2301
2302                                 var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i);
2303                                 TypeSpec rtype = mi.ReturnType;
2304
2305                                 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2306                                         score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2307                         }
2308
2309
2310                         return DoSecondPhase (ec, tic, methodParameters, true);
2311                 }
2312         }
2313
2314         public class TypeInferenceContext
2315         {
2316                 enum BoundKind
2317                 {
2318                         Exact   = 0,
2319                         Lower   = 1,
2320                         Upper   = 2
2321                 }
2322
2323                 class BoundInfo
2324                 {
2325                         public readonly TypeSpec Type;
2326                         public readonly BoundKind Kind;
2327
2328                         public BoundInfo (TypeSpec type, BoundKind kind)
2329                         {
2330                                 this.Type = type;
2331                                 this.Kind = kind;
2332                         }
2333                         
2334                         public override int GetHashCode ()
2335                         {
2336                                 return Type.GetHashCode ();
2337                         }
2338
2339                         public override bool Equals (object obj)
2340                         {
2341                                 BoundInfo a = (BoundInfo) obj;
2342                                 return Type == a.Type && Kind == a.Kind;
2343                         }
2344                 }
2345
2346                 readonly TypeSpec[] unfixed_types;
2347                 readonly TypeSpec[] fixed_types;
2348                 readonly List<BoundInfo>[] bounds;
2349                 bool failed;
2350
2351                 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2352                 public TypeInferenceContext (TypeSpec[] typeArguments)
2353                 {
2354                         if (typeArguments.Length == 0)
2355                                 throw new ArgumentException ("Empty generic arguments");
2356
2357                         fixed_types = new TypeSpec [typeArguments.Length];
2358                         for (int i = 0; i < typeArguments.Length; ++i) {
2359                                 if (typeArguments [i].IsGenericParameter) {
2360                                         if (bounds == null) {
2361                                                 bounds = new List<BoundInfo> [typeArguments.Length];
2362                                                 unfixed_types = new TypeSpec [typeArguments.Length];
2363                                         }
2364                                         unfixed_types [i] = typeArguments [i];
2365                                 } else {
2366                                         fixed_types [i] = typeArguments [i];
2367                                 }
2368                         }
2369                 }
2370
2371                 // 
2372                 // Used together with AddCommonTypeBound fo implement
2373                 // 7.4.2.13 Finding the best common type of a set of expressions
2374                 //
2375                 public TypeInferenceContext ()
2376                 {
2377                         fixed_types = new TypeSpec [1];
2378                         unfixed_types = new TypeSpec [1];
2379                         unfixed_types[0] = InternalType.Arglist; // it can be any internal type
2380                         bounds = new List<BoundInfo> [1];
2381                 }
2382
2383                 public TypeSpec[] InferredTypeArguments {
2384                         get {
2385                                 return fixed_types;
2386                         }
2387                 }
2388
2389                 public void AddCommonTypeBound (TypeSpec type)
2390                 {
2391                         AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2392                 }
2393
2394                 void AddToBounds (BoundInfo bound, int index)
2395                 {
2396                         //
2397                         // Some types cannot be used as type arguments
2398                         //
2399                         if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2400                                 return;
2401
2402                         var a = bounds [index];
2403                         if (a == null) {
2404                                 a = new List<BoundInfo> ();
2405                                 bounds [index] = a;
2406                         } else {
2407                                 if (a.Contains (bound))
2408                                         return;
2409                         }
2410
2411                         //
2412                         // SPEC: does not cover type inference using constraints
2413                         //
2414                         //if (TypeManager.IsGenericParameter (t)) {
2415                         //    GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2416                         //    if (constraints != null) {
2417                         //        //if (constraints.EffectiveBaseClass != null)
2418                         //        //    t = constraints.EffectiveBaseClass;
2419                         //    }
2420                         //}
2421                         a.Add (bound);
2422                 }
2423                 
2424                 bool AllTypesAreFixed (TypeSpec[] types)
2425                 {
2426                         foreach (TypeSpec t in types) {
2427                                 if (t.IsGenericParameter) {
2428                                         if (!IsFixed (t))
2429                                                 return false;
2430                                         continue;
2431                                 }
2432
2433                                 if (TypeManager.IsGenericType (t))
2434                                         return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2435                         }
2436                         
2437                         return true;
2438                 }               
2439
2440                 //
2441                 // 26.3.3.8 Exact Inference
2442                 //
2443                 public int ExactInference (TypeSpec u, TypeSpec v)
2444                 {
2445                         // If V is an array type
2446                         if (v.IsArray) {
2447                                 if (!u.IsArray)
2448                                         return 0;
2449
2450                                 // TODO MemberCache: GetMetaInfo ()
2451                                 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2452                                         return 0;
2453
2454                                 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2455                         }
2456
2457                         // If V is constructed type and U is constructed type
2458                         if (TypeManager.IsGenericType (v)) {
2459                                 if (!TypeManager.IsGenericType (u))
2460                                         return 0;
2461
2462                                 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2463                                 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2464                                 if (ga_u.Length != ga_v.Length)
2465                                         return 0;
2466
2467                                 int score = 0;
2468                                 for (int i = 0; i < ga_u.Length; ++i)
2469                                         score += ExactInference (ga_u [i], ga_v [i]);
2470
2471                                 return score > 0 ? 1 : 0;
2472                         }
2473
2474                         // If V is one of the unfixed type arguments
2475                         int pos = IsUnfixed (v);
2476                         if (pos == -1)
2477                                 return 0;
2478
2479                         AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2480                         return 1;
2481                 }
2482
2483                 public bool FixAllTypes (ResolveContext ec)
2484                 {
2485                         for (int i = 0; i < unfixed_types.Length; ++i) {
2486                                 if (!FixType (ec, i))
2487                                         return false;
2488                         }
2489                         return true;
2490                 }
2491
2492                 //
2493                 // All unfixed type variables Xi are fixed for which all of the following hold:
2494                 // a, There is at least one type variable Xj that depends on Xi
2495                 // b, Xi has a non-empty set of bounds
2496                 // 
2497                 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2498                 {
2499                         for (int i = 0; i < unfixed_types.Length; ++i) {
2500                                 if (unfixed_types[i] == null)
2501                                         continue;
2502
2503                                 if (bounds[i] == null)
2504                                         continue;
2505
2506                                 if (!FixType (ec, i))
2507                                         return false;
2508                                 
2509                                 fixed_any = true;
2510                         }
2511
2512                         return true;
2513                 }
2514
2515                 //
2516                 // All unfixed type variables Xi which depend on no Xj are fixed
2517                 //
2518                 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2519                 {
2520                         var types_to_fix = new List<TypeSpec> (unfixed_types);
2521                         for (int i = 0; i < methodParameters.Length; ++i) {
2522                                 TypeSpec t = methodParameters[i];
2523
2524                                 if (!TypeManager.IsDelegateType (t)) {
2525                                         if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
2526                                                 continue;
2527
2528                                         t =  TypeManager.GetTypeArguments (t) [0];
2529                                 }
2530
2531                                 if (t.IsGenericParameter)
2532                                         continue;
2533
2534                                 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2535                                 TypeSpec rtype = invoke.ReturnType;
2536                                 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2537                                         continue;
2538
2539                                 // Remove dependent types, they cannot be fixed yet
2540                                 RemoveDependentTypes (types_to_fix, rtype);
2541                         }
2542
2543                         foreach (TypeSpec t in types_to_fix) {
2544                                 if (t == null)
2545                                         continue;
2546
2547                                 int idx = IsUnfixed (t);
2548                                 if (idx >= 0 && !FixType (ec, idx)) {
2549                                         return false;
2550                                 }
2551                         }
2552
2553                         fixed_any = types_to_fix.Count > 0;
2554                         return true;
2555                 }
2556
2557                 //
2558                 // 26.3.3.10 Fixing
2559                 //
2560                 public bool FixType (ResolveContext ec, int i)
2561                 {
2562                         // It's already fixed
2563                         if (unfixed_types[i] == null)
2564                                 throw new InternalErrorException ("Type argument has been already fixed");
2565
2566                         if (failed)
2567                                 return false;
2568
2569                         var candidates = bounds [i];
2570                         if (candidates == null)
2571                                 return false;
2572
2573                         if (candidates.Count == 1) {
2574                                 unfixed_types[i] = null;
2575                                 TypeSpec t = candidates[0].Type;
2576                                 if (t == InternalType.Null)
2577                                         return false;
2578
2579                                 fixed_types [i] = t;
2580                                 return true;
2581                         }
2582
2583                         //
2584                         // Determines a unique type from which there is
2585                         // a standard implicit conversion to all the other
2586                         // candidate types.
2587                         //
2588                         TypeSpec best_candidate = null;
2589                         int cii;
2590                         int candidates_count = candidates.Count;
2591                         for (int ci = 0; ci < candidates_count; ++ci) {
2592                                 BoundInfo bound = candidates [ci];
2593                                 for (cii = 0; cii < candidates_count; ++cii) {
2594                                         if (cii == ci)
2595                                                 continue;
2596
2597                                         BoundInfo cbound = candidates[cii];
2598                                         
2599                                         // Same type parameters with different bounds
2600                                         if (cbound.Type == bound.Type) {
2601                                                 if (bound.Kind != BoundKind.Exact)
2602                                                         bound = cbound;
2603
2604                                                 continue;
2605                                         }
2606
2607                                         if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2608                                                 if (cbound.Kind != BoundKind.Exact) {
2609                                                         if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2610                                                                 break;
2611                                                         }
2612
2613                                                         continue;
2614                                                 }
2615                                                 
2616                                                 if (bound.Kind != BoundKind.Exact) {
2617                                                         if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2618                                                                 break;
2619                                                         }
2620
2621                                                         bound = cbound;
2622                                                         continue;
2623                                                 }
2624                                                 
2625                                                 break;
2626                                         }
2627
2628                                         if (bound.Kind == BoundKind.Lower) {
2629                                                 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2630                                                         break;
2631                                                 }
2632                                         } else {
2633                                                 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2634                                                         break;
2635                                                 }
2636                                         }
2637                                 }
2638
2639                                 if (cii != candidates_count)
2640                                         continue;
2641
2642                                 if (best_candidate != null && best_candidate != bound.Type)
2643                                         return false;
2644
2645                                 best_candidate = bound.Type;
2646                         }
2647
2648                         if (best_candidate == null)
2649                                 return false;
2650
2651                         unfixed_types[i] = null;
2652                         fixed_types[i] = best_candidate;
2653                         return true;
2654                 }
2655                 
2656                 //
2657                 // Uses inferred or partially infered types to inflate delegate type argument. Returns
2658                 // null when type parameter was not yet inferres
2659                 //
2660                 public TypeSpec InflateGenericArgument (TypeSpec parameter)
2661                 {
2662                         var tp = parameter as TypeParameterSpec;
2663                         if (tp != null) {
2664                                 //
2665                                 // Type inference work on generic arguments (MVAR) only
2666                                 //
2667                                 if (!tp.IsMethodOwned)
2668                                         return parameter;
2669
2670                                 return fixed_types [tp.DeclaredPosition] ?? parameter;
2671                         }
2672
2673                         var gt = parameter as InflatedTypeSpec;
2674                         if (gt != null) {
2675                                 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
2676                                 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
2677                                         var inflated = InflateGenericArgument (gt.TypeArguments [ii]);
2678                                         if (inflated == null)
2679                                                 return null;
2680
2681                                         inflated_targs[ii] = inflated;
2682                                 }
2683
2684                                 return gt.GetDefinition ().MakeGenericType (inflated_targs);
2685                         }
2686
2687                         return parameter;
2688                 }
2689                 
2690                 //
2691                 // Tests whether all delegate input arguments are fixed and generic output type
2692                 // requires output type inference 
2693                 //
2694                 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
2695                 {
2696                         if (returnType.IsGenericParameter) {
2697                                 if (IsFixed (returnType))
2698                                     return false;
2699                         } else if (TypeManager.IsGenericType (returnType)) {
2700                                 if (TypeManager.IsDelegateType (returnType)) {
2701                                         invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType);
2702                                         return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2703                                 }
2704                                         
2705                                 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
2706                                 
2707                                 // At least one unfixed return type has to exist 
2708                                 if (AllTypesAreFixed (g_args))
2709                                         return false;
2710                         } else {
2711                                 return false;
2712                         }
2713
2714                         // All generic input arguments have to be fixed
2715                         AParametersCollection d_parameters = invoke.Parameters;
2716                         return AllTypesAreFixed (d_parameters.Types);
2717                 }
2718                 
2719                 bool IsFixed (TypeSpec type)
2720                 {
2721                         return IsUnfixed (type) == -1;
2722                 }               
2723
2724                 int IsUnfixed (TypeSpec type)
2725                 {
2726                         if (!type.IsGenericParameter)
2727                                 return -1;
2728
2729                         //return unfixed_types[type.GenericParameterPosition] != null;
2730                         for (int i = 0; i < unfixed_types.Length; ++i) {
2731                                 if (unfixed_types [i] == type)
2732                                         return i;
2733                         }
2734
2735                         return -1;
2736                 }
2737
2738                 //
2739                 // 26.3.3.9 Lower-bound Inference
2740                 //
2741                 public int LowerBoundInference (TypeSpec u, TypeSpec v)
2742                 {
2743                         return LowerBoundInference (u, v, false);
2744                 }
2745
2746                 //
2747                 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2748                 //
2749                 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
2750                 {
2751                         // If V is one of the unfixed type arguments
2752                         int pos = IsUnfixed (v);
2753                         if (pos != -1) {
2754                                 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
2755                                 return 1;
2756                         }                       
2757
2758                         // If U is an array type
2759                         var u_ac = u as ArrayContainer;
2760                         if (u_ac != null) {
2761                                 var v_ac = v as ArrayContainer;
2762                                 if (v_ac != null) {
2763                                         if (u_ac.Rank != v_ac.Rank)
2764                                                 return 0;
2765
2766                                         if (TypeManager.IsValueType (u_ac.Element))
2767                                                 return ExactInference (u_ac.Element, v_ac.Element);
2768
2769                                         return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
2770                                 }
2771
2772                                 if (u_ac.Rank != 1)
2773                                         return 0;
2774
2775                                 if (TypeManager.IsGenericType (v)) {
2776                                         TypeSpec g_v = v.GetDefinition ();
2777                                         if (g_v != TypeManager.generic_ilist_type &&
2778                                                 g_v != TypeManager.generic_icollection_type &&
2779                                                 g_v != TypeManager.generic_ienumerable_type)
2780                                                 return 0;
2781
2782                                         var v_i = TypeManager.GetTypeArguments (v) [0];
2783                                         if (TypeManager.IsValueType (u_ac.Element))
2784                                                 return ExactInference (u_ac.Element, v_i);
2785
2786                                         return LowerBoundInference (u_ac.Element, v_i);
2787                                 }
2788                         } else if (TypeManager.IsGenericType (v)) {
2789                                 //
2790                                 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2791                                 // such that U is identical to, inherits from (directly or indirectly),
2792                                 // or implements (directly or indirectly) C<U1..Uk>
2793                                 //
2794                                 var u_candidates = new List<TypeSpec> ();
2795                                 var open_v = v.MemberDefinition;
2796
2797                                 for (TypeSpec t = u; t != null; t = t.BaseType) {
2798                                         if (open_v == t.MemberDefinition)
2799                                                 u_candidates.Add (t);
2800
2801                                         if (t.Interfaces != null) {
2802                                                 foreach (var iface in t.Interfaces) {
2803                                                         if (open_v == iface.MemberDefinition)
2804                                                                 u_candidates.Add (iface);
2805                                                 }
2806                                         }
2807                                 }
2808
2809                                 TypeSpec [] unique_candidate_targs = null;
2810                                 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
2811                                 foreach (TypeSpec u_candidate in u_candidates) {
2812                                         //
2813                                         // The unique set of types U1..Uk means that if we have an interface I<T>,
2814                                         // class U : I<int>, I<long> then no type inference is made when inferring
2815                                         // type I<T> by applying type U because T could be int or long
2816                                         //
2817                                         if (unique_candidate_targs != null) {
2818                                                 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
2819                                                 if (TypeSpecComparer.Default.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
2820                                                         unique_candidate_targs = second_unique_candidate_targs;
2821                                                         continue;
2822                                                 }
2823
2824                                                 //
2825                                                 // This should always cause type inference failure
2826                                                 //
2827                                                 failed = true;
2828                                                 return 1;
2829                                         }
2830
2831                                         unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
2832                                 }
2833
2834                                 if (unique_candidate_targs != null) {
2835                                         var ga_open_v = open_v.TypeParameters;
2836                                         int score = 0;
2837                                         for (int i = 0; i < unique_candidate_targs.Length; ++i) {
2838                                                 Variance variance = ga_open_v [i].Variance;
2839
2840                                                 TypeSpec u_i = unique_candidate_targs [i];
2841                                                 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
2842                                                         if (ExactInference (u_i, ga_v [i]) == 0)
2843                                                                 ++score;
2844                                                 } else {
2845                                                         bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
2846                                                                 (variance == Variance.Covariant && inversed);
2847
2848                                                         if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
2849                                                                 ++score;
2850                                                 }
2851                                         }
2852                                         return score;
2853                                 }
2854                         }
2855
2856                         return 0;
2857                 }
2858
2859                 //
2860                 // 26.3.3.6 Output Type Inference
2861                 //
2862                 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
2863                 {
2864                         // If e is a lambda or anonymous method with inferred return type
2865                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2866                         if (ame != null) {
2867                                 TypeSpec rt = ame.InferReturnType (ec, this, t);
2868                                 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2869
2870                                 if (rt == null) {
2871                                         AParametersCollection pd = invoke.Parameters;
2872                                         return ame.Parameters.Count == pd.Count ? 1 : 0;
2873                                 }
2874
2875                                 TypeSpec rtype = invoke.ReturnType;
2876                                 return LowerBoundInference (rt, rtype) + 1;
2877                         }
2878
2879                         //
2880                         // if E is a method group and T is a delegate type or expression tree type
2881                         // return type Tb with parameter types T1..Tk and return type Tb, and overload
2882                         // resolution of E with the types T1..Tk yields a single method with return type U,
2883                         // then a lower-bound inference is made from U for Tb.
2884                         //
2885                         if (e is MethodGroupExpr) {
2886                                 if (!TypeManager.IsDelegateType (t)) {
2887                                         if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
2888                                                 return 0;
2889
2890                                         t = TypeManager.GetTypeArguments (t)[0];
2891                                 }
2892
2893                                 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2894                                 TypeSpec rtype = invoke.ReturnType;
2895
2896                                 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2897                                         return 0;
2898
2899                                 // LAMESPEC: Standard does not specify that all methodgroup arguments
2900                                 // has to be fixed but it does not specify how to do recursive type inference
2901                                 // either. We choose the simple option and infer return type only
2902                                 // if all delegate generic arguments are fixed.
2903                                 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
2904                                 for (int i = 0; i < param_types.Length; ++i) {
2905                                         var inflated = InflateGenericArgument (invoke.Parameters.Types[i]);
2906                                         if (inflated == null)
2907                                                 return 0;
2908
2909                                         param_types[i] = inflated;
2910                                 }
2911
2912                                 MethodGroupExpr mg = (MethodGroupExpr) e;
2913                                 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
2914                                 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.Covariant | OverloadResolver.Restrictions.ProbingOnly);
2915                                 if (mg == null)
2916                                         return 0;
2917
2918                                 return LowerBoundInference (mg.BestCandidate.ReturnType, rtype) + 1;
2919                         }
2920
2921                         //
2922                         // if e is an expression with type U, then
2923                         // a lower-bound inference is made from U for T
2924                         //
2925                         return LowerBoundInference (e.Type, t) * 2;
2926                 }
2927
2928                 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
2929                 {
2930                         int idx = IsUnfixed (returnType);
2931                         if (idx >= 0) {
2932                                 types [idx] = null;
2933                                 return;
2934                         }
2935
2936                         if (TypeManager.IsGenericType (returnType)) {
2937                                 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
2938                                         RemoveDependentTypes (types, t);
2939                                 }
2940                         }
2941                 }
2942
2943                 public bool UnfixedVariableExists {
2944                         get {
2945                                 if (unfixed_types == null)
2946                                         return false;
2947
2948                                 foreach (TypeSpec ut in unfixed_types)
2949                                         if (ut != null)
2950                                                 return true;
2951                                 return false;
2952                         }
2953                 }
2954         }
2955 }