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