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