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