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