87d045a3d2d8a8e301c914ce7f4aa3061eeb1b75
[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 (!TypeSpec.IsBaseClass (ba, bb, false) && !TypeSpec.IsBaseClass (bb, ba, false)) {
94                                 context.Compiler.Report.Error (455, loc,
95                                         "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
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 void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
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, ts.Arity);
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                 #region Properties
1173
1174                 public TypeParameter[] MethodTypeParameters {
1175                         get {
1176                                 return mvar;
1177                         }
1178                 }
1179
1180                 #endregion
1181
1182                 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1183                 {
1184                         if (type is InflatedTypeSpec) {
1185                                 if (type.DeclaringType == null)
1186                                         return type.GetDefinition ();
1187
1188                                 var parent = GetMemberDeclaringType (type.DeclaringType);
1189                                 type = MemberCache.GetMember<TypeSpec> (parent, type);
1190                         }
1191
1192                         return type;
1193                 }
1194
1195                 public TypeSpec Mutate (TypeSpec ts)
1196                 {
1197                         TypeSpec value;
1198                         if (mutated_typespec.TryGetValue (ts, out value))
1199                                 return value;
1200
1201                         value = ts.Mutate (this);
1202                         mutated_typespec.Add (ts, value);
1203                         return value;
1204                 }
1205
1206                 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1207                 {
1208                         for (int i = 0; i < mvar.Length; ++i) {
1209                                 if (mvar[i].Type == tp)
1210                                         return var[i].Type;
1211                         }
1212
1213                         return tp;
1214                 }
1215
1216                 public TypeSpec[] Mutate (TypeSpec[] targs)
1217                 {
1218                         TypeSpec[] mutated = new TypeSpec[targs.Length];
1219                         bool changed = false;
1220                         for (int i = 0; i < targs.Length; ++i) {
1221                                 mutated[i] = Mutate (targs[i]);
1222                                 changed |= targs[i] != mutated[i];
1223                         }
1224
1225                         return changed ? mutated : targs;
1226                 }
1227         }
1228
1229         /// <summary>
1230         ///   A TypeExpr which already resolved to a type parameter.
1231         /// </summary>
1232         public class TypeParameterExpr : TypeExpr {
1233                 
1234                 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1235                 {
1236                         this.type = type_parameter.Type;
1237                         this.eclass = ExprClass.TypeParameter;
1238                         this.loc = loc;
1239                 }
1240
1241                 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1242                 {
1243                         throw new NotSupportedException ();
1244                 }
1245
1246                 public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
1247                 {
1248                         return this;
1249                 }
1250
1251                 public override bool CheckAccessLevel (IMemberContext ds)
1252                 {
1253                         return true;
1254                 }
1255         }
1256
1257         public class InflatedTypeSpec : TypeSpec
1258         {
1259                 TypeSpec[] targs;
1260                 TypeParameterSpec[] constraints;
1261                 readonly TypeSpec open_type;
1262
1263                 public InflatedTypeSpec (TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1264                         : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1265                 {
1266                         if (targs == null)
1267                                 throw new ArgumentNullException ("targs");
1268
1269 //                      this.state = openType.state;
1270                         this.open_type = openType;
1271                         this.targs = targs;
1272
1273                         foreach (var arg in targs) {
1274                                 if (arg.HasDynamicElement || arg == InternalType.Dynamic) {
1275                                         state |= StateFlags.HasDynamicElement;
1276                                         break;
1277                                 }
1278                         }
1279                 }
1280
1281                 #region Properties
1282
1283                 public override TypeSpec BaseType {
1284                         get {
1285                                 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1286                                         InitializeMemberCache (true);
1287
1288                                 return base.BaseType;
1289                         }
1290                 }
1291
1292                 //
1293                 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1294                 //
1295                 public TypeParameterSpec[] Constraints {
1296                         get {
1297                                 if (constraints == null) {
1298                                         var inflator = CreateLocalInflator ();
1299                                         constraints = TypeParameterSpec.InflateConstraints (inflator, MemberDefinition.TypeParameters);
1300                                 }
1301
1302                                 return constraints;
1303                         }
1304                 }
1305
1306                 public override IList<TypeSpec> Interfaces {
1307                         get {
1308                                 if (cache == null)
1309                                         InitializeMemberCache (true);
1310
1311                                 return base.Interfaces;
1312                         }
1313                 }
1314
1315                 //
1316                 // Types used to inflate the generic  type
1317                 //
1318                 public override TypeSpec[] TypeArguments {
1319                         get {
1320                                 return targs;
1321                         }
1322                 }
1323
1324                 #endregion
1325
1326                 TypeParameterInflator CreateLocalInflator ()
1327                 {
1328                         TypeParameterSpec[] tparams_full;
1329                         TypeSpec[] targs_full = targs;
1330                         if (IsNested) {
1331                                 //
1332                                 // Special case is needed when we are inflating an open type (nested type definition)
1333                                 // on inflated parent. Consider following case
1334                                 //
1335                                 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1336                                 //
1337                                 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1338                                 //
1339                                 List<TypeSpec> merged_targs = null;
1340                                 List<TypeParameterSpec> merged_tparams = null;
1341
1342                                 var type = DeclaringType;
1343
1344                                 do {
1345                                         if (type.TypeArguments.Length > 0) {
1346                                                 if (merged_targs == null) {
1347                                                         merged_targs = new List<TypeSpec> ();
1348                                                         merged_tparams = new List<TypeParameterSpec> ();
1349                                                         if (targs.Length > 0) {
1350                                                                 merged_targs.AddRange (targs);
1351                                                                 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1352                                                         }
1353                                                 }
1354                                                 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1355                                                 merged_targs.AddRange (type.TypeArguments);
1356                                         }
1357                                         type = type.DeclaringType;
1358                                 } while (type != null);
1359
1360                                 if (merged_targs != null) {
1361                                         // Type arguments are not in the right order but it should not matter in this case
1362                                         targs_full = merged_targs.ToArray ();
1363                                         tparams_full = merged_tparams.ToArray ();
1364                                 } else if (targs.Length == 0) {
1365                                         tparams_full = TypeParameterSpec.EmptyTypes;
1366                                 } else {
1367                                         tparams_full = open_type.MemberDefinition.TypeParameters;
1368                                 }
1369                         } else if (targs.Length == 0) {
1370                                 tparams_full = TypeParameterSpec.EmptyTypes;
1371                         } else {
1372                                 tparams_full = open_type.MemberDefinition.TypeParameters;
1373                         }
1374
1375                         return new TypeParameterInflator (this, tparams_full, targs_full);
1376                 }
1377
1378                 Type CreateMetaInfo (TypeParameterMutator mutator)
1379                 {
1380                         //
1381                         // Converts nested type arguments into right order
1382                         // Foo<string, bool>.Bar<int> => string, bool, int
1383                         //
1384                         var all = new List<Type> ();
1385                         TypeSpec type = this;
1386                         TypeSpec definition = type;
1387                         do {
1388                                 if (type.GetDefinition().IsGeneric) {
1389                                         all.InsertRange (0,
1390                                                 type.TypeArguments != TypeSpec.EmptyTypes ?
1391                                                 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1392                                                 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1393                                 }
1394
1395                                 definition = definition.GetDefinition ();
1396                                 type = type.DeclaringType;
1397                         } while (type != null);
1398
1399                         return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1400                 }
1401
1402                 public override ObsoleteAttribute GetAttributeObsolete ()
1403                 {
1404                         return open_type.GetAttributeObsolete ();
1405                 }
1406
1407                 protected override bool IsNotCLSCompliant ()
1408                 {
1409                         if (base.IsNotCLSCompliant ())
1410                                 return true;
1411
1412                         foreach (var ta in TypeArguments) {
1413                                 if (ta.MemberDefinition.IsNotCLSCompliant ())
1414                                         return true;
1415                         }
1416
1417                         return false;
1418                 }
1419
1420                 public override TypeSpec GetDefinition ()
1421                 {
1422                         return open_type;
1423                 }
1424
1425                 public override Type GetMetaInfo ()
1426                 {
1427                         if (info == null)
1428                                 info = CreateMetaInfo (null);
1429
1430                         return info;
1431                 }
1432
1433                 public override string GetSignatureForError ()
1434                 {
1435                         if (TypeManager.IsNullableType (open_type))
1436                                 return targs[0].GetSignatureForError () + "?";
1437
1438                         return base.GetSignatureForError ();
1439                 }
1440
1441                 protected override string GetTypeNameSignature ()
1442                 {
1443                         if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1444                                 return null;
1445
1446                         return "<" + TypeManager.CSharpName (targs) + ">";
1447                 }
1448
1449                 protected override void InitializeMemberCache (bool onlyTypes)
1450                 {
1451                         if (cache == null)
1452                                 cache = new MemberCache (onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache);
1453
1454                         var inflator = CreateLocalInflator ();
1455
1456                         //
1457                         // Two stage inflate due to possible nested types recursive
1458                         // references
1459                         //
1460                         // class A<T> {
1461                         //    B b;
1462                         //    class B {
1463                         //      T Value;
1464                         //    }
1465                         // }
1466                         //
1467                         // When resolving type of `b' members of `B' cannot be 
1468                         // inflated because are not yet available in membercache
1469                         //
1470                         if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1471                                 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1472
1473                                 //
1474                                 // Inflate any implemented interfaces
1475                                 //
1476                                 if (open_type.Interfaces != null) {
1477                                         ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1478                                         foreach (var iface in open_type.Interfaces) {
1479                                                 var iface_inflated = inflator.Inflate (iface);
1480                                                 AddInterface (iface_inflated);
1481                                         }
1482                                 }
1483
1484                                 //
1485                                 // Handles the tricky case of recursive nested base generic type
1486                                 //
1487                                 // class A<T> : Base<A<T>.Nested> {
1488                                 //    class Nested {}
1489                                 // }
1490                                 //
1491                                 // When inflating A<T>. base type is not yet known, secondary
1492                                 // inflation is required (not common case) once base scope
1493                                 // is known
1494                                 //
1495                                 if (open_type.BaseType == null) {
1496                                         if (IsClass)
1497                                                 state |= StateFlags.PendingBaseTypeInflate;
1498                                 } else {
1499                                         BaseType = inflator.Inflate (open_type.BaseType);
1500                                 }
1501                         } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1502                                 BaseType = inflator.Inflate (open_type.BaseType);
1503                                 state &= ~StateFlags.PendingBaseTypeInflate;
1504                         }
1505
1506                         if (onlyTypes) {
1507                                 state |= StateFlags.PendingMemberCacheMembers;
1508                                 return;
1509                         }
1510
1511                         var tc = open_type.MemberDefinition as TypeContainer;
1512                         if (tc != null && !tc.HasMembersDefined)
1513                                 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1514
1515                         if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1516                                 BaseType = inflator.Inflate (open_type.BaseType);
1517                                 state &= ~StateFlags.PendingBaseTypeInflate;
1518                         }
1519
1520                         state &= ~StateFlags.PendingMemberCacheMembers;
1521                         open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1522                 }
1523
1524                 public override TypeSpec Mutate (TypeParameterMutator mutator)
1525                 {
1526                         var targs = TypeArguments;
1527                         if (targs != null)
1528                                 targs = mutator.Mutate (targs);
1529
1530                         var decl = DeclaringType;
1531                         if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1532                                 decl = mutator.Mutate (decl);
1533
1534                         if (targs == TypeArguments && decl == DeclaringType)
1535                                 return this;
1536
1537                         var mutated = (InflatedTypeSpec) MemberwiseClone ();
1538                         if (decl != DeclaringType) {
1539                                 // Gets back MethodInfo in case of metaInfo was inflated
1540                                 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1541
1542                                 mutated.declaringType = decl;
1543                                 mutated.state |= StateFlags.PendingMetaInflate;
1544                         }
1545
1546                         if (targs != null) {
1547                                 mutated.targs = targs;
1548                                 mutated.info = null;
1549                         }
1550
1551                         return mutated;
1552                 }
1553         }
1554
1555
1556         //
1557         // Tracks the type arguments when instantiating a generic type. It's used
1558         // by both type arguments and type parameters
1559         //
1560         public class TypeArguments
1561         {
1562                 List<FullNamedExpression> args;
1563                 TypeSpec[] atypes;
1564
1565                 public TypeArguments (params FullNamedExpression[] types)
1566                 {
1567                         this.args = new List<FullNamedExpression> (types);
1568                 }
1569
1570                 public void Add (FullNamedExpression type)
1571                 {
1572                         args.Add (type);
1573                 }
1574
1575                 // TODO: Kill this monster
1576                 public TypeParameterName[] GetDeclarations ()
1577                 {
1578                         return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1579                 }
1580
1581                 /// <summary>
1582                 ///   We may only be used after Resolve() is called and return the fully
1583                 ///   resolved types.
1584                 /// </summary>
1585                 // TODO: Not needed, just return type from resolve
1586                 public TypeSpec[] Arguments {
1587                         get {
1588                                 return atypes;
1589                         }
1590                 }
1591
1592                 public int Count {
1593                         get {
1594                                 return args.Count;
1595                         }
1596                 }
1597
1598                 public virtual bool IsEmpty {
1599                         get {
1600                                 return false;
1601                         }
1602                 }
1603
1604                 public string GetSignatureForError()
1605                 {
1606                         StringBuilder sb = new StringBuilder ();
1607                         for (int i = 0; i < Count; ++i) {
1608                                 var expr = args[i];
1609                                 if (expr != null)
1610                                         sb.Append (expr.GetSignatureForError ());
1611
1612                                 if (i + 1 < Count)
1613                                         sb.Append (',');
1614                         }
1615
1616                         return sb.ToString ();
1617                 }
1618
1619                 /// <summary>
1620                 ///   Resolve the type arguments.
1621                 /// </summary>
1622                 public virtual bool Resolve (IMemberContext ec)
1623                 {
1624                         if (atypes != null)
1625                             return atypes.Length != 0;
1626
1627                         int count = args.Count;
1628                         bool ok = true;
1629
1630                         atypes = new TypeSpec [count];
1631
1632                         for (int i = 0; i < count; i++){
1633                                 TypeExpr te = args[i].ResolveAsTypeTerminal (ec, false);
1634                                 if (te == null) {
1635                                         ok = false;
1636                                         continue;
1637                                 }
1638
1639                                 atypes[i] = te.Type;
1640
1641                                 if (te.Type.IsStatic) {
1642                                         ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
1643                                                 te.GetSignatureForError ());
1644                                         ok = false;
1645                                 }
1646
1647                                 if (te.Type.IsPointer || TypeManager.IsSpecialType (te.Type)) {
1648                                         ec.Compiler.Report.Error (306, te.Location,
1649                                                 "The type `{0}' may not be used as a type argument",
1650                                                 te.GetSignatureForError ());
1651                                         ok = false;
1652                                 }
1653                         }
1654
1655                         if (!ok)
1656                                 atypes = TypeSpec.EmptyTypes;
1657
1658                         return ok;
1659                 }
1660
1661                 public TypeArguments Clone ()
1662                 {
1663                         TypeArguments copy = new TypeArguments ();
1664                         foreach (var ta in args)
1665                                 copy.args.Add (ta);
1666
1667                         return copy;
1668                 }
1669         }
1670
1671         public class UnboundTypeArguments : TypeArguments
1672         {
1673                 public UnboundTypeArguments (int arity)
1674                         : base (new FullNamedExpression[arity])
1675                 {
1676                 }
1677
1678                 public override bool IsEmpty {
1679                         get {
1680                                 return true;
1681                         }
1682                 }
1683
1684                 public override bool Resolve (IMemberContext ec)
1685                 {
1686                         // Nothing to be resolved
1687                         return true;
1688                 }
1689         }
1690
1691         public class TypeParameterName : SimpleName
1692         {
1693                 Attributes attributes;
1694                 Variance variance;
1695
1696                 public TypeParameterName (string name, Attributes attrs, Location loc)
1697                         : this (name, attrs, Variance.None, loc)
1698                 {
1699                 }
1700
1701                 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1702                         : base (name, loc)
1703                 {
1704                         attributes = attrs;
1705                         this.variance = variance;
1706                 }
1707
1708                 public Attributes OptAttributes {
1709                         get {
1710                                 return attributes;
1711                         }
1712                 }
1713
1714                 public Variance Variance {
1715                         get {
1716                                 return variance;
1717                         }
1718                 }
1719         }
1720
1721         //
1722         // A type expression of generic type with type arguments
1723         //
1724         class GenericTypeExpr : TypeExpr
1725         {
1726                 TypeArguments args;
1727                 TypeSpec open_type;
1728                 bool constraints_checked;
1729
1730                 /// <summary>
1731                 ///   Instantiate the generic type `t' with the type arguments `args'.
1732                 ///   Use this constructor if you already know the fully resolved
1733                 ///   generic type.
1734                 /// </summary>          
1735                 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1736                 {
1737                         this.open_type = open_type;
1738                         loc = l;
1739                         this.args = args;
1740                 }
1741
1742                 public TypeArguments TypeArguments {
1743                         get { return args; }
1744                 }
1745
1746                 public override string GetSignatureForError ()
1747                 {
1748                         return TypeManager.CSharpName (type);
1749                 }
1750
1751                 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1752                 {
1753                         if (!args.Resolve (ec))
1754                                 return null;
1755
1756                         TypeSpec[] atypes = args.Arguments;
1757
1758                         //
1759                         // Now bind the parameters
1760                         //
1761                         type = open_type.MakeGenericType (atypes);
1762
1763                         //
1764                         // Check constraints when context is not method/base type
1765                         //
1766                         if (!ec.HasUnresolvedConstraints)
1767                                 CheckConstraints (ec);
1768
1769                         return this;
1770                 }
1771
1772                 //
1773                 // Checks the constraints of open generic type against type
1774                 // arguments. Has to be called after all members have been defined
1775                 //
1776                 public bool CheckConstraints (IMemberContext ec)
1777                 {
1778                         if (constraints_checked)
1779                                 return true;
1780
1781                         constraints_checked = true;
1782
1783                         var gtype = (InflatedTypeSpec) type;
1784                         var constraints = gtype.Constraints;
1785                         if (constraints == null)
1786                                 return true;
1787
1788                         return new ConstraintChecker(ec).CheckAll (open_type, args.Arguments, constraints, loc);
1789                 }
1790         
1791                 public override bool CheckAccessLevel (IMemberContext mc)
1792                 {
1793                         DeclSpace c = mc.CurrentMemberDefinition as DeclSpace;
1794                         if (c == null)
1795                                 c = mc.CurrentMemberDefinition.Parent;
1796
1797                         return c.CheckAccessLevel (open_type);
1798                 }
1799
1800                 public bool HasDynamicArguments ()
1801                 {
1802                         return HasDynamicArguments (args.Arguments);
1803                 }
1804
1805                 static bool HasDynamicArguments (TypeSpec[] args)
1806                 {
1807                         for (int i = 0; i < args.Length; ++i) {
1808                                 var item = args[i];
1809
1810                                 if (item == InternalType.Dynamic)
1811                                         return true;
1812
1813                                 if (TypeManager.IsGenericType (item))
1814                                         return HasDynamicArguments (TypeManager.GetTypeArguments (item));
1815
1816                                 if (item.IsArray) {
1817                                         while (item.IsArray) {
1818                                                 item = ((ArrayContainer) item).Element;
1819                                         }
1820
1821                                         if (item == InternalType.Dynamic)
1822                                                 return true;
1823                                 }
1824                         }
1825
1826                         return false;
1827                 }
1828
1829                 public override bool Equals (object obj)
1830                 {
1831                         GenericTypeExpr cobj = obj as GenericTypeExpr;
1832                         if (cobj == null)
1833                                 return false;
1834
1835                         if ((type == null) || (cobj.type == null))
1836                                 return false;
1837
1838                         return type == cobj.type;
1839                 }
1840
1841                 public override int GetHashCode ()
1842                 {
1843                         return base.GetHashCode ();
1844                 }
1845         }
1846
1847         //
1848         // Generic type with unbound type arguments, used for typeof (G<,,>)
1849         //
1850         class GenericOpenTypeExpr : TypeExpr
1851         {
1852                 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
1853                 {
1854                         this.type = type.GetDefinition ();
1855                         this.loc = loc;
1856                 }
1857
1858                 protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
1859                 {
1860                         return this;
1861                 }
1862         }
1863
1864         struct ConstraintChecker
1865         {
1866                 IMemberContext mc;
1867                 bool ignore_inferred_dynamic;
1868
1869                 public ConstraintChecker (IMemberContext ctx)
1870                 {
1871                         this.mc = ctx;
1872                         ignore_inferred_dynamic = false;
1873                 }
1874
1875                 #region Properties
1876
1877                 public bool IgnoreInferredDynamic {
1878                         get {
1879                                 return ignore_inferred_dynamic;
1880                         }
1881                         set {
1882                                 ignore_inferred_dynamic = value;
1883                         }
1884                 }
1885
1886                 #endregion
1887
1888                 //
1889                 // Checks all type arguments againts type parameters constraints
1890                 // NOTE: It can run in probing mode when `mc' is null
1891                 //
1892                 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
1893                 {
1894                         for (int i = 0; i < tparams.Length; i++) {
1895                                 if (ignore_inferred_dynamic && targs[i] == InternalType.Dynamic)
1896                                         continue;
1897
1898                                 if (!CheckConstraint (context, targs [i], tparams [i], loc))
1899                                         return false;
1900                         }
1901
1902                         return true;
1903                 }
1904
1905                 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
1906                 {
1907                         //
1908                         // First, check the `class' and `struct' constraints.
1909                         //
1910                         if (tparam.HasSpecialClass && !TypeManager.IsReferenceType (atype)) {
1911                                 if (mc != null) {
1912                                         mc.Compiler.Report.Error (452, loc,
1913                                                 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
1914                                                 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1915                                 }
1916
1917                                 return false;
1918                         }
1919
1920                         if (tparam.HasSpecialStruct && (!TypeManager.IsValueType (atype) || TypeManager.IsNullableType (atype))) {
1921                                 if (mc != null) {
1922                                         mc.Compiler.Report.Error (453, loc,
1923                                                 "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}'",
1924                                                 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1925                                 }
1926
1927                                 return false;
1928                         }
1929
1930                         bool ok = true;
1931
1932                         //
1933                         // Check the class constraint
1934                         //
1935                         if (tparam.HasTypeConstraint) {
1936                                 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
1937                                         if (mc == null)
1938                                                 return false;
1939
1940                                         ok = false;
1941                                 }
1942                         }
1943
1944                         //
1945                         // Check the interfaces constraints
1946                         //
1947                         if (tparam.Interfaces != null) {
1948                                 if (TypeManager.IsNullableType (atype)) {
1949                                         if (mc == null)
1950                                                 return false;
1951
1952                                         mc.Compiler.Report.Error (313, loc,
1953                                                 "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",
1954                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
1955                                         ok = false;
1956                                 } else {
1957                                         foreach (TypeSpec iface in tparam.Interfaces) {
1958                                                 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
1959                                                         if (mc == null)
1960                                                                 return false;
1961
1962                                                         ok = false;
1963                                                 }
1964                                         }
1965                                 }
1966                         }
1967
1968                         //
1969                         // Check the type parameter constraint
1970                         //
1971                         if (tparam.TypeArguments != null) {
1972                                 foreach (var ta in tparam.TypeArguments) {
1973                                         if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
1974                                                 if (mc == null)
1975                                                         return false;
1976
1977                                                 ok = false;
1978                                         }
1979                                 }
1980                         }
1981
1982                         //
1983                         // Finally, check the constructor constraint.
1984                         //
1985                         if (!tparam.HasSpecialConstructor)
1986                                 return ok;
1987
1988                         if (!HasDefaultConstructor (atype)) {
1989                                 if (mc != null) {
1990                                         mc.Compiler.Report.SymbolRelatedToPreviousError (atype);
1991                                         mc.Compiler.Report.Error (310, loc,
1992                                                 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
1993                                                 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
1994                                 }
1995                                 return false;
1996                         }
1997
1998                         return ok;
1999                 }
2000
2001                 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2002                 {
2003                         for (int i = 0; i < targs.Length; ++i) {
2004                                 var targ = targs [i];
2005                                 if (targ == InternalType.Dynamic)
2006                                         return true;
2007
2008                                 if (HasDynamicTypeArgument (targ.TypeArguments))
2009                                         return true;
2010                         }
2011
2012                         return false;
2013                 }
2014
2015                 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2016                 {
2017                         var expr = new EmptyExpression (atype);
2018                         if (Convert.ImplicitStandardConversionExists (expr, ttype))
2019                                 return true;
2020
2021                         //
2022                         // When partial/full type inference finds a dynamic type argument delay
2023                         // the constraint check to runtime, it can succeed for real underlying
2024                         // dynamic type
2025                         //
2026                         if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2027                                 return true;
2028
2029                         if (mc != null) {
2030                                 mc.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2031                                 if (TypeManager.IsValueType (atype)) {
2032                                         mc.Compiler.Report.Error (315, loc,
2033                                                 "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}'",
2034                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2035                                 } else if (atype.IsGenericParameter) {
2036                                         mc.Compiler.Report.Error (314, loc,
2037                                                 "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}'",
2038                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2039                                 } else {
2040                                         mc.Compiler.Report.Error (311, loc,
2041                                                 "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}'",
2042                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2043                                 }
2044                         }
2045
2046                         return false;
2047                 }
2048
2049                 bool HasDefaultConstructor (TypeSpec atype)
2050                 {
2051                         var tp = atype as TypeParameterSpec;
2052                         if (tp != null) {
2053                                 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2054                         }
2055
2056                         if (atype.IsStruct || atype.IsEnum)
2057                                 return true;
2058
2059                         if (atype.IsAbstract)
2060                                 return false;
2061
2062                         var tdef = atype.GetDefinition ();
2063
2064                         //
2065                         // In some circumstances MemberCache is not yet populated and members
2066                         // cannot be defined yet (recursive type new constraints)
2067                         //
2068                         // class A<T> where T : B<T>, new () {}
2069                         // class B<T> where T : A<T>, new () {}
2070                         //
2071                         var tc = tdef.MemberDefinition as Class;
2072                         if (tc != null) {
2073                                 if (tc.InstanceConstructors == null) {
2074                                         // Default ctor will be generated later
2075                                         return true;
2076                                 }
2077
2078                                 foreach (var c in tc.InstanceConstructors) {
2079                                         if (c.ParameterInfo.IsEmpty) {
2080                                                 if ((c.ModFlags & Modifiers.PUBLIC) != 0)
2081                                                         return true;
2082                                         }
2083                                 }
2084
2085                                 return false;
2086                         }
2087
2088                         var found = MemberCache.FindMember (tdef,
2089                                 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2090                                 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2091
2092                         return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2093                 }
2094         }
2095
2096         /// <summary>
2097         ///   A generic method definition.
2098         /// </summary>
2099         public class GenericMethod : DeclSpace
2100         {
2101                 ParametersCompiled parameters;
2102
2103                 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
2104                                       FullNamedExpression return_type, ParametersCompiled parameters)
2105                         : base (ns, parent, name, null)
2106                 {
2107                         this.parameters = parameters;
2108                 }
2109
2110                 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2111                                           FullNamedExpression return_type, ParametersCompiled parameters)
2112                         : this (ns, parent, name, return_type, parameters)
2113                 {
2114                         this.type_params = tparams;
2115                 }
2116
2117                 public override TypeParameter[] CurrentTypeParameters {
2118                         get {
2119                                 return base.type_params;
2120                         }
2121                 }
2122
2123                 public override TypeBuilder DefineType ()
2124                 {
2125                         throw new Exception ();
2126                 }
2127
2128                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2129                 {
2130                         throw new NotSupportedException ();
2131                 }
2132
2133                 public override bool Define ()
2134                 {
2135                         throw new NotSupportedException ();
2136                 }
2137
2138                 /// <summary>
2139                 ///   Define and resolve the type parameters.
2140                 ///   We're called from Method.Define().
2141                 /// </summary>
2142                 public bool Define (MethodOrOperator m)
2143                 {
2144                         TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2145                         string[] snames = new string [names.Length];
2146                         var block = m.Block;
2147                         for (int i = 0; i < names.Length; i++) {
2148                                 string type_argument_name = names[i].Name;
2149
2150                                 if (block == null) {
2151                                         int idx = parameters.GetParameterIndexByName (type_argument_name);
2152                                         if (idx >= 0) {
2153                                                 var b = m.Block;
2154                                                 if (b == null)
2155                                                         b = new ToplevelBlock (Compiler, Location);
2156
2157                                                 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2158                                         }
2159                                 } else {
2160                                         INamedBlockVariable variable = null;
2161                                         block.GetLocalName (type_argument_name, m.Block, ref variable);
2162                                         if (variable != null)
2163                                                 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2164                                 }
2165
2166                                 snames[i] = type_argument_name;
2167                         }
2168
2169                         GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2170                         for (int i = 0; i < TypeParameters.Length; i++)
2171                                 TypeParameters [i].Define (gen_params [i], null);
2172
2173                         return true;
2174                 }
2175
2176                 public void EmitAttributes ()
2177                 {
2178                         if (OptAttributes != null)
2179                                 OptAttributes.Emit ();
2180                 }
2181
2182                 public override string GetSignatureForError ()
2183                 {
2184                         return base.GetSignatureForError () + parameters.GetSignatureForError ();
2185                 }
2186
2187                 public override AttributeTargets AttributeTargets {
2188                         get {
2189                                 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2190                         }
2191                 }
2192
2193                 public override string DocCommentHeader {
2194                         get { return "M:"; }
2195                 }
2196
2197                 public new void VerifyClsCompliance ()
2198                 {
2199                         foreach (TypeParameter tp in TypeParameters) {
2200                                 tp.VerifyClsCompliance ();
2201                         }
2202                 }
2203         }
2204
2205         public partial class TypeManager
2206         {
2207                 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2208                 {
2209                         var tp = t as TypeParameterSpec;
2210                         if (tp != null) {
2211                                 Variance v = tp.Variance;
2212                                 if (expected == Variance.None && v != expected ||
2213                                         expected == Variance.Covariant && v == Variance.Contravariant ||
2214                                         expected == Variance.Contravariant && v == Variance.Covariant) {
2215                                         ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2216                                 }
2217
2218                                 return expected;
2219                         }
2220
2221                         if (t.TypeArguments.Length > 0) {
2222                                 var targs_definition = t.MemberDefinition.TypeParameters;
2223                                 TypeSpec[] targs = GetTypeArguments (t);
2224                                 for (int i = 0; i < targs.Length; ++i) {
2225                                         Variance v = targs_definition[i].Variance;
2226                                         CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2227                                 }
2228
2229                                 return expected;
2230                         }
2231
2232                         if (t.IsArray)
2233                                 return CheckTypeVariance (GetElementType (t), expected, member);
2234
2235                         return Variance.None;
2236                 }
2237         }
2238
2239         //
2240         // Implements C# type inference
2241         //
2242         class TypeInference
2243         {
2244                 //
2245                 // Tracks successful rate of type inference
2246                 //
2247                 int score = int.MaxValue;
2248                 readonly Arguments arguments;
2249                 readonly int arg_count;
2250
2251                 public TypeInference (Arguments arguments)
2252                 {
2253                         this.arguments = arguments;
2254                         if (arguments != null)
2255                                 arg_count = arguments.Count;
2256                 }
2257
2258                 public int InferenceScore {
2259                         get {
2260                                 return score;
2261                         }
2262                 }
2263
2264                 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2265                 {
2266                         var method_generic_args = method.GenericDefinition.TypeParameters;
2267                         TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2268                         if (!context.UnfixedVariableExists)
2269                                 return TypeSpec.EmptyTypes;
2270
2271                         AParametersCollection pd = method.Parameters;
2272                         if (!InferInPhases (ec, context, pd))
2273                                 return null;
2274
2275                         return context.InferredTypeArguments;
2276                 }
2277
2278                 //
2279                 // Implements method type arguments inference
2280                 //
2281                 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2282                 {
2283                         int params_arguments_start;
2284                         if (methodParameters.HasParams) {
2285                                 params_arguments_start = methodParameters.Count - 1;
2286                         } else {
2287                                 params_arguments_start = arg_count;
2288                         }
2289
2290                         TypeSpec [] ptypes = methodParameters.Types;
2291                         
2292                         //
2293                         // The first inference phase
2294                         //
2295                         TypeSpec method_parameter = null;
2296                         for (int i = 0; i < arg_count; i++) {
2297                                 Argument a = arguments [i];
2298                                 if (a == null)
2299                                         continue;
2300                                 
2301                                 if (i < params_arguments_start) {
2302                                         method_parameter = methodParameters.Types [i];
2303                                 } else if (i == params_arguments_start) {
2304                                         if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2305                                                 method_parameter = methodParameters.Types [params_arguments_start];
2306                                         else
2307                                                 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2308
2309                                         ptypes = (TypeSpec[]) ptypes.Clone ();
2310                                         ptypes [i] = method_parameter;
2311                                 }
2312
2313                                 //
2314                                 // When a lambda expression, an anonymous method
2315                                 // is used an explicit argument type inference takes a place
2316                                 //
2317                                 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2318                                 if (am != null) {
2319                                         if (am.ExplicitTypeInference (ec, tic, method_parameter))
2320                                                 --score; 
2321                                         continue;
2322                                 }
2323
2324                                 if (a.IsByRef) {
2325                                         score -= tic.ExactInference (a.Type, method_parameter);
2326                                         continue;
2327                                 }
2328
2329                                 if (a.Expr.Type == InternalType.Null)
2330                                         continue;
2331
2332                                 if (TypeManager.IsValueType (method_parameter)) {
2333                                         score -= tic.LowerBoundInference (a.Type, method_parameter);
2334                                         continue;
2335                                 }
2336
2337                                 //
2338                                 // Otherwise an output type inference is made
2339                                 //
2340                                 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2341                         }
2342
2343                         //
2344                         // Part of the second phase but because it happens only once
2345                         // we don't need to call it in cycle
2346                         //
2347                         bool fixed_any = false;
2348                         if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2349                                 return false;
2350
2351                         return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2352                 }
2353
2354                 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2355                 {
2356                         bool fixed_any = false;
2357                         if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2358                                 return false;
2359
2360                         // If no further unfixed type variables exist, type inference succeeds
2361                         if (!tic.UnfixedVariableExists)
2362                                 return true;
2363
2364                         if (!fixed_any && fixDependent)
2365                                 return false;
2366                         
2367                         // For all arguments where the corresponding argument output types
2368                         // contain unfixed type variables but the input types do not,
2369                         // an output type inference is made
2370                         for (int i = 0; i < arg_count; i++) {
2371                                 
2372                                 // Align params arguments
2373                                 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2374                                 
2375                                 if (!TypeManager.IsDelegateType (t_i)) {
2376                                         if (t_i.GetDefinition () != TypeManager.expression_type)
2377                                                 continue;
2378
2379                                         t_i = TypeManager.GetTypeArguments (t_i) [0];
2380                                 }
2381
2382                                 var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i);
2383                                 TypeSpec rtype = mi.ReturnType;
2384
2385                                 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2386                                         score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2387                         }
2388
2389
2390                         return DoSecondPhase (ec, tic, methodParameters, true);
2391                 }
2392         }
2393
2394         public class TypeInferenceContext
2395         {
2396                 enum BoundKind
2397                 {
2398                         Exact   = 0,
2399                         Lower   = 1,
2400                         Upper   = 2
2401                 }
2402
2403                 class BoundInfo : IEquatable<BoundInfo>
2404                 {
2405                         public readonly TypeSpec Type;
2406                         public readonly BoundKind Kind;
2407
2408                         public BoundInfo (TypeSpec type, BoundKind kind)
2409                         {
2410                                 this.Type = type;
2411                                 this.Kind = kind;
2412                         }
2413                         
2414                         public override int GetHashCode ()
2415                         {
2416                                 return Type.GetHashCode ();
2417                         }
2418
2419                         #region IEquatable<BoundInfo> Members
2420
2421                         public bool Equals (BoundInfo other)
2422                         {
2423                                 return Type == other.Type && Kind == other.Kind;
2424                         }
2425
2426                         #endregion
2427                 }
2428
2429                 readonly TypeSpec[] unfixed_types;
2430                 readonly TypeSpec[] fixed_types;
2431                 readonly List<BoundInfo>[] bounds;
2432                 bool failed;
2433
2434                 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2435                 public TypeInferenceContext (TypeSpec[] typeArguments)
2436                 {
2437                         if (typeArguments.Length == 0)
2438                                 throw new ArgumentException ("Empty generic arguments");
2439
2440                         fixed_types = new TypeSpec [typeArguments.Length];
2441                         for (int i = 0; i < typeArguments.Length; ++i) {
2442                                 if (typeArguments [i].IsGenericParameter) {
2443                                         if (bounds == null) {
2444                                                 bounds = new List<BoundInfo> [typeArguments.Length];
2445                                                 unfixed_types = new TypeSpec [typeArguments.Length];
2446                                         }
2447                                         unfixed_types [i] = typeArguments [i];
2448                                 } else {
2449                                         fixed_types [i] = typeArguments [i];
2450                                 }
2451                         }
2452                 }
2453
2454                 // 
2455                 // Used together with AddCommonTypeBound fo implement
2456                 // 7.4.2.13 Finding the best common type of a set of expressions
2457                 //
2458                 public TypeInferenceContext ()
2459                 {
2460                         fixed_types = new TypeSpec [1];
2461                         unfixed_types = new TypeSpec [1];
2462                         unfixed_types[0] = InternalType.Arglist; // it can be any internal type
2463                         bounds = new List<BoundInfo> [1];
2464                 }
2465
2466                 public TypeSpec[] InferredTypeArguments {
2467                         get {
2468                                 return fixed_types;
2469                         }
2470                 }
2471
2472                 public void AddCommonTypeBound (TypeSpec type)
2473                 {
2474                         AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2475                 }
2476
2477                 void AddToBounds (BoundInfo bound, int index)
2478                 {
2479                         //
2480                         // Some types cannot be used as type arguments
2481                         //
2482                         if (bound.Type == TypeManager.void_type || bound.Type.IsPointer)
2483                                 return;
2484
2485                         var a = bounds [index];
2486                         if (a == null) {
2487                                 a = new List<BoundInfo> (2);
2488                                 a.Add (bound);
2489                                 bounds [index] = a;
2490                                 return;
2491                         }
2492
2493                         if (a.Contains (bound))
2494                                 return;
2495
2496                         a.Add (bound);
2497                 }
2498                 
2499                 bool AllTypesAreFixed (TypeSpec[] types)
2500                 {
2501                         foreach (TypeSpec t in types) {
2502                                 if (t.IsGenericParameter) {
2503                                         if (!IsFixed (t))
2504                                                 return false;
2505                                         continue;
2506                                 }
2507
2508                                 if (TypeManager.IsGenericType (t))
2509                                         return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2510                         }
2511                         
2512                         return true;
2513                 }               
2514
2515                 //
2516                 // 26.3.3.8 Exact Inference
2517                 //
2518                 public int ExactInference (TypeSpec u, TypeSpec v)
2519                 {
2520                         // If V is an array type
2521                         if (v.IsArray) {
2522                                 if (!u.IsArray)
2523                                         return 0;
2524
2525                                 // TODO MemberCache: GetMetaInfo ()
2526                                 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2527                                         return 0;
2528
2529                                 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2530                         }
2531
2532                         // If V is constructed type and U is constructed type
2533                         if (TypeManager.IsGenericType (v)) {
2534                                 if (!TypeManager.IsGenericType (u))
2535                                         return 0;
2536
2537                                 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2538                                 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2539                                 if (ga_u.Length != ga_v.Length)
2540                                         return 0;
2541
2542                                 int score = 0;
2543                                 for (int i = 0; i < ga_u.Length; ++i)
2544                                         score += ExactInference (ga_u [i], ga_v [i]);
2545
2546                                 return score > 0 ? 1 : 0;
2547                         }
2548
2549                         // If V is one of the unfixed type arguments
2550                         int pos = IsUnfixed (v);
2551                         if (pos == -1)
2552                                 return 0;
2553
2554                         AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2555                         return 1;
2556                 }
2557
2558                 public bool FixAllTypes (ResolveContext ec)
2559                 {
2560                         for (int i = 0; i < unfixed_types.Length; ++i) {
2561                                 if (!FixType (ec, i))
2562                                         return false;
2563                         }
2564                         return true;
2565                 }
2566
2567                 //
2568                 // All unfixed type variables Xi are fixed for which all of the following hold:
2569                 // a, There is at least one type variable Xj that depends on Xi
2570                 // b, Xi has a non-empty set of bounds
2571                 // 
2572                 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2573                 {
2574                         for (int i = 0; i < unfixed_types.Length; ++i) {
2575                                 if (unfixed_types[i] == null)
2576                                         continue;
2577
2578                                 if (bounds[i] == null)
2579                                         continue;
2580
2581                                 if (!FixType (ec, i))
2582                                         return false;
2583                                 
2584                                 fixed_any = true;
2585                         }
2586
2587                         return true;
2588                 }
2589
2590                 //
2591                 // All unfixed type variables Xi which depend on no Xj are fixed
2592                 //
2593                 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2594                 {
2595                         var types_to_fix = new List<TypeSpec> (unfixed_types);
2596                         for (int i = 0; i < methodParameters.Length; ++i) {
2597                                 TypeSpec t = methodParameters[i];
2598
2599                                 if (!TypeManager.IsDelegateType (t)) {
2600                                         if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
2601                                                 continue;
2602
2603                                         t =  TypeManager.GetTypeArguments (t) [0];
2604                                 }
2605
2606                                 if (t.IsGenericParameter)
2607                                         continue;
2608
2609                                 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2610                                 TypeSpec rtype = invoke.ReturnType;
2611                                 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2612                                         continue;
2613
2614                                 // Remove dependent types, they cannot be fixed yet
2615                                 RemoveDependentTypes (types_to_fix, rtype);
2616                         }
2617
2618                         foreach (TypeSpec t in types_to_fix) {
2619                                 if (t == null)
2620                                         continue;
2621
2622                                 int idx = IsUnfixed (t);
2623                                 if (idx >= 0 && !FixType (ec, idx)) {
2624                                         return false;
2625                                 }
2626                         }
2627
2628                         fixed_any = types_to_fix.Count > 0;
2629                         return true;
2630                 }
2631
2632                 //
2633                 // 26.3.3.10 Fixing
2634                 //
2635                 public bool FixType (ResolveContext ec, int i)
2636                 {
2637                         // It's already fixed
2638                         if (unfixed_types[i] == null)
2639                                 throw new InternalErrorException ("Type argument has been already fixed");
2640
2641                         if (failed)
2642                                 return false;
2643
2644                         var candidates = bounds [i];
2645                         if (candidates == null)
2646                                 return false;
2647
2648                         if (candidates.Count == 1) {
2649                                 unfixed_types[i] = null;
2650                                 TypeSpec t = candidates[0].Type;
2651                                 if (t == InternalType.Null)
2652                                         return false;
2653
2654                                 fixed_types [i] = t;
2655                                 return true;
2656                         }
2657
2658                         //
2659                         // Determines a unique type from which there is
2660                         // a standard implicit conversion to all the other
2661                         // candidate types.
2662                         //
2663                         TypeSpec best_candidate = null;
2664                         int cii;
2665                         int candidates_count = candidates.Count;
2666                         for (int ci = 0; ci < candidates_count; ++ci) {
2667                                 BoundInfo bound = candidates [ci];
2668                                 for (cii = 0; cii < candidates_count; ++cii) {
2669                                         if (cii == ci)
2670                                                 continue;
2671
2672                                         BoundInfo cbound = candidates[cii];
2673                                         
2674                                         // Same type parameters with different bounds
2675                                         if (cbound.Type == bound.Type) {
2676                                                 if (bound.Kind != BoundKind.Exact)
2677                                                         bound = cbound;
2678
2679                                                 continue;
2680                                         }
2681
2682                                         if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2683                                                 if (cbound.Kind == BoundKind.Lower) {
2684                                                         if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2685                                                                 break;
2686                                                         }
2687
2688                                                         continue;
2689                                                 }
2690                                                 if (cbound.Kind == BoundKind.Upper) {
2691                                                         if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2692                                                                 break;
2693                                                         }
2694
2695                                                         continue;
2696                                                 }
2697                                                 
2698                                                 if (bound.Kind != BoundKind.Exact) {
2699                                                         if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2700                                                                 break;
2701                                                         }
2702
2703                                                         bound = cbound;
2704                                                         continue;
2705                                                 }
2706                                                 
2707                                                 break;
2708                                         }
2709
2710                                         if (bound.Kind == BoundKind.Lower) {
2711                                                 if (cbound.Kind == BoundKind.Lower) {
2712                                                         if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
2713                                                                 break;
2714                                                         }
2715                                                 } else {
2716                                                         if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2717                                                                 break;
2718                                                         }
2719
2720                                                         bound = cbound;
2721                                                 }
2722
2723                                                 continue;
2724                                         }
2725
2726                                         if (bound.Kind == BoundKind.Upper) {
2727                                                 if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
2728                                                         break;
2729                                                 }
2730                                         } else {
2731                                                 throw new NotImplementedException ("variance conversion");
2732                                         }
2733                                 }
2734
2735                                 if (cii != candidates_count)
2736                                         continue;
2737
2738                                 //
2739                                 // We already have the best candidate, break if thet are different
2740                                 //
2741                                 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
2742                                 //
2743                                 if (best_candidate != null) {
2744
2745                                         if (best_candidate == InternalType.Dynamic)
2746                                                 continue;
2747
2748                                         if (bound.Type != InternalType.Dynamic && best_candidate != bound.Type)
2749                                                 return false;
2750                                 }
2751
2752                                 best_candidate = bound.Type;
2753                         }
2754
2755                         if (best_candidate == null)
2756                                 return false;
2757
2758                         unfixed_types[i] = null;
2759                         fixed_types[i] = best_candidate;
2760                         return true;
2761                 }
2762                 
2763                 //
2764                 // Uses inferred or partially infered types to inflate delegate type argument. Returns
2765                 // null when type parameter was not yet inferres
2766                 //
2767                 public TypeSpec InflateGenericArgument (TypeSpec parameter)
2768                 {
2769                         var tp = parameter as TypeParameterSpec;
2770                         if (tp != null) {
2771                                 //
2772                                 // Type inference work on generic arguments (MVAR) only
2773                                 //
2774                                 if (!tp.IsMethodOwned)
2775                                         return parameter;
2776
2777                                 return fixed_types [tp.DeclaredPosition] ?? parameter;
2778                         }
2779
2780                         var gt = parameter as InflatedTypeSpec;
2781                         if (gt != null) {
2782                                 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
2783                                 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
2784                                         var inflated = InflateGenericArgument (gt.TypeArguments [ii]);
2785                                         if (inflated == null)
2786                                                 return null;
2787
2788                                         inflated_targs[ii] = inflated;
2789                                 }
2790
2791                                 return gt.GetDefinition ().MakeGenericType (inflated_targs);
2792                         }
2793
2794                         return parameter;
2795                 }
2796                 
2797                 //
2798                 // Tests whether all delegate input arguments are fixed and generic output type
2799                 // requires output type inference 
2800                 //
2801                 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
2802                 {
2803                         if (returnType.IsGenericParameter) {
2804                                 if (IsFixed (returnType))
2805                                     return false;
2806                         } else if (TypeManager.IsGenericType (returnType)) {
2807                                 if (TypeManager.IsDelegateType (returnType)) {
2808                                         invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType);
2809                                         return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
2810                                 }
2811                                         
2812                                 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
2813                                 
2814                                 // At least one unfixed return type has to exist 
2815                                 if (AllTypesAreFixed (g_args))
2816                                         return false;
2817                         } else {
2818                                 return false;
2819                         }
2820
2821                         // All generic input arguments have to be fixed
2822                         AParametersCollection d_parameters = invoke.Parameters;
2823                         return AllTypesAreFixed (d_parameters.Types);
2824                 }
2825                 
2826                 bool IsFixed (TypeSpec type)
2827                 {
2828                         return IsUnfixed (type) == -1;
2829                 }               
2830
2831                 int IsUnfixed (TypeSpec type)
2832                 {
2833                         if (!type.IsGenericParameter)
2834                                 return -1;
2835
2836                         //return unfixed_types[type.GenericParameterPosition] != null;
2837                         for (int i = 0; i < unfixed_types.Length; ++i) {
2838                                 if (unfixed_types [i] == type)
2839                                         return i;
2840                         }
2841
2842                         return -1;
2843                 }
2844
2845                 //
2846                 // 26.3.3.9 Lower-bound Inference
2847                 //
2848                 public int LowerBoundInference (TypeSpec u, TypeSpec v)
2849                 {
2850                         return LowerBoundInference (u, v, false);
2851                 }
2852
2853                 //
2854                 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
2855                 //
2856                 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
2857                 {
2858                         // If V is one of the unfixed type arguments
2859                         int pos = IsUnfixed (v);
2860                         if (pos != -1) {
2861                                 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
2862                                 return 1;
2863                         }                       
2864
2865                         // If U is an array type
2866                         var u_ac = u as ArrayContainer;
2867                         if (u_ac != null) {
2868                                 var v_ac = v as ArrayContainer;
2869                                 if (v_ac != null) {
2870                                         if (u_ac.Rank != v_ac.Rank)
2871                                                 return 0;
2872
2873                                         if (TypeManager.IsValueType (u_ac.Element))
2874                                                 return ExactInference (u_ac.Element, v_ac.Element);
2875
2876                                         return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
2877                                 }
2878
2879                                 if (u_ac.Rank != 1)
2880                                         return 0;
2881
2882                                 if (TypeManager.IsGenericType (v)) {
2883                                         TypeSpec g_v = v.GetDefinition ();
2884                                         if (g_v != TypeManager.generic_ilist_type &&
2885                                                 g_v != TypeManager.generic_icollection_type &&
2886                                                 g_v != TypeManager.generic_ienumerable_type)
2887                                                 return 0;
2888
2889                                         var v_i = TypeManager.GetTypeArguments (v) [0];
2890                                         if (TypeManager.IsValueType (u_ac.Element))
2891                                                 return ExactInference (u_ac.Element, v_i);
2892
2893                                         return LowerBoundInference (u_ac.Element, v_i);
2894                                 }
2895                         } else if (TypeManager.IsGenericType (v)) {
2896                                 //
2897                                 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
2898                                 // such that U is identical to, inherits from (directly or indirectly),
2899                                 // or implements (directly or indirectly) C<U1..Uk>
2900                                 //
2901                                 var u_candidates = new List<TypeSpec> ();
2902                                 var open_v = v.MemberDefinition;
2903
2904                                 for (TypeSpec t = u; t != null; t = t.BaseType) {
2905                                         if (open_v == t.MemberDefinition)
2906                                                 u_candidates.Add (t);
2907
2908                                         if (t.Interfaces != null) {
2909                                                 foreach (var iface in t.Interfaces) {
2910                                                         if (open_v == iface.MemberDefinition)
2911                                                                 u_candidates.Add (iface);
2912                                                 }
2913                                         }
2914                                 }
2915
2916                                 TypeSpec [] unique_candidate_targs = null;
2917                                 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
2918                                 foreach (TypeSpec u_candidate in u_candidates) {
2919                                         //
2920                                         // The unique set of types U1..Uk means that if we have an interface I<T>,
2921                                         // class U : I<int>, I<long> then no type inference is made when inferring
2922                                         // type I<T> by applying type U because T could be int or long
2923                                         //
2924                                         if (unique_candidate_targs != null) {
2925                                                 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
2926                                                 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
2927                                                         unique_candidate_targs = second_unique_candidate_targs;
2928                                                         continue;
2929                                                 }
2930
2931                                                 //
2932                                                 // This should always cause type inference failure
2933                                                 //
2934                                                 failed = true;
2935                                                 return 1;
2936                                         }
2937
2938                                         unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
2939                                 }
2940
2941                                 if (unique_candidate_targs != null) {
2942                                         var ga_open_v = open_v.TypeParameters;
2943                                         int score = 0;
2944                                         for (int i = 0; i < unique_candidate_targs.Length; ++i) {
2945                                                 Variance variance = ga_open_v [i].Variance;
2946
2947                                                 TypeSpec u_i = unique_candidate_targs [i];
2948                                                 if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
2949                                                         if (ExactInference (u_i, ga_v [i]) == 0)
2950                                                                 ++score;
2951                                                 } else {
2952                                                         bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
2953                                                                 (variance == Variance.Covariant && inversed);
2954
2955                                                         if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
2956                                                                 ++score;
2957                                                 }
2958                                         }
2959                                         return score;
2960                                 }
2961                         }
2962
2963                         return 0;
2964                 }
2965
2966                 //
2967                 // 26.3.3.6 Output Type Inference
2968                 //
2969                 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
2970                 {
2971                         // If e is a lambda or anonymous method with inferred return type
2972                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
2973                         if (ame != null) {
2974                                 TypeSpec rt = ame.InferReturnType (ec, this, t);
2975                                 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
2976
2977                                 if (rt == null) {
2978                                         AParametersCollection pd = invoke.Parameters;
2979                                         return ame.Parameters.Count == pd.Count ? 1 : 0;
2980                                 }
2981
2982                                 TypeSpec rtype = invoke.ReturnType;
2983                                 return LowerBoundInference (rt, rtype) + 1;
2984                         }
2985
2986                         //
2987                         // if E is a method group and T is a delegate type or expression tree type
2988                         // return type Tb with parameter types T1..Tk and return type Tb, and overload
2989                         // resolution of E with the types T1..Tk yields a single method with return type U,
2990                         // then a lower-bound inference is made from U for Tb.
2991                         //
2992                         if (e is MethodGroupExpr) {
2993                                 if (!TypeManager.IsDelegateType (t)) {
2994                                         if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
2995                                                 return 0;
2996
2997                                         t = TypeManager.GetTypeArguments (t)[0];
2998                                 }
2999
3000                                 var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
3001                                 TypeSpec rtype = invoke.ReturnType;
3002
3003                                 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3004                                         return 0;
3005
3006                                 // LAMESPEC: Standard does not specify that all methodgroup arguments
3007                                 // has to be fixed but it does not specify how to do recursive type inference
3008                                 // either. We choose the simple option and infer return type only
3009                                 // if all delegate generic arguments are fixed.
3010                                 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3011                                 for (int i = 0; i < param_types.Length; ++i) {
3012                                         var inflated = InflateGenericArgument (invoke.Parameters.Types[i]);
3013                                         if (inflated == null)
3014                                                 return 0;
3015
3016                                         param_types[i] = inflated;
3017                                 }
3018
3019                                 MethodGroupExpr mg = (MethodGroupExpr) e;
3020                                 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3021                                 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3022                                 if (mg == null)
3023                                         return 0;
3024
3025                                 return LowerBoundInference (mg.BestCandidate.ReturnType, rtype) + 1;
3026                         }
3027
3028                         //
3029                         // if e is an expression with type U, then
3030                         // a lower-bound inference is made from U for T
3031                         //
3032                         return LowerBoundInference (e.Type, t) * 2;
3033                 }
3034
3035                 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3036                 {
3037                         int idx = IsUnfixed (returnType);
3038                         if (idx >= 0) {
3039                                 types [idx] = null;
3040                                 return;
3041                         }
3042
3043                         if (TypeManager.IsGenericType (returnType)) {
3044                                 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3045                                         RemoveDependentTypes (types, t);
3046                                 }
3047                         }
3048                 }
3049
3050                 public bool UnfixedVariableExists {
3051                         get {
3052                                 if (unfixed_types == null)
3053                                         return false;
3054
3055                                 foreach (TypeSpec ut in unfixed_types)
3056                                         if (ut != null)
3057                                                 return true;
3058                                 return false;
3059                         }
3060                 }
3061         }
3062 }