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