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