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