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