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