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