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