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