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