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