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