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