2008-02-13 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 // Licensed under the terms of the GNU GPL
9 //
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
12 //
13 using System;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Globalization;
17 using System.Collections;
18 using System.Text;
19 using System.Text.RegularExpressions;
20         
21 namespace Mono.CSharp {
22
23         /// <summary>
24         ///   Abstract base class for type parameter constraints.
25         ///   The type parameter can come from a generic type definition or from reflection.
26         /// </summary>
27         public abstract class GenericConstraints {
28                 public abstract string TypeParameter {
29                         get;
30                 }
31
32                 public abstract GenericParameterAttributes Attributes {
33                         get;
34                 }
35
36                 public bool HasConstructorConstraint {
37                         get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
38                 }
39
40                 public bool HasReferenceTypeConstraint {
41                         get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
42                 }
43
44                 public bool HasValueTypeConstraint {
45                         get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
46                 }
47
48                 public virtual bool HasClassConstraint {
49                         get { return ClassConstraint != null; }
50                 }
51
52                 public abstract Type ClassConstraint {
53                         get;
54                 }
55
56                 public abstract Type[] InterfaceConstraints {
57                         get;
58                 }
59
60                 public abstract Type EffectiveBaseClass {
61                         get;
62                 }
63
64                 // <summary>
65                 //   Returns whether the type parameter is "known to be a reference type".
66                 // </summary>
67                 public virtual bool IsReferenceType {
68                         get {
69                                 if (HasReferenceTypeConstraint)
70                                         return true;
71                                 if (HasValueTypeConstraint)
72                                         return false;
73
74                                 if (ClassConstraint != null) {
75                                         if (ClassConstraint.IsValueType)
76                                                 return false;
77
78                                         if (ClassConstraint != TypeManager.object_type)
79                                                 return true;
80                                 }
81
82                                 foreach (Type t in InterfaceConstraints) {
83                                         if (!t.IsGenericParameter)
84                                                 continue;
85
86                                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
87                                         if ((gc != null) && gc.IsReferenceType)
88                                                 return true;
89                                 }
90
91                                 return false;
92                         }
93                 }
94
95                 // <summary>
96                 //   Returns whether the type parameter is "known to be a value type".
97                 // </summary>
98                 public virtual bool IsValueType {
99                         get {
100                                 if (HasValueTypeConstraint)
101                                         return true;
102                                 if (HasReferenceTypeConstraint)
103                                         return false;
104
105                                 if (ClassConstraint != null) {
106                                         if (!ClassConstraint.IsValueType)
107                                                 return false;
108
109                                         if (ClassConstraint != TypeManager.value_type)
110                                                 return true;
111                                 }
112
113                                 foreach (Type t in InterfaceConstraints) {
114                                         if (!t.IsGenericParameter)
115                                                 continue;
116
117                                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
118                                         if ((gc != null) && gc.IsValueType)
119                                                 return true;
120                                 }
121
122                                 return false;
123                         }
124                 }
125         }
126
127         public enum SpecialConstraint
128         {
129                 Constructor,
130                 ReferenceType,
131                 ValueType
132         }
133
134         /// <summary>
135         ///   Tracks the constraints for a type parameter from a generic type definition.
136         /// </summary>
137         public class Constraints : GenericConstraints {
138                 string name;
139                 ArrayList constraints;
140                 Location loc;
141                 
142                 //
143                 // name is the identifier, constraints is an arraylist of
144                 // Expressions (with types) or `true' for the constructor constraint.
145                 // 
146                 public Constraints (string name, ArrayList constraints,
147                                     Location loc)
148                 {
149                         this.name = name;
150                         this.constraints = constraints;
151                         this.loc = loc;
152                 }
153
154                 public override string TypeParameter {
155                         get {
156                                 return name;
157                         }
158                 }
159
160                 public Constraints Clone ()
161                 {
162                         return new Constraints (name, constraints, loc);
163                 }
164
165                 GenericParameterAttributes attrs;
166                 TypeExpr class_constraint;
167                 ArrayList iface_constraints;
168                 ArrayList type_param_constraints;
169                 int num_constraints;
170                 Type class_constraint_type;
171                 Type[] iface_constraint_types;
172                 Type effective_base_type;
173                 bool resolved;
174                 bool resolved_types;
175
176                 /// <summary>
177                 ///   Resolve the constraints - but only resolve things into Expression's, not
178                 ///   into actual types.
179                 /// </summary>
180                 public bool Resolve (IResolveContext ec)
181                 {
182                         if (resolved)
183                                 return true;
184
185                         iface_constraints = new ArrayList ();
186                         type_param_constraints = new ArrayList ();
187
188                         foreach (object obj in constraints) {
189                                 if (HasConstructorConstraint) {
190                                         Report.Error (401, loc,
191                                                       "The new() constraint must be the last constraint specified");
192                                         return false;
193                                 }
194
195                                 if (obj is SpecialConstraint) {
196                                         SpecialConstraint sc = (SpecialConstraint) obj;
197
198                                         if (sc == SpecialConstraint.Constructor) {
199                                                 if (!HasValueTypeConstraint) {
200                                                         attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
201                                                         continue;
202                                                 }
203
204                                                 Report.Error (451, loc, "The `new()' constraint " +
205                                                         "cannot be used with the `struct' constraint");
206                                                 return false;
207                                         }
208
209                                         if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
210                                                 Report.Error (449, loc, "The `class' or `struct' " +
211                                                               "constraint must be the first constraint specified");
212                                                 return false;
213                                         }
214
215                                         if (sc == SpecialConstraint.ReferenceType)
216                                                 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
217                                         else
218                                                 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
219                                         continue;
220                                 }
221
222                                 int errors = Report.Errors;
223                                 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
224
225                                 if (fn == null) {
226                                         if (errors != Report.Errors)
227                                                 return false;
228
229                                         NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
230                                         return false;
231                                 }
232
233                                 TypeExpr expr;
234                                 ConstructedType cexpr = fn as ConstructedType;
235                                 if (cexpr != null) {
236                                         if (!cexpr.ResolveConstructedType (ec))
237                                                 return false;
238
239                                         expr = cexpr;
240                                 } else
241                                         expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
242
243                                 if ((expr == null) || (expr.Type == null))
244                                         return false;
245
246                                 if (!ec.GenericDeclContainer.IsAccessibleAs (fn.Type)) {
247                                         Report.SymbolRelatedToPreviousError (fn.Type);
248                                         Report.Error (703, loc,
249                                                 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
250                                                 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
251                                         return false;
252                                 }
253
254                                 TypeParameterExpr texpr = expr as TypeParameterExpr;
255                                 if (texpr != null)
256                                         type_param_constraints.Add (expr);
257                                 else if (expr.IsInterface)
258                                         iface_constraints.Add (expr);
259                                 else if (class_constraint != null) {
260                                         Report.Error (406, loc,
261                                                       "`{0}': the class constraint for `{1}' " +
262                                                       "must come before any other constraints.",
263                                                       expr.Name, name);
264                                         return false;
265                                 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
266                                         Report.Error (450, loc, "`{0}': cannot specify both " +
267                                                       "a constraint class and the `class' " +
268                                                       "or `struct' constraint", expr.GetSignatureForError ());
269                                         return false;
270                                 } else
271                                         class_constraint = expr;
272
273                                 num_constraints++;
274                         }
275
276                         ArrayList list = new ArrayList ();
277                         foreach (TypeExpr iface_constraint in iface_constraints) {
278                                 foreach (Type type in list) {
279                                         if (!type.Equals (iface_constraint.Type))
280                                                 continue;
281
282                                         Report.Error (405, loc,
283                                                       "Duplicate constraint `{0}' for type " +
284                                                       "parameter `{1}'.", iface_constraint.GetSignatureForError (),
285                                                       name);
286                                         return false;
287                                 }
288
289                                 list.Add (iface_constraint.Type);
290                         }
291
292                         foreach (TypeParameterExpr expr in type_param_constraints) {
293                                 foreach (Type type in list) {
294                                         if (!type.Equals (expr.Type))
295                                                 continue;
296
297                                         Report.Error (405, loc,
298                                                       "Duplicate constraint `{0}' for type " +
299                                                       "parameter `{1}'.", expr.GetSignatureForError (), name);
300                                         return false;
301                                 }
302
303                                 list.Add (expr.Type);
304                         }
305
306                         iface_constraint_types = new Type [list.Count];
307                         list.CopyTo (iface_constraint_types, 0);
308
309                         if (class_constraint != null) {
310                                 class_constraint_type = class_constraint.Type;
311                                 if (class_constraint_type == null)
312                                         return false;
313
314                                 if (class_constraint_type.IsSealed) {
315                                         if (class_constraint_type.IsAbstract)
316                                         {
317                                                 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
318                                                         TypeManager.CSharpName (class_constraint_type));
319                                         }
320                                         else
321                                         {
322                                                 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
323                                                         "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
324                                         }
325                                         return false;
326                                 }
327
328                                 if ((class_constraint_type == TypeManager.array_type) ||
329                                     (class_constraint_type == TypeManager.delegate_type) ||
330                                     (class_constraint_type == TypeManager.enum_type) ||
331                                     (class_constraint_type == TypeManager.value_type) ||
332                                     (class_constraint_type == TypeManager.object_type) ||
333                                         class_constraint_type == TypeManager.multicast_delegate_type) {
334                                         Report.Error (702, loc,
335                                                           "A constraint cannot be special class `{0}'",
336                                                       TypeManager.CSharpName (class_constraint_type));
337                                         return false;
338                                 }
339                         }
340
341                         if (class_constraint_type != null)
342                                 effective_base_type = class_constraint_type;
343                         else if (HasValueTypeConstraint)
344                                 effective_base_type = TypeManager.value_type;
345                         else
346                                 effective_base_type = TypeManager.object_type;
347
348                         resolved = true;
349                         return true;
350                 }
351
352                 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
353                 {
354                         seen.Add (tparam, true);
355
356                         Constraints constraints = tparam.Constraints;
357                         if (constraints == null)
358                                 return true;
359
360                         if (constraints.HasValueTypeConstraint) {
361                                 Report.Error (456, loc, "Type parameter `{0}' has " +
362                                               "the `struct' constraint, so it cannot " +
363                                               "be used as a constraint for `{1}'",
364                                               tparam.Name, name);
365                                 return false;
366                         }
367
368                         if (constraints.type_param_constraints == null)
369                                 return true;
370
371                         foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
372                                 if (seen.Contains (expr.TypeParameter)) {
373                                         Report.Error (454, loc, "Circular constraint " +
374                                                       "dependency involving `{0}' and `{1}'",
375                                                       tparam.Name, expr.Name);
376                                         return false;
377                                 }
378
379                                 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
380                                         return false;
381                         }
382
383                         return true;
384                 }
385
386                 /// <summary>
387                 ///   Resolve the constraints into actual types.
388                 /// </summary>
389                 public bool ResolveTypes (IResolveContext ec)
390                 {
391                         if (resolved_types)
392                                 return true;
393
394                         resolved_types = true;
395
396                         foreach (object obj in constraints) {
397                                 ConstructedType cexpr = obj as ConstructedType;
398                                 if (cexpr == null)
399                                         continue;
400
401                                 if (!cexpr.CheckConstraints (ec))
402                                         return false;
403                         }
404
405                         foreach (TypeParameterExpr expr in type_param_constraints) {
406                                 Hashtable seen = new Hashtable ();
407                                 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
408                                         return false;
409                         }
410
411                         for (int i = 0; i < iface_constraints.Count; ++i) {
412                                 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
413                                 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
414                                 if (iface_constraint == null)
415                                         return false;
416                                 iface_constraints [i] = iface_constraint;
417                         }
418
419                         if (class_constraint != null) {
420                                 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
421                                 if (class_constraint == null)
422                                         return false;
423                         }
424
425                         return true;
426                 }
427
428                 /// <summary>
429                 ///   Check whether there are no conflicts in our type parameter constraints.
430                 ///
431                 ///   This is an example:
432                 ///
433                 ///   class Foo<T,U>
434                 ///      where T : class
435                 ///      where U : T, struct
436                 /// </summary>
437                 public bool CheckDependencies ()
438                 {
439                         foreach (TypeParameterExpr expr in type_param_constraints) {
440                                 if (!CheckDependencies (expr.TypeParameter))
441                                         return false;
442                         }
443
444                         return true;
445                 }
446
447                 bool CheckDependencies (TypeParameter tparam)
448                 {
449                         Constraints constraints = tparam.Constraints;
450                         if (constraints == null)
451                                 return true;
452
453                         if (HasValueTypeConstraint && constraints.HasClassConstraint) {
454                                 Report.Error (455, loc, "Type parameter `{0}' inherits " +
455                                               "conflicting constraints `{1}' and `{2}'",
456                                               name, TypeManager.CSharpName (constraints.ClassConstraint),
457                                               "System.ValueType");
458                                 return false;
459                         }
460
461                         if (HasClassConstraint && constraints.HasClassConstraint) {
462                                 Type t1 = ClassConstraint;
463                                 TypeExpr e1 = class_constraint;
464                                 Type t2 = constraints.ClassConstraint;
465                                 TypeExpr e2 = constraints.class_constraint;
466
467                                 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
468                                     !Convert.ImplicitReferenceConversionExists (e2, t1)) {
469                                         Report.Error (455, loc,
470                                                       "Type parameter `{0}' inherits " +
471                                                       "conflicting constraints `{1}' and `{2}'",
472                                                       name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
473                                         return false;
474                                 }
475                         }
476
477                         if (constraints.type_param_constraints == null)
478                                 return true;
479
480                         foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
481                                 if (!CheckDependencies (expr.TypeParameter))
482                                         return false;
483                         }
484
485                         return true;
486                 }
487
488                 public override GenericParameterAttributes Attributes {
489                         get { return attrs; }
490                 }
491
492                 public override bool HasClassConstraint {
493                         get { return class_constraint != null; }
494                 }
495
496                 public override Type ClassConstraint {
497                         get { return class_constraint_type; }
498                 }
499
500                 public override Type[] InterfaceConstraints {
501                         get { return iface_constraint_types; }
502                 }
503
504                 public override Type EffectiveBaseClass {
505                         get { return effective_base_type; }
506                 }
507
508                 public bool IsSubclassOf (Type t)
509                 {
510                         if ((class_constraint_type != null) &&
511                             class_constraint_type.IsSubclassOf (t))
512                                 return true;
513
514                         if (iface_constraint_types == null)
515                                 return false;
516
517                         foreach (Type iface in iface_constraint_types) {
518                                 if (TypeManager.IsSubclassOf (iface, t))
519                                         return true;
520                         }
521
522                         return false;
523                 }
524
525                 public Location Location {
526                         get {
527                                 return loc;
528                         }
529                 }
530
531                 /// <summary>
532                 ///   This is used when we're implementing a generic interface method.
533                 ///   Each method type parameter in implementing method must have the same
534                 ///   constraints than the corresponding type parameter in the interface
535                 ///   method.  To do that, we're called on each of the implementing method's
536                 ///   type parameters.
537                 /// </summary>
538                 public bool CheckInterfaceMethod (GenericConstraints gc)
539                 {
540                         if (gc.Attributes != attrs)
541                                 return false;
542
543                         if (HasClassConstraint != gc.HasClassConstraint)
544                                 return false;
545                         if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
546                                 return false;
547
548                         int gc_icount = gc.InterfaceConstraints != null ?
549                                 gc.InterfaceConstraints.Length : 0;
550                         int icount = InterfaceConstraints != null ?
551                                 InterfaceConstraints.Length : 0;
552
553                         if (gc_icount != icount)
554                                 return false;
555
556                         for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
557                                 Type iface = gc.InterfaceConstraints [i];
558                                 if (iface.IsGenericType)
559                                         iface = iface.GetGenericTypeDefinition ();
560                                 
561                                 bool ok = false;
562                                 for (int ii = 0; i < InterfaceConstraints.Length; ++ii) {
563                                         Type check = InterfaceConstraints [ii];
564                                         if (check.IsGenericType)
565                                                 check = check.GetGenericTypeDefinition ();
566                                         
567                                         if (TypeManager.IsEqual (iface, check)) {
568                                                 ok = true;
569                                                 break;
570                                         }
571                                 }
572
573                                 if (!ok)
574                                         return false;
575                         }
576
577                         return true;
578                 }
579
580                 public void VerifyClsCompliance ()
581                 {
582                         if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
583                                 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
584
585                         if (iface_constraint_types != null) {
586                                 for (int i = 0; i < iface_constraint_types.Length; ++i) {
587                                         if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
588                                                 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
589                                                         ((TypeExpr)iface_constraints [i]).Location);
590                                 }
591                         }
592                 }
593
594                 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
595                 {
596                         Report.SymbolRelatedToPreviousError (t);
597                         Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
598                                 TypeManager.CSharpName (t));
599                 }
600         }
601
602         /// <summary>
603         ///   A type parameter from a generic type definition.
604         /// </summary>
605         public class TypeParameter : MemberCore, IMemberContainer
606         {
607                 string name;
608                 DeclSpace decl;
609                 GenericConstraints gc;
610                 Constraints constraints;
611                 Location loc;
612                 GenericTypeParameterBuilder type;
613                 MemberCache member_cache;
614
615                 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
616                                       Constraints constraints, Attributes attrs, Location loc)
617                         : base (parent, new MemberName (name, loc), attrs)
618                 {
619                         this.name = name;
620                         this.decl = decl;
621                         this.constraints = constraints;
622                         this.loc = loc;
623                 }
624
625                 public GenericConstraints GenericConstraints {
626                         get { return gc != null ? gc : constraints; }
627                 }
628
629                 public Constraints Constraints {
630                         get { return constraints; }
631                 }
632
633                 public DeclSpace DeclSpace {
634                         get { return decl; }
635                 }
636
637                 public Type Type {
638                         get { return type; }
639                 }
640
641                 /// <summary>
642                 ///   This is the first method which is called during the resolving
643                 ///   process; we're called immediately after creating the type parameters
644                 ///   with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
645                 ///   MethodBuilder).
646                 ///
647                 ///   We're either called from TypeContainer.DefineType() or from
648                 ///   GenericMethod.Define() (called from Method.Define()).
649                 /// </summary>
650                 public void Define (GenericTypeParameterBuilder type)
651                 {
652                         if (this.type != null)
653                                 throw new InvalidOperationException ();
654
655                         this.type = type;
656                         TypeManager.AddTypeParameter (type, this);
657                 }
658
659                 /// <summary>
660                 ///   This is the second method which is called during the resolving
661                 ///   process - in case of class type parameters, we're called from
662                 ///   TypeContainer.ResolveType() - after it resolved the class'es
663                 ///   base class and interfaces. For method type parameters, we're
664                 ///   called immediately after Define().
665                 ///
666                 ///   We're just resolving the constraints into expressions here, we
667                 ///   don't resolve them into actual types.
668                 ///
669                 ///   Note that in the special case of partial generic classes, we may be
670                 ///   called _before_ Define() and we may also be called multiple types.
671                 /// </summary>
672                 public bool Resolve (DeclSpace ds)
673                 {
674                         if (constraints != null) {
675                                 if (!constraints.Resolve (ds)) {
676                                         constraints = null;
677                                         return false;
678                                 }
679                         }
680
681                         return true;
682                 }
683
684                 /// <summary>
685                 ///   This is the third method which is called during the resolving
686                 ///   process.  We're called immediately after calling DefineConstraints()
687                 ///   on all of the current class'es type parameters.
688                 ///
689                 ///   Our job is to resolve the constraints to actual types.
690                 ///
691                 ///   Note that we may have circular dependencies on type parameters - this
692                 ///   is why Resolve() and ResolveType() are separate.
693                 /// </summary>
694                 public bool ResolveType (IResolveContext ec)
695                 {
696                         if (constraints != null) {
697                                 if (!constraints.ResolveTypes (ec)) {
698                                         constraints = null;
699                                         return false;
700                                 }
701                         }
702
703                         return true;
704                 }
705
706                 /// <summary>
707                 ///   This is the fourth and last method which is called during the resolving
708                 ///   process.  We're called after everything is fully resolved and actually
709                 ///   register the constraints with SRE and the TypeManager.
710                 /// </summary>
711                 public bool DefineType (IResolveContext ec)
712                 {
713                         return DefineType (ec, null, null, false);
714                 }
715
716                 /// <summary>
717                 ///   This is the fith and last method which is called during the resolving
718                 ///   process.  We're called after everything is fully resolved and actually
719                 ///   register the constraints with SRE and the TypeManager.
720                 ///
721                 ///   The `builder', `implementing' and `is_override' arguments are only
722                 ///   applicable to method type parameters.
723                 /// </summary>
724                 public bool DefineType (IResolveContext ec, MethodBuilder builder,
725                                         MethodInfo implementing, bool is_override)
726                 {
727                         if (!ResolveType (ec))
728                                 return false;
729
730                         if (implementing != null) {
731                                 if (is_override && (constraints != null)) {
732                                         Report.Error (460, loc,
733                                                 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
734                                                 TypeManager.CSharpSignature (builder));
735                                         return false;
736                                 }
737
738                                 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
739
740                                 int pos = type.GenericParameterPosition;
741                                 Type mparam = mb.GetGenericArguments () [pos];
742                                 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
743
744                                 if (temp_gc != null)
745                                         gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
746                                 else if (constraints != null)
747                                         gc = new InflatedConstraints (constraints, implementing.DeclaringType);
748
749                                 bool ok = true;
750                                 if (constraints != null) {
751                                         if (temp_gc == null)
752                                                 ok = false;
753                                         else if (!constraints.CheckInterfaceMethod (gc))
754                                                 ok = false;
755                                 } else {
756                                         if (!is_override && (temp_gc != null))
757                                                 ok = false;
758                                 }
759
760                                 if (!ok) {
761                                         Report.SymbolRelatedToPreviousError (implementing);
762
763                                         Report.Error (
764                                                 425, loc, "The constraints for type " +
765                                                 "parameter `{0}' of method `{1}' must match " +
766                                                 "the constraints for type parameter `{2}' " +
767                                                 "of interface method `{3}'. Consider using " +
768                                                 "an explicit interface implementation instead",
769                                                 Name, TypeManager.CSharpSignature (builder),
770                                                 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
771                                         return false;
772                                 }
773                         } else if (DeclSpace is CompilerGeneratedClass) {
774                                 TypeParameter[] tparams = DeclSpace.TypeParameters;
775                                 Type[] types = new Type [tparams.Length];
776                                 for (int i = 0; i < tparams.Length; i++)
777                                         types [i] = tparams [i].Type;
778
779                                 if (constraints != null)
780                                         gc = new InflatedConstraints (constraints, types);
781                         } else {
782                                 gc = (GenericConstraints) constraints;
783                         }
784
785                         if (gc == null)
786                                 return true;
787
788                         if (gc.HasClassConstraint)
789                                 type.SetBaseTypeConstraint (gc.ClassConstraint);
790
791                         type.SetInterfaceConstraints (gc.InterfaceConstraints);
792                         type.SetGenericParameterAttributes (gc.Attributes);
793                         TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
794
795                         return true;
796                 }
797
798                 /// <summary>
799                 ///   Check whether there are no conflicts in our type parameter constraints.
800                 ///
801                 ///   This is an example:
802                 ///
803                 ///   class Foo<T,U>
804                 ///      where T : class
805                 ///      where U : T, struct
806                 /// </summary>
807                 public bool CheckDependencies ()
808                 {
809                         if (constraints != null)
810                                 return constraints.CheckDependencies ();
811
812                         return true;
813                 }
814
815                 /// <summary>
816                 ///   This is called for each part of a partial generic type definition.
817                 ///
818                 ///   If `new_constraints' is not null and we don't already have constraints,
819                 ///   they become our constraints.  If we already have constraints, we must
820                 ///   check that they're the same.
821                 ///   con
822                 /// </summary>
823                 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
824                 {
825                         if (type == null)
826                                 throw new InvalidOperationException ();
827
828                         if (new_constraints == null)
829                                 return true;
830
831                         if (!new_constraints.Resolve (ec))
832                                 return false;
833                         if (!new_constraints.ResolveTypes (ec))
834                                 return false;
835
836                         if (constraints != null) 
837                                 return constraints.CheckInterfaceMethod (new_constraints);
838
839                         constraints = new_constraints;
840                         return true;
841                 }
842
843                 public override void Emit ()
844                 {
845                         if (OptAttributes != null)
846                                 OptAttributes.Emit ();
847
848                         base.Emit ();
849                 }
850
851                 public override string DocCommentHeader {
852                         get {
853                                 throw new InvalidOperationException (
854                                         "Unexpected attempt to get doc comment from " + this.GetType () + ".");
855                         }
856                 }
857
858                 //
859                 // MemberContainer
860                 //
861
862                 public override bool Define ()
863                 {
864                         return true;
865                 }
866
867                 public override void ApplyAttributeBuilder (Attribute a,
868                                                             CustomAttributeBuilder cb)
869                 {
870                         type.SetCustomAttribute (cb);
871                 }
872
873                 public override AttributeTargets AttributeTargets {
874                         get {
875                                 return (AttributeTargets) AttributeTargets.GenericParameter;
876                         }
877                 }
878
879                 public override string[] ValidAttributeTargets {
880                         get {
881                                 return new string [] { "type parameter" };
882                         }
883                 }
884
885                 //
886                 // IMemberContainer
887                 //
888
889                 string IMemberContainer.Name {
890                         get { return Name; }
891                 }
892
893                 MemberCache IMemberContainer.BaseCache {
894                         get {
895                                 if (gc == null)
896                                         return null;
897
898                                 if (gc.EffectiveBaseClass.BaseType == null)
899                                         return null;
900
901                                 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
902                         }
903                 }
904
905                 bool IMemberContainer.IsInterface {
906                         get { return false; }
907                 }
908
909                 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
910                 {
911                         return FindMembers (mt, bf, null, null);
912                 }
913
914                 public MemberCache MemberCache {
915                         get {
916                                 if (member_cache != null)
917                                         return member_cache;
918
919                                 if (gc == null)
920                                         return null;
921
922                                 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
923                                 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
924
925                                 return member_cache;
926                         }
927                 }
928
929                 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
930                                                MemberFilter filter, object criteria)
931                 {
932                         if (gc == null)
933                                 return MemberList.Empty;
934
935                         ArrayList members = new ArrayList ();
936
937                         if (gc.HasClassConstraint) {
938                                 MemberList list = TypeManager.FindMembers (
939                                         gc.ClassConstraint, mt, bf, filter, criteria);
940
941                                 members.AddRange (list);
942                         }
943
944                         Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
945                         foreach (Type t in ifaces) {
946                                 MemberList list = TypeManager.FindMembers (
947                                         t, mt, bf, filter, criteria);
948
949                                 members.AddRange (list);
950                         }
951
952                         return new MemberList (members);
953                 }
954
955                 public bool IsSubclassOf (Type t)
956                 {
957                         if (type.Equals (t))
958                                 return true;
959
960                         if (constraints != null)
961                                 return constraints.IsSubclassOf (t);
962
963                         return false;
964                 }
965
966                 public override string ToString ()
967                 {
968                         return "TypeParameter[" + name + "]";
969                 }
970
971                 public static string GetSignatureForError (TypeParameter[] tp)
972                 {
973                         if (tp == null || tp.Length == 0)
974                                 return "";
975
976                         StringBuilder sb = new StringBuilder ("<");
977                         for (int i = 0; i < tp.Length; ++i) {
978                                 if (i > 0)
979                                         sb.Append (",");
980                                 sb.Append (tp[i].GetSignatureForError ());
981                         }
982                         sb.Append ('>');
983                         return sb.ToString ();
984                 }
985
986                 public void InflateConstraints (Type declaring)
987                 {
988                         if (constraints != null)
989                                 gc = new InflatedConstraints (constraints, declaring);
990                 }
991                 
992                 public override bool IsClsComplianceRequired ()
993                 {
994                         return false;
995                 }
996
997                 protected class InflatedConstraints : GenericConstraints
998                 {
999                         GenericConstraints gc;
1000                         Type base_type;
1001                         Type class_constraint;
1002                         Type[] iface_constraints;
1003                         Type[] dargs;
1004
1005                         public InflatedConstraints (GenericConstraints gc, Type declaring)
1006                                 : this (gc, TypeManager.GetTypeArguments (declaring))
1007                         { }
1008
1009                         public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1010                         {
1011                                 this.gc = gc;
1012                                 this.dargs = dargs;
1013
1014                                 ArrayList list = new ArrayList ();
1015                                 if (gc.HasClassConstraint)
1016                                         list.Add (inflate (gc.ClassConstraint));
1017                                 foreach (Type iface in gc.InterfaceConstraints)
1018                                         list.Add (inflate (iface));
1019
1020                                 bool has_class_constr = false;
1021                                 if (list.Count > 0) {
1022                                         Type first = (Type) list [0];
1023                                         has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1024                                 }
1025
1026                                 if ((list.Count > 0) && has_class_constr) {
1027                                         class_constraint = (Type) list [0];
1028                                         iface_constraints = new Type [list.Count - 1];
1029                                         list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1030                                 } else {
1031                                         iface_constraints = new Type [list.Count];
1032                                         list.CopyTo (iface_constraints, 0);
1033                                 }
1034
1035                                 if (HasValueTypeConstraint)
1036                                         base_type = TypeManager.value_type;
1037                                 else if (class_constraint != null)
1038                                         base_type = class_constraint;
1039                                 else
1040                                         base_type = TypeManager.object_type;
1041                         }
1042
1043                         Type inflate (Type t)
1044                         {
1045                                 if (t == null)
1046                                         return null;
1047                                 if (t.IsGenericParameter)
1048                                         return dargs [t.GenericParameterPosition];
1049                                 if (t.IsGenericType) {
1050                                         Type[] args = t.GetGenericArguments ();
1051                                         Type[] inflated = new Type [args.Length];
1052
1053                                         for (int i = 0; i < args.Length; i++)
1054                                                 inflated [i] = inflate (args [i]);
1055
1056                                         t = t.GetGenericTypeDefinition ();
1057                                         t = t.MakeGenericType (inflated);
1058                                 }
1059
1060                                 return t;
1061                         }
1062
1063                         public override string TypeParameter {
1064                                 get { return gc.TypeParameter; }
1065                         }
1066
1067                         public override GenericParameterAttributes Attributes {
1068                                 get { return gc.Attributes; }
1069                         }
1070
1071                         public override Type ClassConstraint {
1072                                 get { return class_constraint; }
1073                         }
1074
1075                         public override Type EffectiveBaseClass {
1076                                 get { return base_type; }
1077                         }
1078
1079                         public override Type[] InterfaceConstraints {
1080                                 get { return iface_constraints; }
1081                         }
1082                 }
1083         }
1084
1085         /// <summary>
1086         ///   A TypeExpr which already resolved to a type parameter.
1087         /// </summary>
1088         public class TypeParameterExpr : TypeExpr {
1089                 TypeParameter type_parameter;
1090
1091                 public override string Name {
1092                         get {
1093                                 return type_parameter.Name;
1094                         }
1095                 }
1096
1097                 public override string FullName {
1098                         get {
1099                                 return type_parameter.Name;
1100                         }
1101                 }
1102
1103                 public TypeParameter TypeParameter {
1104                         get {
1105                                 return type_parameter;
1106                         }
1107                 }
1108                 
1109                 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1110                 {
1111                         this.type_parameter = type_parameter;
1112                         this.loc = loc;
1113                 }
1114
1115                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1116                 {
1117                         type = type_parameter.Type;
1118
1119                         return this;
1120                 }
1121
1122                 public override bool IsInterface {
1123                         get { return false; }
1124                 }
1125
1126                 public override bool CheckAccessLevel (DeclSpace ds)
1127                 {
1128                         return true;
1129                 }
1130
1131                 public void Error_CannotUseAsUnmanagedType (Location loc)
1132                 {
1133                         Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1134                 }
1135         }
1136
1137         /// <summary>
1138         ///   Tracks the type arguments when instantiating a generic type.  We're used in
1139         ///   ConstructedType.
1140         /// </summary>
1141         public class TypeArguments {
1142                 public readonly Location Location;
1143                 ArrayList args;
1144                 Type[] atypes;
1145                 int dimension;
1146                 bool has_type_args;
1147                 bool created;
1148                 
1149                 public TypeArguments (Location loc)
1150                 {
1151                         args = new ArrayList ();
1152                         this.Location = loc;
1153                 }
1154
1155                 public TypeArguments (Location loc, params Expression[] types)
1156                 {
1157                         this.Location = loc;
1158                         this.args = new ArrayList (types);
1159                 }
1160                 
1161                 public TypeArguments (int dimension, Location loc)
1162                 {
1163                         this.dimension = dimension;
1164                         this.Location = loc;
1165                 }
1166
1167                 public void Add (Expression type)
1168                 {
1169                         if (created)
1170                                 throw new InvalidOperationException ();
1171
1172                         args.Add (type);
1173                 }
1174
1175                 public void Add (TypeArguments new_args)
1176                 {
1177                         if (created)
1178                                 throw new InvalidOperationException ();
1179
1180                         args.AddRange (new_args.args);
1181                 }
1182
1183                 /// <summary>
1184                 ///   We're used during the parsing process: the parser can't distinguish
1185                 ///   between type parameters and type arguments.  Because of that, the
1186                 ///   parser creates a `MemberName' with `TypeArguments' for both cases and
1187                 ///   in case of a generic type definition, we call GetDeclarations().
1188                 /// </summary>
1189                 public TypeParameterName[] GetDeclarations ()
1190                 {
1191                         TypeParameterName[] ret = new TypeParameterName [args.Count];
1192                         for (int i = 0; i < args.Count; i++) {
1193                                 TypeParameterName name = args [i] as TypeParameterName;
1194                                 if (name != null) {
1195                                         ret [i] = name;
1196                                         continue;
1197                                 }
1198                                 SimpleName sn = args [i] as SimpleName;
1199                                 if (sn != null) {
1200                                         ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1201                                         continue;
1202                                 }
1203
1204                                 Report.Error (81, Location, "Type parameter declaration " +
1205                                               "must be an identifier not a type");
1206                                 return null;
1207                         }
1208                         return ret;
1209                 }
1210
1211                 /// <summary>
1212                 ///   We may only be used after Resolve() is called and return the fully
1213                 ///   resolved types.
1214                 /// </summary>
1215                 public Type[] Arguments {
1216                         get {
1217                                 return atypes;
1218                         }
1219                 }
1220
1221                 public bool HasTypeArguments {
1222                         get {
1223                                 return has_type_args;
1224                         }
1225                 }
1226
1227                 public int Count {
1228                         get {
1229                                 if (dimension > 0)
1230                                         return dimension;
1231                                 else
1232                                         return args.Count;
1233                         }
1234                 }
1235
1236                 public bool IsUnbound {
1237                         get {
1238                                 return dimension > 0;
1239                         }
1240                 }
1241
1242                 public override string ToString ()
1243                 {
1244                         StringBuilder s = new StringBuilder ();
1245
1246                         int count = Count;
1247                         for (int i = 0; i < count; i++){
1248                                 //
1249                                 // FIXME: Use TypeManager.CSharpname once we have the type
1250                                 //
1251                                 if (args != null)
1252                                         s.Append (args [i].ToString ());
1253                                 if (i+1 < count)
1254                                         s.Append (",");
1255                         }
1256                         return s.ToString ();
1257                 }
1258
1259                 public string GetSignatureForError()
1260                 {
1261                         StringBuilder sb = new StringBuilder();
1262                         for (int i = 0; i < Count; ++i)
1263                         {
1264                                 Expression expr = (Expression)args [i];
1265                                 sb.Append(expr.GetSignatureForError());
1266                                 if (i + 1 < Count)
1267                                         sb.Append(',');
1268                         }
1269                         return sb.ToString();
1270                 }
1271
1272                 /// <summary>
1273                 ///   Resolve the type arguments.
1274                 /// </summary>
1275                 public bool Resolve (IResolveContext ec)
1276                 {
1277                         int count = args.Count;
1278                         bool ok = true;
1279
1280                         atypes = new Type [count];
1281
1282                         for (int i = 0; i < count; i++){
1283                                 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1284                                 if (te == null) {
1285                                         ok = false;
1286                                         continue;
1287                                 }
1288
1289                                 atypes[i] = te.Type;
1290                                 if (te.Type.IsGenericParameter) {
1291                                         if (te is TypeParameterExpr)
1292                                                 has_type_args = true;
1293                                         continue;
1294                                 }
1295
1296                                 if (te.Type.IsSealed && te.Type.IsAbstract) {
1297                                         Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1298                                                 te.GetSignatureForError ());
1299                                         return false;
1300                                 }
1301
1302                                 if (te.Type.IsPointer) {
1303                                         Report.Error (306, Location, "The type `{0}' may not be used " +
1304                                                           "as a type argument", TypeManager.CSharpName (te.Type));
1305                                         return false;
1306                                 }
1307
1308                                 if (te.Type == TypeManager.void_type) {
1309                                         Expression.Error_VoidInvalidInTheContext (Location);
1310                                         return false;
1311                                 }
1312                         }
1313                         return ok;
1314                 }
1315
1316                 public TypeArguments Clone ()
1317                 {
1318                         TypeArguments copy = new TypeArguments (Location);
1319                         foreach (Expression ta in args)
1320                                 copy.args.Add (ta);
1321
1322                         return copy;
1323                 }
1324         }
1325
1326         public class TypeParameterName : SimpleName
1327         {
1328                 Attributes attributes;
1329
1330                 public TypeParameterName (string name, Attributes attrs, Location loc)
1331                         : base (name, loc)
1332                 {
1333                         attributes = attrs;
1334                 }
1335
1336                 public Attributes OptAttributes {
1337                         get {
1338                                 return attributes;
1339                         }
1340                 }
1341         }
1342
1343         /// <summary>
1344         ///   An instantiation of a generic type.
1345         /// </summary>  
1346         public class ConstructedType : TypeExpr {
1347                 string full_name;
1348                 FullNamedExpression name;
1349                 TypeArguments args;
1350                 Type[] gen_params, atypes;
1351                 Type gt;
1352
1353                 /// <summary>
1354                 ///   Instantiate the generic type `fname' with the type arguments `args'.
1355                 /// </summary>          
1356                 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1357                 {
1358                         loc = l;
1359                         this.name = fname;
1360                         this.args = args;
1361
1362                         eclass = ExprClass.Type;
1363                         full_name = name + "<" + args.ToString () + ">";
1364                 }
1365
1366                 protected ConstructedType (TypeArguments args, Location l)
1367                 {
1368                         loc = l;
1369                         this.args = args;
1370
1371                         eclass = ExprClass.Type;
1372                 }
1373
1374                 protected ConstructedType (TypeParameter[] type_params, Location l)
1375                 {
1376                         loc = l;
1377
1378                         args = new TypeArguments (l);
1379                         foreach (TypeParameter type_param in type_params)
1380                                 args.Add (new TypeParameterExpr (type_param, l));
1381
1382                         eclass = ExprClass.Type;
1383                 }
1384
1385                 /// <summary>
1386                 ///   This is used to construct the `this' type inside a generic type definition.
1387                 /// </summary>
1388                 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1389                         : this (type_params, l)
1390                 {
1391                         gt = t.GetGenericTypeDefinition ();
1392
1393                         this.name = new TypeExpression (gt, l);
1394                         full_name = gt.FullName + "<" + args.ToString () + ">";
1395                 }
1396
1397                 /// <summary>
1398                 ///   Instantiate the generic type `t' with the type arguments `args'.
1399                 ///   Use this constructor if you already know the fully resolved
1400                 ///   generic type.
1401                 /// </summary>          
1402                 public ConstructedType (Type t, TypeArguments args, Location l)
1403                         : this (args, l)
1404                 {
1405                         gt = t.GetGenericTypeDefinition ();
1406
1407                         this.name = new TypeExpression (gt, l);
1408                         full_name = gt.FullName + "<" + args.ToString () + ">";
1409                 }
1410
1411                 public TypeArguments TypeArguments {
1412                         get { return args; }
1413                 }
1414
1415                 public override string GetSignatureForError ()
1416                 {
1417                         return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1418                 }
1419
1420                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1421                 {
1422                         if (!ResolveConstructedType (ec))
1423                                 return null;
1424
1425                         return this;
1426                 }
1427
1428                 /// <summary>
1429                 ///   Check the constraints; we're called from ResolveAsTypeTerminal()
1430                 ///   after fully resolving the constructed type.
1431                 /// </summary>
1432                 public bool CheckConstraints (IResolveContext ec)
1433                 {
1434                         return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1435                 }
1436
1437                 /// <summary>
1438                 ///   Resolve the constructed type, but don't check the constraints.
1439                 /// </summary>
1440                 public bool ResolveConstructedType (IResolveContext ec)
1441                 {
1442                         if (type != null)
1443                                 return true;
1444                         // If we already know the fully resolved generic type.
1445                         if (gt != null)
1446                                 return DoResolveType (ec);
1447
1448                         int num_args;
1449                         Type t = name.Type;
1450
1451                         if (t == null) {
1452                                 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1453                                 return false;
1454                         }
1455
1456                         num_args = TypeManager.GetNumberOfTypeArguments (t);
1457                         if (num_args == 0) {
1458                                 Report.Error (308, loc,
1459                                               "The non-generic type `{0}' cannot " +
1460                                               "be used with type arguments.",
1461                                               TypeManager.CSharpName (t));
1462                                 return false;
1463                         }
1464
1465                         gt = t.GetGenericTypeDefinition ();
1466                         return DoResolveType (ec);
1467                 }
1468
1469                 bool DoResolveType (IResolveContext ec)
1470                 {
1471                         //
1472                         // Resolve the arguments.
1473                         //
1474                         if (args.Resolve (ec) == false)
1475                                 return false;
1476
1477                         gen_params = gt.GetGenericArguments ();
1478                         atypes = args.Arguments;
1479
1480                         if (atypes.Length != gen_params.Length) {
1481                                 Report.Error (305, loc,
1482                                               "Using the generic type `{0}' " +
1483                                               "requires {1} type arguments",
1484                                               TypeManager.CSharpName (gt),
1485                                               gen_params.Length.ToString ());
1486                                 return false;
1487                         }
1488
1489                         //
1490                         // Now bind the parameters.
1491                         //
1492                         type = gt.MakeGenericType (atypes);
1493                         return true;
1494                 }
1495
1496                 public Expression GetSimpleName (EmitContext ec)
1497                 {
1498                         return this;
1499                 }
1500
1501                 public override bool CheckAccessLevel (DeclSpace ds)
1502                 {
1503                         return ds.CheckAccessLevel (gt);
1504                 }
1505
1506                 public override bool AsAccessible (DeclSpace ds)
1507                 {
1508                         foreach (Type t in atypes) {
1509                                 if (!ds.IsAccessibleAs (t))
1510                                         return false;
1511                         }
1512
1513                         return ds.IsAccessibleAs (gt);
1514                 }
1515
1516                 public override bool IsClass {
1517                         get { return gt.IsClass; }
1518                 }
1519
1520                 public override bool IsValueType {
1521                         get { return gt.IsValueType; }
1522                 }
1523
1524                 public override bool IsInterface {
1525                         get { return gt.IsInterface; }
1526                 }
1527
1528                 public override bool IsSealed {
1529                         get { return gt.IsSealed; }
1530                 }
1531
1532                 public override bool Equals (object obj)
1533                 {
1534                         ConstructedType cobj = obj as ConstructedType;
1535                         if (cobj == null)
1536                                 return false;
1537
1538                         if ((type == null) || (cobj.type == null))
1539                                 return false;
1540
1541                         return type == cobj.type;
1542                 }
1543
1544                 public override int GetHashCode ()
1545                 {
1546                         return base.GetHashCode ();
1547                 }
1548
1549                 public override string Name {
1550                         get {
1551                                 return full_name;
1552                         }
1553                 }
1554
1555                 public override string FullName {
1556                         get {
1557                                 return full_name;
1558                         }
1559                 }
1560         }
1561
1562         public abstract class ConstraintChecker
1563         {
1564                 protected readonly Type[] gen_params;
1565                 protected readonly Type[] atypes;
1566                 protected readonly Location loc;
1567
1568                 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1569                 {
1570                         this.gen_params = gen_params;
1571                         this.atypes = atypes;
1572                         this.loc = loc;
1573                 }
1574
1575                 /// <summary>
1576                 ///   Check the constraints; we're called from ResolveAsTypeTerminal()
1577                 ///   after fully resolving the constructed type.
1578                 /// </summary>
1579                 public bool CheckConstraints (IResolveContext ec)
1580                 {
1581                         for (int i = 0; i < gen_params.Length; i++) {
1582                                 if (!CheckConstraints (ec, i))
1583                                         return false;
1584                         }
1585
1586                         return true;
1587                 }
1588
1589                 protected bool CheckConstraints (IResolveContext ec, int index)
1590                 {
1591                         Type atype = atypes [index];
1592                         Type ptype = gen_params [index];
1593
1594                         if (atype == ptype)
1595                                 return true;
1596
1597                         Expression aexpr = new EmptyExpression (atype);
1598
1599                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1600                         if (gc == null)
1601                                 return true;
1602
1603                         bool is_class, is_struct;
1604                         if (atype.IsGenericParameter) {
1605                                 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1606                                 if (agc != null) {
1607                                         if (agc is Constraints)
1608                                                 ((Constraints) agc).Resolve (ec);
1609                                         is_class = agc.IsReferenceType;
1610                                         is_struct = agc.IsValueType;
1611                                 } else {
1612                                         is_class = is_struct = false;
1613                                 }
1614                         } else {
1615 #if MS_COMPATIBLE
1616                                 is_class = false;
1617                                 if (!atype.IsGenericType)
1618 #endif
1619                                 is_class = atype.IsClass || atype.IsInterface;
1620                                 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1621                         }
1622
1623                         //
1624                         // First, check the `class' and `struct' constraints.
1625                         //
1626                         if (gc.HasReferenceTypeConstraint && !is_class) {
1627                                 Report.Error (452, loc, "The type `{0}' must be " +
1628                                               "a reference type in order to use it " +
1629                                               "as type parameter `{1}' in the " +
1630                                               "generic type or method `{2}'.",
1631                                               TypeManager.CSharpName (atype),
1632                                               TypeManager.CSharpName (ptype),
1633                                               GetSignatureForError ());
1634                                 return false;
1635                         } else if (gc.HasValueTypeConstraint && !is_struct) {
1636                                 Report.Error (453, loc, "The type `{0}' must be a " +
1637                                               "non-nullable value type in order to use it " +
1638                                               "as type parameter `{1}' in the " +
1639                                               "generic type or method `{2}'.",
1640                                               TypeManager.CSharpName (atype),
1641                                               TypeManager.CSharpName (ptype),
1642                                               GetSignatureForError ());
1643                                 return false;
1644                         }
1645
1646                         //
1647                         // The class constraint comes next.
1648                         //
1649                         if (gc.HasClassConstraint) {
1650                                 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1651                                         return false;
1652                         }
1653
1654                         //
1655                         // Now, check the interface constraints.
1656                         //
1657                         if (gc.InterfaceConstraints != null) {
1658                                 foreach (Type it in gc.InterfaceConstraints) {
1659                                         if (!CheckConstraint (ec, ptype, aexpr, it))
1660                                                 return false;
1661                                 }
1662                         }
1663
1664                         //
1665                         // Finally, check the constructor constraint.
1666                         //
1667
1668                         if (!gc.HasConstructorConstraint)
1669                                 return true;
1670
1671                         if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1672                                 return true;
1673
1674                         if (HasDefaultConstructor (atype))
1675                                 return true;
1676
1677                         Report_SymbolRelatedToPreviousError ();
1678                         Report.SymbolRelatedToPreviousError (atype);
1679                         Report.Error (310, loc, "The type `{0}' must have a public " +
1680                                       "parameterless constructor in order to use it " +
1681                                       "as parameter `{1}' in the generic type or " +
1682                                       "method `{2}'",
1683                                       TypeManager.CSharpName (atype),
1684                                       TypeManager.CSharpName (ptype),
1685                                       GetSignatureForError ());
1686                         return false;
1687                 }
1688
1689                 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1690                                                 Type ctype)
1691                 {
1692                         if (TypeManager.HasGenericArguments (ctype)) {
1693                                 Type[] types = TypeManager.GetTypeArguments (ctype);
1694
1695                                 TypeArguments new_args = new TypeArguments (loc);
1696
1697                                 for (int i = 0; i < types.Length; i++) {
1698                                         Type t = types [i];
1699
1700                                         if (t.IsGenericParameter) {
1701                                                 int pos = t.GenericParameterPosition;
1702                                                 t = atypes [pos];
1703                                         }
1704                                         new_args.Add (new TypeExpression (t, loc));
1705                                 }
1706
1707                                 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1708                                 if (ct.ResolveAsTypeStep (ec, false) == null)
1709                                         return false;
1710                                 ctype = ct.Type;
1711                         } else if (ctype.IsGenericParameter) {
1712                                 int pos = ctype.GenericParameterPosition;
1713                                 ctype = atypes [pos];
1714                         }
1715
1716                         if (Convert.ImplicitStandardConversionExists (expr, ctype))
1717                                 return true;
1718
1719                         Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1720                         return false;
1721                 }
1722
1723                 bool HasDefaultConstructor (Type atype)
1724                 {
1725                         if (atype.IsAbstract)
1726                                 return false;
1727
1728                 again:
1729                         atype = TypeManager.DropGenericTypeArguments (atype);
1730                         if (atype is TypeBuilder) {
1731                                 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1732                                 if (tc.InstanceConstructors == null) {
1733                                         atype = atype.BaseType;
1734                                         goto again;
1735                                 }
1736
1737                                 foreach (Constructor c in tc.InstanceConstructors) {
1738                                         if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1739                                                 continue;
1740                                         if ((c.Parameters.FixedParameters != null) &&
1741                                             (c.Parameters.FixedParameters.Length != 0))
1742                                                 continue;
1743                                         if (c.Parameters.HasArglist || c.Parameters.HasParams)
1744                                                 continue;
1745
1746                                         return true;
1747                                 }
1748                         }
1749
1750                         TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1751                         if (tparam != null) {
1752                                 if (tparam.GenericConstraints == null)
1753                                         return false;
1754                                                 
1755                                 return tparam.GenericConstraints.HasConstructorConstraint || 
1756                                         tparam.GenericConstraints.HasValueTypeConstraint;
1757                         }
1758
1759                         MemberList list = TypeManager.FindMembers (
1760                                 atype, MemberTypes.Constructor,
1761                                 BindingFlags.Public | BindingFlags.Instance |
1762                                 BindingFlags.DeclaredOnly, null, null);
1763
1764                         if (atype.IsAbstract || (list == null))
1765                                 return false;
1766
1767                         foreach (MethodBase mb in list) {
1768                                 ParameterData pd = TypeManager.GetParameterData (mb);
1769                                 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1770                                         return true;
1771                         }
1772
1773                         return false;
1774                 }
1775
1776                 protected abstract string GetSignatureForError ();
1777                 protected abstract void Report_SymbolRelatedToPreviousError ();
1778
1779                 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1780                 {
1781                         Report_SymbolRelatedToPreviousError ();
1782                         Report.SymbolRelatedToPreviousError (atype);
1783                         Report.Error (309, loc, 
1784                                       "The type `{0}' must be convertible to `{1}' in order to " +
1785                                       "use it as parameter `{2}' in the generic type or method `{3}'",
1786                                       TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1787                                       TypeManager.CSharpName (ptype), GetSignatureForError ());
1788                 }
1789
1790                 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1791                                                      MethodBase instantiated, Location loc)
1792                 {
1793                         MethodConstraintChecker checker = new MethodConstraintChecker (
1794                                 definition, definition.GetGenericArguments (),
1795                                 instantiated.GetGenericArguments (), loc);
1796
1797                         return checker.CheckConstraints (ec);
1798                 }
1799
1800                 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1801                                                      Type[] atypes, Location loc)
1802                 {
1803                         TypeConstraintChecker checker = new TypeConstraintChecker (
1804                                 gt, gen_params, atypes, loc);
1805
1806                         return checker.CheckConstraints (ec);
1807                 }
1808
1809                 protected class MethodConstraintChecker : ConstraintChecker
1810                 {
1811                         MethodBase definition;
1812
1813                         public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1814                                                         Type[] atypes, Location loc)
1815                                 : base (gen_params, atypes, loc)
1816                         {
1817                                 this.definition = definition;
1818                         }
1819
1820                         protected override string GetSignatureForError ()
1821                         {
1822                                 return TypeManager.CSharpSignature (definition);
1823                         }
1824
1825                         protected override void Report_SymbolRelatedToPreviousError ()
1826                         {
1827                                 Report.SymbolRelatedToPreviousError (definition);
1828                         }
1829                 }
1830
1831                 protected class TypeConstraintChecker : ConstraintChecker
1832                 {
1833                         Type gt;
1834
1835                         public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1836                                                       Location loc)
1837                                 : base (gen_params, atypes, loc)
1838                         {
1839                                 this.gt = gt;
1840                         }
1841
1842                         protected override string GetSignatureForError ()
1843                         {
1844                                 return TypeManager.CSharpName (gt);
1845                         }
1846
1847                         protected override void Report_SymbolRelatedToPreviousError ()
1848                         {
1849                                 Report.SymbolRelatedToPreviousError (gt);
1850                         }
1851                 }
1852         }
1853
1854         /// <summary>
1855         ///   A generic method definition.
1856         /// </summary>
1857         public class GenericMethod : DeclSpace
1858         {
1859                 Expression return_type;
1860                 Parameters parameters;
1861
1862                 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1863                                       Expression return_type, Parameters parameters)
1864                         : base (ns, parent, name, null)
1865                 {
1866                         this.return_type = return_type;
1867                         this.parameters = parameters;
1868                 }
1869
1870                 public override TypeBuilder DefineType ()
1871                 {
1872                         throw new Exception ();
1873                 }
1874
1875                 public override bool Define ()
1876                 {
1877                         for (int i = 0; i < TypeParameters.Length; i++)
1878                                 if (!TypeParameters [i].Resolve (this))
1879                                         return false;
1880
1881                         return true;
1882                 }
1883
1884                 /// <summary>
1885                 ///   Define and resolve the type parameters.
1886                 ///   We're called from Method.Define().
1887                 /// </summary>
1888                 public bool Define (MethodBuilder mb, ToplevelBlock block)
1889                 {
1890                         TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1891                         string[] snames = new string [names.Length];
1892                         for (int i = 0; i < names.Length; i++) {
1893                                 string type_argument_name = names[i].Name;
1894                                 Parameter p = parameters.GetParameterByName (type_argument_name);
1895                                 if (p != null) {
1896                                         Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1897                                         return false;
1898                                 }
1899                                 
1900                                 snames[i] = type_argument_name;
1901                         }
1902
1903                         GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1904                         for (int i = 0; i < TypeParameters.Length; i++)
1905                                 TypeParameters [i].Define (gen_params [i]);
1906
1907                         if (!Define ())
1908                                 return false;
1909
1910                         for (int i = 0; i < TypeParameters.Length; i++) {
1911                                 if (!TypeParameters [i].ResolveType (this))
1912                                         return false;
1913                         }
1914
1915                         return true;
1916                 }
1917
1918                 internal static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1919                 {
1920                         Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1921                                 name, collisionWith);
1922                 }
1923
1924                 /// <summary>
1925                 ///   We're called from MethodData.Define() after creating the MethodBuilder.
1926                 /// </summary>
1927                 public bool DefineType (EmitContext ec, MethodBuilder mb,
1928                                         MethodInfo implementing, bool is_override)
1929                 {
1930                         for (int i = 0; i < TypeParameters.Length; i++)
1931                                 if (!TypeParameters [i].DefineType (
1932                                             ec, mb, implementing, is_override))
1933                                         return false;
1934
1935                         bool ok = true;
1936                         foreach (Parameter p in parameters.FixedParameters){
1937                                 if (!p.Resolve (ec))
1938                                         ok = false;
1939                         }
1940                         if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1941                                 ok = false;
1942
1943                         return ok;
1944                 }
1945
1946                 public void EmitAttributes ()
1947                 {
1948                         for (int i = 0; i < TypeParameters.Length; i++)
1949                                 TypeParameters [i].Emit ();
1950
1951                         if (OptAttributes != null)
1952                                 OptAttributes.Emit ();
1953                 }
1954
1955                 public override bool DefineMembers ()
1956                 {
1957                         return true;
1958                 }
1959
1960                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1961                                                         MemberFilter filter, object criteria)
1962                 {
1963                         throw new Exception ();
1964                 }               
1965
1966                 public override MemberCache MemberCache {
1967                         get {
1968                                 return null;
1969                         }
1970                 }
1971
1972                 public override AttributeTargets AttributeTargets {
1973                         get {
1974                                 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1975                         }
1976                 }
1977
1978                 public override string DocCommentHeader {
1979                         get { return "M:"; }
1980                 }
1981
1982                 public new void VerifyClsCompliance ()
1983                 {
1984                         foreach (TypeParameter tp in TypeParameters) {
1985                                 if (tp.Constraints == null)
1986                                         continue;
1987
1988                                 tp.Constraints.VerifyClsCompliance ();
1989                         }
1990                 }
1991         }
1992
1993         public class NullableType : TypeExpr
1994         {
1995                 Expression underlying;
1996
1997                 public NullableType (Expression underlying, Location l)
1998                 {
1999                         this.underlying = underlying;
2000                         loc = l;
2001
2002                         eclass = ExprClass.Type;
2003                 }
2004
2005                 public NullableType (Type type, Location loc)
2006                         : this (new TypeExpression (type, loc), loc)
2007                 { }
2008
2009                 public override string Name {
2010                         get { return underlying.ToString () + "?"; }
2011                 }
2012
2013                 public override string FullName {
2014                         get { return underlying.ToString () + "?"; }
2015                 }
2016
2017                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2018                 {
2019                         TypeArguments args = new TypeArguments (loc);
2020                         args.Add (underlying);
2021
2022                         ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2023                         return ctype.ResolveAsTypeTerminal (ec, false);
2024                 }
2025         }
2026
2027         public partial class TypeManager
2028         {
2029                 //
2030                 // A list of core types that the compiler requires or uses
2031                 //
2032                 static public Type activator_type;
2033                 static public Type generic_ilist_type;
2034                 static public Type generic_icollection_type;
2035                 static public Type generic_ienumerator_type;
2036                 static public Type generic_ienumerable_type;
2037                 static public Type generic_nullable_type;
2038
2039                 //
2040                 // These methods are called by code generated by the compiler
2041                 //
2042                 static public MethodInfo activator_create_instance;
2043
2044                 static void InitGenericCoreTypes ()
2045                 {
2046                         activator_type = CoreLookupType ("System", "Activator");
2047
2048                         generic_ilist_type = CoreLookupType (
2049                                 "System.Collections.Generic", "IList", 1);
2050                         generic_icollection_type = CoreLookupType (
2051                                 "System.Collections.Generic", "ICollection", 1);
2052                         generic_ienumerator_type = CoreLookupType (
2053                                 "System.Collections.Generic", "IEnumerator", 1);
2054                         generic_ienumerable_type = CoreLookupType (
2055                                 "System.Collections.Generic", "IEnumerable", 1);
2056                         generic_nullable_type = CoreLookupType (
2057                                 "System", "Nullable", 1);
2058                 }
2059
2060                 static void InitGenericCodeHelpers ()
2061                 {
2062                         // Activator
2063                         activator_create_instance = GetCoreMethod (
2064                                 activator_type, "CreateInstance", Type.EmptyTypes);
2065                 }
2066
2067                 static Type CoreLookupType (string ns, string name, int arity)
2068                 {
2069                         return CoreLookupType (ns, MemberName.MakeName (name, arity));
2070                 }
2071
2072                 public static TypeContainer LookupGenericTypeContainer (Type t)
2073                 {
2074                         t = DropGenericTypeArguments (t);
2075                         return LookupTypeContainer (t);
2076                 }
2077
2078                 /// <summary>
2079                 ///   Check whether `a' and `b' may become equal generic types.
2080                 ///   The algorithm to do that is a little bit complicated.
2081                 /// </summary>
2082                 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2083                                                                Type[] method_inferred)
2084                 {
2085                         if (a.IsGenericParameter) {
2086                                 //
2087                                 // If a is an array of a's type, they may never
2088                                 // become equal.
2089                                 //
2090                                 while (b.IsArray) {
2091                                         b = b.GetElementType ();
2092                                         if (a.Equals (b))
2093                                                 return false;
2094                                 }
2095
2096                                 //
2097                                 // If b is a generic parameter or an actual type,
2098                                 // they may become equal:
2099                                 //
2100                                 //    class X<T,U> : I<T>, I<U>
2101                                 //    class X<T> : I<T>, I<float>
2102                                 // 
2103                                 if (b.IsGenericParameter || !b.IsGenericType) {
2104                                         int pos = a.GenericParameterPosition;
2105                                         Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2106                                         if (args [pos] == null) {
2107                                                 args [pos] = b;
2108                                                 return true;
2109                                         }
2110
2111                                         return args [pos] == a;
2112                                 }
2113
2114                                 //
2115                                 // We're now comparing a type parameter with a
2116                                 // generic instance.  They may become equal unless
2117                                 // the type parameter appears anywhere in the
2118                                 // generic instance:
2119                                 //
2120                                 //    class X<T,U> : I<T>, I<X<U>>
2121                                 //        -> error because you could instanciate it as
2122                                 //           X<X<int>,int>
2123                                 //
2124                                 //    class X<T> : I<T>, I<X<T>> -> ok
2125                                 //
2126
2127                                 Type[] bargs = GetTypeArguments (b);
2128                                 for (int i = 0; i < bargs.Length; i++) {
2129                                         if (a.Equals (bargs [i]))
2130                                                 return false;
2131                                 }
2132
2133                                 return true;
2134                         }
2135
2136                         if (b.IsGenericParameter)
2137                                 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2138
2139                         //
2140                         // At this point, neither a nor b are a type parameter.
2141                         //
2142                         // If one of them is a generic instance, let
2143                         // MayBecomeEqualGenericInstances() compare them (if the
2144                         // other one is not a generic instance, they can never
2145                         // become equal).
2146                         //
2147
2148                         if (a.IsGenericType || b.IsGenericType)
2149                                 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2150
2151                         //
2152                         // If both of them are arrays.
2153                         //
2154
2155                         if (a.IsArray && b.IsArray) {
2156                                 if (a.GetArrayRank () != b.GetArrayRank ())
2157                                         return false;
2158                         
2159                                 a = a.GetElementType ();
2160                                 b = b.GetElementType ();
2161
2162                                 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2163                         }
2164
2165                         //
2166                         // Ok, two ordinary types.
2167                         //
2168
2169                         return a.Equals (b);
2170                 }
2171
2172                 //
2173                 // Checks whether two generic instances may become equal for some
2174                 // particular instantiation (26.3.1).
2175                 //
2176                 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2177                                                                    Type[] class_inferred,
2178                                                                    Type[] method_inferred)
2179                 {
2180                         if (!a.IsGenericType || !b.IsGenericType)
2181                                 return false;
2182                         if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2183                                 return false;
2184
2185                         return MayBecomeEqualGenericInstances (
2186                                 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2187                 }
2188
2189                 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2190                                                                    Type[] class_inferred,
2191                                                                    Type[] method_inferred)
2192                 {
2193                         if (aargs.Length != bargs.Length)
2194                                 return false;
2195
2196                         for (int i = 0; i < aargs.Length; i++) {
2197                                 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2198                                         return false;
2199                         }
2200
2201                         return true;
2202                 }
2203
2204                 /// <summary>
2205                 ///   Type inference.  Try to infer the type arguments from `method',
2206                 ///   which is invoked with the arguments `arguments'.  This is used
2207                 ///   when resolving an Invocation or a DelegateInvocation and the user
2208                 ///   did not explicitly specify type arguments.
2209                 /// </summary>
2210                 public static int InferTypeArguments (EmitContext ec,
2211                                                        ArrayList arguments,
2212                                                        ref MethodBase method)
2213                 {
2214                         ATypeInference ti = ATypeInference.CreateInstance (arguments);
2215                         Type[] i_args = ti.InferMethodArguments (ec, method);
2216                         if (i_args == null)
2217                                 return ti.InferenceScore;
2218
2219                         if (i_args.Length == 0)
2220                                 return 0;
2221
2222                         method = ((MethodInfo) method).MakeGenericMethod (i_args);
2223                         return 0;
2224                 }
2225
2226                 /// <summary>
2227                 ///   Type inference.
2228                 /// </summary>
2229                 public static bool InferTypeArguments (ParameterData apd,
2230                                                        ref MethodBase method)
2231                 {
2232                         if (!TypeManager.IsGenericMethod (method))
2233                                 return true;
2234
2235                         ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2236                         Type[] i_args = ti.InferDelegateArguments (method);
2237                         if (i_args == null)
2238                                 return false;
2239
2240                         method = ((MethodInfo) method).MakeGenericMethod (i_args);
2241                         return true;
2242                 }
2243         }
2244
2245         abstract class ATypeInference
2246         {
2247                 protected readonly ArrayList arguments;
2248                 protected readonly int arg_count;
2249
2250                 protected ATypeInference (ArrayList arguments)
2251                 {
2252                         this.arguments = arguments;
2253                         if (arguments != null)
2254                                 arg_count = arguments.Count;
2255                 }
2256
2257                 public static ATypeInference CreateInstance (ArrayList arguments)
2258                 {
2259                         if (RootContext.Version == LanguageVersion.ISO_2)
2260                                 return new TypeInferenceV2 (arguments);
2261
2262                         return new TypeInferenceV3 (arguments);
2263                 }
2264
2265                 public virtual int InferenceScore {
2266                         get {
2267                                 return int.MaxValue;
2268                         }
2269                 }
2270
2271                 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2272                 public abstract Type[] InferDelegateArguments (MethodBase method);
2273         }
2274
2275         //
2276         // Implements C# 2.0 type inference
2277         //
2278         class TypeInferenceV2 : ATypeInference
2279         {
2280                 public TypeInferenceV2 (ArrayList arguments)
2281                         : base (arguments)
2282                 {
2283                 }
2284
2285                 public override Type[] InferDelegateArguments (MethodBase method)
2286                 {
2287                         ParameterData pd = TypeManager.GetParameterData (method);
2288                         if (arg_count != pd.Count)
2289                                 return null;
2290
2291                         Type[] method_args = method.GetGenericArguments ();
2292                         Type[] inferred_types = new Type[method_args.Length];
2293
2294                         Type[] param_types = new Type[pd.Count];
2295                         Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2296
2297                         for (int i = 0; i < arg_count; i++) {
2298                                 param_types[i] = pd.ParameterType (i);
2299                         }
2300
2301                         if (!InferTypeArguments (param_types, arg_types, inferred_types))
2302                                 return null;
2303
2304                         return inferred_types;
2305                 }
2306
2307                 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2308                 {
2309                         ParameterData pd = TypeManager.GetParameterData (method);
2310                         Type[] method_generic_args = method.GetGenericArguments ();
2311                         Type [] inferred_types = new Type [method_generic_args.Length];
2312                         Type[] arg_types = new Type [pd.Count];
2313
2314                         int a_count = arg_types.Length;
2315                         if (pd.HasParams)
2316                                 --a_count;
2317
2318                         for (int i = 0; i < a_count; i++) {
2319                                 Argument a = (Argument) arguments[i];
2320                                 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2321                                         continue;
2322
2323                                 if (!TypeInferenceV2.UnifyType (pd.ParameterType (i), a.Type, inferred_types))
2324                                         return null;
2325                         }
2326
2327                         if (pd.HasParams) {
2328                                 Type element_type = TypeManager.GetElementType (pd.ParameterType (a_count));
2329                                 for (int i = a_count; i < arg_count; i++) {
2330                                         Argument a = (Argument) arguments [i];
2331                                         if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2332                                                 continue;
2333
2334                                         if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2335                                                 return null;
2336                                 }
2337                         }
2338
2339                         for (int i = 0; i < inferred_types.Length; i++)
2340                                 if (inferred_types [i] == null)
2341                                         return null;
2342
2343                         return inferred_types;
2344                 }
2345
2346                 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2347                                 Type[] inferred_types)
2348                 {
2349                         for (int i = 0; i < arg_types.Length; i++) {
2350                                 if (arg_types[i] == null)
2351                                         continue;
2352
2353                                 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2354                                         return false;
2355                         }
2356
2357                         for (int i = 0; i < inferred_types.Length; ++i)
2358                                 if (inferred_types[i] == null)
2359                                         return false;
2360
2361                         return true;
2362                 }
2363
2364                 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2365                 {
2366                         if (pt.IsGenericParameter) {
2367                                 if (pt.DeclaringMethod == null)
2368                                         return pt == at;
2369
2370                                 int pos = pt.GenericParameterPosition;
2371
2372                                 if (inferred [pos] == null)
2373                                         inferred [pos] = at;
2374
2375                                 return inferred [pos] == at;
2376                         }
2377
2378                         if (!pt.ContainsGenericParameters) {
2379                                 if (at.ContainsGenericParameters)
2380                                         return UnifyType (at, pt, inferred);
2381                                 else
2382                                         return true;
2383                         }
2384
2385                         if (at.IsArray) {
2386                                 if (pt.IsArray) {
2387                                         if (at.GetArrayRank () != pt.GetArrayRank ())
2388                                                 return false;
2389
2390                                         return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2391                                 }
2392
2393                                 if (!pt.IsGenericType)
2394                                         return false;
2395
2396                                 Type gt = pt.GetGenericTypeDefinition ();
2397                                 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2398                                         (gt != TypeManager.generic_ienumerable_type))
2399                                         return false;
2400
2401                                 Type[] args = TypeManager.GetTypeArguments (pt);
2402                                 return UnifyType (args[0], at.GetElementType (), inferred);
2403                         }
2404
2405                         if (pt.IsArray) {
2406                                 if (!at.IsArray ||
2407                                         (pt.GetArrayRank () != at.GetArrayRank ()))
2408                                         return false;
2409
2410                                 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2411                         }
2412
2413                         if (pt.IsByRef && at.IsByRef)
2414                                 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2415                         ArrayList list = new ArrayList ();
2416                         if (at.IsGenericType)
2417                                 list.Add (at);
2418                         for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2419                                 list.Add (bt);
2420
2421                         list.AddRange (TypeManager.GetInterfaces (at));
2422
2423                         foreach (Type type in list) {
2424                                 if (!type.IsGenericType)
2425                                         continue;
2426
2427                                 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2428                                         continue;
2429
2430                                 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2431                                         return false;
2432                         }
2433
2434                         return true;
2435                 }
2436
2437                 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2438                 {
2439                         for (int i = 0; i < ats.Length; i++) {
2440                                 if (!UnifyType (pts [i], ats [i], inferred))
2441                                         return false;
2442                         }
2443                         return true;
2444                 }
2445         }
2446
2447         //
2448         // Implements C# 3.0 type inference
2449         //
2450         class TypeInferenceV3 : ATypeInference
2451         {
2452                 //
2453                 // Tracks successful rate of type inference
2454                 //
2455                 int score = int.MaxValue;
2456
2457                 public TypeInferenceV3 (ArrayList arguments)
2458                         : base (arguments)
2459                 {
2460                 }
2461
2462                 public override int InferenceScore {
2463                         get {
2464                                 return score;
2465                         }
2466                 }
2467
2468                 public override Type[] InferDelegateArguments (MethodBase method)
2469                 {
2470                         ParameterData pd = TypeManager.GetParameterData (method);
2471                         if (arg_count != pd.Count)
2472                                 return null;
2473
2474                         Type[] d_gargs = method.GetGenericArguments ();
2475                         TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2476
2477                         // A lower-bound inference is made from each argument type Uj of D
2478                         // to the corresponding parameter type Tj of M
2479                         for (int i = 0; i < arg_count; ++i) {
2480                                 Type t = pd.Types [i];
2481                                 if (!t.IsGenericParameter)
2482                                         continue;
2483
2484                                 context.LowerBoundInference ((Type)arguments[i], t);
2485                         }
2486
2487                         if (!context.FixAllTypes ())
2488                                 return null;
2489
2490                         return context.InferredTypeArguments;
2491                 }
2492
2493                 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2494                 {
2495                         Type[] method_generic_args = method.GetGenericArguments ();
2496                         TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2497                         if (!context.UnfixedVariableExists)
2498                                 return Type.EmptyTypes;
2499
2500                         ParameterData pd = TypeManager.GetParameterData (method);
2501                         if (!InferInPhases (ec, context, pd))
2502                                 return null;
2503
2504                         return context.InferredTypeArguments;
2505                 }
2506
2507                 //
2508                 // Implements method type arguments inference
2509                 //
2510                 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
2511                 {
2512                         int params_arguments_start;
2513                         if (methodParameters.HasParams) {
2514                                 params_arguments_start = methodParameters.Count - 1;
2515                         } else {
2516                                 params_arguments_start = arg_count;
2517                         }
2518                         
2519                         //
2520                         // The first inference phase
2521                         //
2522                         Type method_parameter = null;
2523                         for (int i = 0; i < arg_count; i++) {
2524                                 Argument a = (Argument) arguments [i];
2525                                 
2526                                 if (i < params_arguments_start) {
2527                                         method_parameter = methodParameters.Types [i];
2528                                 } else if (i == params_arguments_start) {
2529                                         if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2530                                                 method_parameter = methodParameters.Types [params_arguments_start];
2531                                         else
2532                                                 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2533                                 }
2534
2535                                 //
2536                                 // When a lambda expression, an anonymous method
2537                                 // is used an explicit argument type inference takes a place
2538                                 //
2539                                 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2540                                 if (am != null) {
2541                                         if (am.ExplicitTypeInference (tic, method_parameter))
2542                                                 --score; 
2543                                         continue;
2544                                 }
2545
2546                                 if (a.Expr.Type == TypeManager.null_type)
2547                                         continue;
2548
2549                                 //
2550                                 // Otherwise an output type inference is made
2551                                 //
2552                                 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2553                         }
2554
2555                         //
2556                         // Part of the second phase but because it happens only once
2557                         // we don't need to call it in cycle
2558                         //
2559                         bool fixed_any = false;
2560                         if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
2561                                 return false;
2562
2563                         return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
2564                 }
2565
2566                 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
2567                 {
2568                         bool fixed_any = false;
2569                         if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
2570                                 return false;
2571
2572                         // If no further unfixed type variables exist, type inference succeeds
2573                         if (!tic.UnfixedVariableExists)
2574                                 return true;
2575
2576                         if (!fixed_any && fixDependent)
2577                                 return false;
2578                         
2579                         // For all arguments where the corresponding argument output types
2580                         // contain unfixed type variables but the input types do not,
2581                         // an output type inference is made
2582                         for (int i = 0; i < arg_count; i++) {
2583                                 Type t_i = methodParameters.ParameterType (i);
2584                                 if (!TypeManager.IsDelegateType (t_i)) {
2585                                         if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
2586                                                 continue;
2587
2588                                         t_i = t_i.GetGenericArguments () [0];
2589                                 }
2590
2591                                 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2592                                 Type rtype = mi.ReturnType;
2593
2594 #if MS_COMPATIBLE
2595                                 // Blablabla, because reflection does not work with dynamic types
2596                                 Type[] g_args = t_i.GetGenericArguments ();
2597                                 rtype = g_args[rtype.GenericParameterPosition];
2598 #endif
2599
2600                                 if (tic.IsReturnTypeNonDependent (mi, rtype))
2601                                         score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2602                         }
2603
2604
2605                         return DoSecondPhase (ec, tic, methodParameters, true);
2606                 }
2607         }
2608
2609         public class TypeInferenceContext
2610         {
2611                 readonly Type[] unfixed_types;
2612                 readonly Type[] fixed_types;
2613                 readonly ArrayList[] bounds;
2614                 
2615                 public TypeInferenceContext (Type[] typeArguments)
2616                 {
2617                         if (typeArguments.Length == 0)
2618                                 throw new ArgumentException ("Empty generic arguments");
2619
2620                         fixed_types = new Type [typeArguments.Length];
2621                         for (int i = 0; i < typeArguments.Length; ++i) {
2622                                 if (typeArguments [i].IsGenericParameter) {
2623                                         if (bounds == null) {
2624                                                 bounds = new ArrayList [typeArguments.Length];
2625                                                 unfixed_types = new Type [typeArguments.Length];
2626                                         }
2627                                         unfixed_types [i] = typeArguments [i];
2628                                 } else {
2629                                         fixed_types [i] = typeArguments [i];
2630                                 }
2631                         }
2632                 }
2633
2634                 public Type[] InferredTypeArguments {
2635                         get {
2636                                 return fixed_types;
2637                         }
2638                 }
2639
2640                 void AddToBounds (Type t, int index)
2641                 {
2642                         ArrayList a = bounds [index];
2643                         if (a == null) {
2644                                 a = new ArrayList ();
2645                                 bounds [index] = a;
2646                         } else {
2647                                 if (a.Contains (t))
2648                                         return;
2649                         }
2650
2651                         //
2652                         // SPEC: does not cover type inference using constraints
2653                         //
2654                         if (TypeManager.IsGenericParameter (t)) {
2655                                 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
2656                                 if (constraints != null) {
2657                                         //if (constraints.EffectiveBaseClass != null)
2658                                         //      t = constraints.EffectiveBaseClass;
2659                                 }
2660                         }
2661                         a.Add (t);
2662                 }
2663                 
2664                 bool AllTypesAreFixed (Type[] types)
2665                 {
2666                         foreach (Type t in types) {
2667                                 if (t.IsGenericParameter) {
2668                                         if (!IsFixed (t))
2669                                                 return false;
2670                                         continue;
2671                                 }
2672
2673                                 if (t.IsGenericType)
2674                                         return AllTypesAreFixed (t.GetGenericArguments ());
2675                         }
2676                         
2677                         return true;
2678                 }               
2679
2680                 //
2681                 // 26.3.3.8 Exact Inference
2682                 //
2683                 public int ExactInference (Type u, Type v)
2684                 {
2685                         // If V is an array type
2686                         if (v.IsArray) {
2687                                 if (!u.IsArray)
2688                                         return 0;
2689
2690                                 if (u.GetArrayRank () != v.GetArrayRank ())
2691                                         return 0;
2692
2693                                 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2694                         }
2695
2696                         // If V is constructed type and U is constructed type
2697                         if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2698                                 if (!u.IsGenericType)
2699                                         return 0;
2700
2701                                 Type [] ga_u = u.GetGenericArguments ();
2702                                 Type [] ga_v = v.GetGenericArguments ();
2703                                 if (ga_u.Length != ga_v.Length)
2704                                         return 0;
2705
2706                                 int score = 0;
2707                                 for (int i = 0; i < ga_u.Length; ++i)
2708                                         score += ExactInference (ga_u [i], ga_v [i]);
2709
2710                                 return score > 0 ? 1 : 0;
2711                         }
2712
2713                         // If V is one of the unfixed type arguments
2714                         int pos = IsUnfixed (v);
2715                         if (pos == -1)
2716                                 return 0;
2717
2718                         AddToBounds (u, pos);
2719                         return 1;
2720                 }
2721
2722                 public bool FixAllTypes ()
2723                 {
2724                         for (int i = 0; i < unfixed_types.Length; ++i) {
2725                                 if (!FixType (i))
2726                                         return false;
2727                         }
2728                         return true;
2729                 }
2730
2731                 //
2732                 // All unfixed type variables Xi are fixed for which all of the following hold:
2733                 // a, There is at least one type variable Xj that depends on Xi
2734                 // b, Xi has a non-empty set of bounds
2735                 // 
2736                 public bool FixDependentTypes (ParameterData methodParameters, ref bool fixed_any)
2737                 {
2738                         for (int i = 0; i < unfixed_types.Length; ++i) {
2739                                 if (unfixed_types[i] == null)
2740                                         continue;
2741
2742                                 if (bounds[i] == null)
2743                                         continue;
2744
2745                                 if (!FixType (i))
2746                                         return false;
2747                                 
2748                                 fixed_any = true;
2749                         }
2750
2751                         return true;
2752                 }
2753
2754                 //
2755                 // All unfixed type variables Xi which depend on no Xj are fixed
2756                 //
2757                 public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
2758                 {
2759                         ArrayList types_to_fix = new ArrayList (unfixed_types);
2760                         for (int i = 0; i < methodParameters.Types.Length; ++i) {
2761                                 Type t = methodParameters.Types [i];
2762                                 if (t.IsGenericParameter)
2763                                         continue;
2764
2765                                 if (!TypeManager.IsDelegateType (t)) {
2766                                         if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
2767                                                 continue;
2768
2769                                         t = t.GetGenericArguments () [0];
2770                                 }
2771
2772                                 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2773                                 Type rtype = invoke.ReturnType;
2774                                 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2775                                         continue;
2776
2777 #if MS_COMPATIBLE
2778                                 // Blablabla, because reflection does not work with dynamic types
2779                                 if (rtype.IsGenericParameter) {
2780                                         Type [] g_args = t.GetGenericArguments ();
2781                                         rtype = g_args [rtype.GenericParameterPosition];
2782                                 }
2783 #endif
2784                                 // Remove dependent types, they cannot be fixed yet
2785                                 RemoveDependentTypes (types_to_fix, rtype);
2786                         }
2787
2788                         foreach (Type t in types_to_fix) {
2789                                 if (t == null)
2790                                         continue;
2791
2792                                 int idx = IsUnfixed (t);
2793                                 if (idx >= 0 && !FixType (idx)) {
2794                                         return false;
2795                                 }
2796                         }
2797
2798                         fixed_any = types_to_fix.Count > 0;
2799                         return true;
2800                 }
2801
2802                 //
2803                 // 26.3.3.10 Fixing
2804                 //
2805                 public bool FixType (int i)
2806                 {
2807                         // It's already fixed
2808                         if (unfixed_types[i] == null)
2809                                 throw new InternalErrorException ("Type argument has been already fixed");
2810
2811                         ArrayList candidates = (ArrayList)bounds [i];
2812                         if (candidates == null)
2813                                 return false;
2814
2815                         if (candidates.Count == 1) {
2816                                 unfixed_types[i] = null;
2817                                 fixed_types[i] = (Type)candidates[0];
2818                                 return true;
2819                         }
2820
2821                         //
2822                         // Determines a unique type from which there is
2823                         // a standard implicit conversion to all the other
2824                         // candidate types.
2825                         //
2826                         Type best_candidate = null;
2827                         int cii;
2828                         int candidates_count = candidates.Count;
2829                         for (int ci = 0; ci < candidates_count; ++ci) {
2830                                 Type candidate = (Type)candidates [ci];
2831                                 for (cii = 0; cii < candidates_count; ++cii) {
2832                                         if (cii == ci)
2833                                                 continue;
2834
2835                                         if (!Convert.ImplicitConversionExists (null,
2836                                                 new TypeExpression ((Type)candidates [cii], Location.Null), candidate)) {
2837                                                 break;
2838                                         }
2839                                 }
2840
2841                                 if (cii != candidates_count)
2842                                         continue;
2843
2844                                 if (best_candidate != null)
2845                                         return false;
2846
2847                                 best_candidate = candidate;
2848                         }
2849
2850                         if (best_candidate == null)
2851                                 return false;
2852
2853                         unfixed_types[i] = null;
2854                         fixed_types[i] = best_candidate;
2855                         return true;
2856                 }
2857                 
2858                 //
2859                 // Uses inferred types to inflate delegate type argument
2860                 //
2861                 public Type InflateGenericArgument (Type parameter)
2862                 {
2863                         if (parameter.IsGenericParameter)
2864                                 return fixed_types [parameter.GenericParameterPosition];
2865
2866                         if (parameter.IsGenericType) {
2867                                 Type [] parameter_targs = parameter.GetGenericArguments ();
2868                                 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2869                                         parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2870                                 }
2871                                 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2872                         }
2873
2874                         return parameter;
2875                 }
2876                 
2877                 //
2878                 // Tests whether all delegate input arguments are fixed and generic output type
2879                 // requires output type inference 
2880                 //
2881                 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2882                 {
2883                         if (returnType.IsGenericParameter) {
2884                                 if (IsFixed (returnType))
2885                                     return false;
2886                         } else if (returnType.IsGenericType) {
2887                                 if (TypeManager.IsDelegateType (returnType)) {
2888                                         invoke = Delegate.GetInvokeMethod (returnType, returnType);
2889                                         return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2890                                 }
2891                                         
2892                                 Type[] g_args = returnType.GetGenericArguments ();
2893                                 
2894                                 // At least one unfixed return type has to exist 
2895                                 if (AllTypesAreFixed (g_args))
2896                                         return false;
2897                         } else {
2898                                 return false;
2899                         }
2900
2901                         // All generic input arguments have to be fixed
2902                         ParameterData d_parameters = TypeManager.GetParameterData (invoke);
2903                         return AllTypesAreFixed (d_parameters.Types);
2904                 }
2905                 
2906                 bool IsFixed (Type type)
2907                 {
2908                         return IsUnfixed (type) == -1;
2909                 }               
2910
2911                 int IsUnfixed (Type type)
2912                 {
2913                         if (!type.IsGenericParameter)
2914                                 return -1;
2915
2916                         //return unfixed_types[type.GenericParameterPosition] != null;
2917                         for (int i = 0; i < unfixed_types.Length; ++i) {
2918                                 if (unfixed_types [i] == type)
2919                                         return i;
2920                         }
2921
2922                         return -1;
2923                 }
2924
2925                 //
2926                 // 26.3.3.9 Lower-bound Inference
2927                 //
2928                 public int LowerBoundInference (Type u, Type v)
2929                 {
2930                         // Remove ref, out modifiers
2931                         if (v.IsByRef)
2932                                 v = v.GetElementType ();
2933                         
2934                         // If V is one of the unfixed type arguments
2935                         int pos = IsUnfixed (v);
2936                         if (pos != -1) {
2937                                 AddToBounds (u, pos);
2938                                 return 1;
2939                         }                       
2940
2941                         // If U is an array type
2942                         if (u.IsArray) {
2943                                 int u_dim = u.GetArrayRank ();
2944                                 Type v_e;
2945                                 Type u_e = TypeManager.GetElementType (u);
2946
2947                                 if (v.IsArray) {
2948                                         if (u_dim != v.GetArrayRank ())
2949                                                 return 0;
2950
2951                                         v_e = TypeManager.GetElementType (v);
2952
2953                                         if (u.IsByRef) {
2954                                                 return LowerBoundInference (u_e, v_e);
2955                                         }
2956
2957                                         return ExactInference (u_e, v_e);
2958                                 }
2959
2960                                 if (u_dim != 1)
2961                                         return 0;
2962
2963                                 if (v.IsGenericType) {
2964                                         Type g_v = v.GetGenericTypeDefinition ();
2965                                         if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2966                                                 (g_v != TypeManager.generic_ienumerable_type))
2967                                                 return 0;
2968
2969                                         v_e = TypeManager.GetTypeArguments (v)[0];
2970
2971                                         if (u.IsByRef) {
2972                                                 return LowerBoundInference (u_e, v_e);
2973                                         }
2974
2975                                         return ExactInference (u_e, v_e);
2976                                 }
2977                         } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2978                                 //
2979                                 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2980                                 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2981                                 // inference is made from each Ui for the corresponding Vi
2982                                 //
2983                                 ArrayList u_candidates = new ArrayList ();
2984                                 if (u.IsGenericType)
2985                                         u_candidates.Add (u);
2986
2987                                 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2988                                         if (t.IsGenericType && !t.IsGenericTypeDefinition)
2989                                                 u_candidates.Add (t);
2990                                 }
2991
2992                                 // TODO: Implement GetGenericInterfaces only and remove
2993                                 // the if from foreach
2994                                 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2995
2996                                 Type open_v = v.GetGenericTypeDefinition ();
2997                                 int score = 0;
2998                                 foreach (Type u_candidate in u_candidates) {
2999                                         if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
3000                                                 continue;
3001
3002                                         if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
3003                                                 continue;
3004
3005                                         Type [] ga_u = u_candidate.GetGenericArguments ();
3006                                         Type [] ga_v = v.GetGenericArguments ();
3007                                         bool all_exact = true;
3008                                         for (int i = 0; i < ga_u.Length; ++i)
3009                                                 if (ExactInference (ga_u [i], ga_v [i]) == 0)
3010                                                         all_exact = false;
3011
3012                                         if (all_exact && score == 0)
3013                                                 ++score;
3014                                 }
3015                                 return score;
3016                         }
3017
3018                         return 0;
3019                 }
3020
3021                 //
3022                 // 26.3.3.6 Output Type Inference
3023                 //
3024                 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
3025                 {
3026                         // If e is a lambda or anonymous method with inferred return type
3027                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3028                         if (ame != null) {
3029                                 Type rt = ame.InferReturnType (ec, this, t);
3030                                 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3031
3032                                 if (rt == null) {
3033                                         ParameterData pd = TypeManager.GetParameterData (invoke);
3034                                         return ame.Parameters.Count == pd.Count ? 1 : 0;
3035                                 }
3036
3037                                 Type rtype = invoke.ReturnType;
3038 #if MS_COMPATIBLE
3039                                 // Blablabla, because reflection does not work with dynamic types
3040                                 Type [] g_args = t.GetGenericArguments ();
3041                                 rtype = g_args [rtype.GenericParameterPosition];
3042 #endif
3043                                 return LowerBoundInference (rt, rtype) + 1;
3044                         }
3045
3046                         if (e is MethodGroupExpr) {
3047                                 if (!TypeManager.IsDelegateType (t))
3048                                         return 0;
3049
3050                                 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3051                                 Type rtype = invoke.ReturnType;
3052                                 if (!TypeManager.IsGenericType (rtype))
3053                                         return 0;
3054                                 
3055                                 throw new NotImplementedException ();
3056                         }
3057
3058                         //
3059                         // if e is an expression with type U, then
3060                         // a lower-bound inference is made from U for T
3061                         //
3062                         return LowerBoundInference (e.Type, t) * 2;
3063                 }
3064
3065                 static void RemoveDependentTypes (ArrayList types, Type returnType)
3066                 {
3067                         if (returnType.IsGenericParameter) {
3068                                 types [returnType.GenericParameterPosition] = null;
3069                                 return;
3070                         }
3071
3072                         if (returnType.IsGenericType) {
3073                                 foreach (Type t in returnType.GetGenericArguments ()) {
3074                                         RemoveDependentTypes (types, t);
3075                                 }
3076                         }
3077                 }
3078
3079                 public bool UnfixedVariableExists {
3080                         get {
3081                                 if (unfixed_types == null)
3082                                         return false;
3083
3084                                 foreach (Type ut in unfixed_types)
3085                                         if (ut != null)
3086                                                 return true;
3087                                 return false;
3088                         }
3089                 }
3090         }
3091
3092         public abstract class Nullable
3093         {
3094                 public sealed class NullableInfo
3095                 {
3096                         public readonly Type Type;
3097                         public readonly Type UnderlyingType;
3098                         public readonly MethodInfo HasValue;
3099                         public readonly MethodInfo Value;
3100                         public readonly ConstructorInfo Constructor;
3101
3102                         public NullableInfo (Type type)
3103                         {
3104                                 Type = type;
3105                                 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
3106
3107                                 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
3108                                 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
3109
3110                                 HasValue = has_value_pi.GetGetMethod (false);
3111                                 Value = value_pi.GetGetMethod (false);
3112                                 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
3113                         }
3114                 }
3115                 
3116                 public class HasValue : Expression
3117                 {
3118                         Expression expr;
3119                         NullableInfo info;
3120
3121                         private HasValue (Expression expr)
3122                         {
3123                                 this.expr = expr;
3124                         }
3125                         
3126                         public static Expression Create (Expression expr, EmitContext ec)
3127                         {
3128                                 return new HasValue (expr).Resolve (ec);
3129                         }
3130
3131                         public override void Emit (EmitContext ec)
3132                         {
3133                                 IMemoryLocation memory_loc = expr as IMemoryLocation;
3134                                 if (memory_loc == null) {
3135                                         LocalTemporary temp = new LocalTemporary (expr.Type);
3136                                         expr.Emit (ec);
3137                                         temp.Store (ec);
3138                                         memory_loc = temp;
3139                                 }
3140                                 memory_loc.AddressOf (ec, AddressOp.LoadStore);
3141                                 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3142                         }
3143
3144                         public override Expression DoResolve (EmitContext ec)
3145                         {
3146                                 this.info = new NullableInfo (expr.Type);
3147
3148                                 type = TypeManager.bool_type;
3149                                 eclass = expr.eclass;
3150                                 return this;
3151                         }
3152                 }               
3153
3154                 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
3155                 {
3156                         Expression expr;
3157                         NullableInfo info;
3158
3159                         LocalTemporary temp;
3160                         bool has_temp;
3161
3162                         protected Unwrap (Expression expr)
3163                         {
3164                                 this.expr = expr;
3165                                 this.loc = expr.Location;
3166                         }
3167
3168                         public static Unwrap Create (Expression expr, EmitContext ec)
3169                         {
3170                                 return new Unwrap (expr).Resolve (ec) as Unwrap;
3171                         }
3172                         
3173                         public override Expression CreateExpressionTree (EmitContext ec)
3174                         {
3175                                 return expr.CreateExpressionTree (ec);
3176                         }                       
3177
3178                         public override Expression DoResolve (EmitContext ec)
3179                         {
3180                                 if (expr == null)
3181                                         return null;
3182
3183                                 temp = new LocalTemporary (expr.Type);
3184
3185                                 info = new NullableInfo (expr.Type);
3186                                 type = info.UnderlyingType;
3187                                 eclass = expr.eclass;
3188                                 return this;
3189                         }
3190                         
3191                         public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3192                         {
3193                                 return DoResolve (ec);
3194                         }                       
3195
3196                         public override void Emit (EmitContext ec)
3197                         {
3198                                 AddressOf (ec, AddressOp.LoadStore);
3199                                 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
3200                         }
3201
3202                         public void EmitCheck (EmitContext ec)
3203                         {
3204                                 AddressOf (ec, AddressOp.LoadStore);
3205                                 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3206                         }
3207
3208                         public override bool IsNull {
3209                                 get {
3210                                         return expr.IsNull;
3211                                 }
3212                         }
3213
3214                         public void Store (EmitContext ec)
3215                         {
3216                                 create_temp (ec);
3217                         }
3218
3219                         void create_temp (EmitContext ec)
3220                         {
3221                                 if ((temp != null) && !has_temp) {
3222                                         expr.Emit (ec);
3223                                         temp.Store (ec);
3224                                         has_temp = true;
3225                                 }
3226                         }
3227
3228                         public void AddressOf (EmitContext ec, AddressOp mode)
3229                         {
3230                                 create_temp (ec);
3231                                 if (temp != null)
3232                                         temp.AddressOf (ec, AddressOp.LoadStore);
3233                                 else
3234                                         ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3235                         }
3236
3237                         public void Emit (EmitContext ec, bool leave_copy)
3238                         {
3239                                 create_temp (ec);
3240                                 if (leave_copy) {
3241                                         if (temp != null)
3242                                                 temp.Emit (ec);
3243                                         else
3244                                                 expr.Emit (ec);
3245                                 }
3246
3247                                 Emit (ec);
3248                         }
3249
3250                         public void EmitAssign (EmitContext ec, Expression source,
3251                                                 bool leave_copy, bool prepare_for_load)
3252                         {
3253                                 InternalWrap wrap = new InternalWrap (source, info, loc);
3254                                 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
3255                         }
3256
3257                         protected class InternalWrap : Expression
3258                         {
3259                                 public Expression expr;
3260                                 public NullableInfo info;
3261
3262                                 public InternalWrap (Expression expr, NullableInfo info, Location loc)
3263                                 {
3264                                         this.expr = expr;
3265                                         this.info = info;
3266                                         this.loc = loc;
3267
3268                                         type = info.Type;
3269                                         eclass = ExprClass.Value;
3270                                 }
3271
3272                                 public override Expression DoResolve (EmitContext ec)
3273                                 {
3274                                         return this;
3275                                 }
3276
3277                                 public override void Emit (EmitContext ec)
3278                                 {
3279                                         expr.Emit (ec);
3280                                         ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3281                                 }
3282                         }
3283                 }
3284
3285                 public class Wrap : Expression
3286                 {
3287                         Expression expr;
3288                         NullableInfo info;
3289
3290                         protected Wrap (Expression expr)
3291                         {
3292                                 this.expr = expr;
3293                                 this.loc = expr.Location;
3294                         }
3295
3296                         public static Wrap Create (Expression expr, EmitContext ec)
3297                         {
3298                                 return new Wrap (expr).Resolve (ec) as Wrap;
3299                         }
3300                         
3301                         public override Expression CreateExpressionTree (EmitContext ec)
3302                         {
3303                                 ArrayList args = new ArrayList (2);
3304                                 args.Add (new Argument (expr.CreateExpressionTree (ec)));
3305                                 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
3306                                 return CreateExpressionFactoryCall ("Convert", args);
3307                         }                       
3308
3309                         public override Expression DoResolve (EmitContext ec)
3310                         {
3311                                 if (expr == null)
3312                                         return null;
3313
3314                                 TypeExpr target_type = new NullableType (expr.Type, loc);
3315                                 target_type = target_type.ResolveAsTypeTerminal (ec, false);
3316                                 if (target_type == null)
3317                                         return null;
3318
3319                                 type = target_type.Type;
3320                                 info = new NullableInfo (type);
3321                                 eclass = ExprClass.Value;
3322                                 return this;
3323                         }
3324
3325                         public override void Emit (EmitContext ec)
3326                         {
3327                                 expr.Emit (ec);
3328                                 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3329                         }
3330                 }
3331
3332                 //
3333                 // Represents null value converted to nullable type
3334                 //
3335                 public class Null : Expression, IMemoryLocation
3336                 {
3337                         public Null (Type target_type, Location loc)
3338                         {
3339                                 this.type = target_type;
3340                                 this.loc = loc;
3341
3342                                 eclass = ExprClass.Value;
3343                         }
3344                         
3345                         public override Expression CreateExpressionTree (EmitContext ec)
3346                         {
3347                                 return EmptyCast.Create (new NullConstant (loc), type).CreateExpressionTree (ec);
3348                         }                       
3349                 
3350                         public override Expression DoResolve (EmitContext ec)
3351                         {
3352                                 return this;
3353                         }
3354
3355                         public override void Emit (EmitContext ec)
3356                         {
3357                                 LocalTemporary value_target = new LocalTemporary (type);
3358
3359                                 value_target.AddressOf (ec, AddressOp.Store);
3360                                 ec.ig.Emit (OpCodes.Initobj, type);
3361                                 value_target.Emit (ec);
3362                         }
3363                         
3364                         public override bool IsNull {
3365                                 get {
3366                                         return true;
3367                                 }
3368                         }                       
3369
3370                         public void AddressOf (EmitContext ec, AddressOp Mode)
3371                         {
3372                                 LocalTemporary value_target = new LocalTemporary (type);
3373                                         
3374                                 value_target.AddressOf (ec, AddressOp.Store);
3375                                 ec.ig.Emit (OpCodes.Initobj, type);
3376                                 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
3377                         }
3378                 }
3379
3380                 public abstract class Lifted : Expression, IMemoryLocation
3381                 {
3382                         Expression expr, underlying, wrap, null_value;
3383                         Unwrap unwrap;
3384
3385                         protected Lifted (Expression expr, Location loc)
3386                         {
3387                                 this.expr = expr;
3388                                 this.loc = loc;
3389                         }
3390                         
3391                         public override Expression CreateExpressionTree (EmitContext ec)
3392                         {
3393                                 return expr.CreateExpressionTree (ec);
3394                         }                       
3395
3396                         public override Expression DoResolve (EmitContext ec)
3397                         {
3398                                 expr = expr.Resolve (ec);
3399                                 if (expr == null)
3400                                         return null;
3401
3402                                 unwrap = Unwrap.Create (expr, ec);
3403                                 if (unwrap == null)
3404                                         return null;
3405
3406                                 underlying = ResolveUnderlying (unwrap, ec);
3407                                 if (underlying == null)
3408                                         return null;
3409
3410                                 wrap = Wrap.Create (underlying, ec);
3411                                 if (wrap == null)
3412                                         return null;
3413
3414                                 null_value = new Null (wrap.Type, loc).Resolve (ec);
3415                                 if (null_value == null)
3416                                         return null;
3417
3418                                 type = wrap.Type;
3419                                 eclass = ExprClass.Value;
3420                                 return this;
3421                         }
3422
3423                         protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
3424
3425                         public override void Emit (EmitContext ec)
3426                         {
3427                                 ILGenerator ig = ec.ig;
3428                                 Label is_null_label = ig.DefineLabel ();
3429                                 Label end_label = ig.DefineLabel ();
3430
3431                                 unwrap.EmitCheck (ec);
3432                                 ig.Emit (OpCodes.Brfalse, is_null_label);
3433
3434                                 wrap.Emit (ec);
3435                                 ig.Emit (OpCodes.Br, end_label);
3436
3437                                 ig.MarkLabel (is_null_label);
3438                                 null_value.Emit (ec);
3439
3440                                 ig.MarkLabel (end_label);
3441                         }
3442
3443                         public void AddressOf (EmitContext ec, AddressOp mode)
3444                         {
3445                                 unwrap.AddressOf (ec, mode);
3446                         }
3447                 }
3448
3449                 public class LiftedConversion : Lifted
3450                 {
3451                         public readonly bool IsUser;
3452                         public readonly bool IsExplicit;
3453                         public readonly Type TargetType;
3454
3455                         public LiftedConversion (Expression expr, Type target_type, bool is_user,
3456                                                  bool is_explicit, Location loc)
3457                                 : base (expr, loc)
3458                         {
3459                                 this.IsUser = is_user;
3460                                 this.IsExplicit = is_explicit;
3461                                 this.TargetType = target_type;
3462                         }
3463
3464                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3465                         {
3466                                 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3467
3468                                 if (IsUser) {
3469                                         return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3470                                 } else {
3471                                         if (IsExplicit)
3472                                                 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3473                                         else
3474                                                 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3475                                 }
3476                         }
3477                 }
3478
3479                 public class LiftedUnaryOperator : Lifted
3480                 {
3481                         public readonly Unary.Operator Oper;
3482
3483                         public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3484                                 : base (expr, loc)
3485                         {
3486                                 this.Oper = op;
3487                         }
3488
3489                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3490                         {
3491                                 return new Unary (Oper, unwrap, loc).Resolve (ec);
3492                         }
3493                 }
3494
3495                 public class LiftedBinaryOperator : Binary
3496                 {
3497                         Expression underlying, null_value, bool_wrap;
3498                         Unwrap left_unwrap, right_unwrap;
3499                         bool is_equality, is_comparision, is_boolean;
3500
3501                         public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3502                                                      Location loc)
3503                                 : base (op, left, right)
3504                         {
3505                                 this.loc = loc;
3506                         }
3507
3508                         public override Expression DoResolve (EmitContext ec)
3509                         {
3510                                 if ((Oper == Binary.Operator.LogicalAnd) ||
3511                                     (Oper == Binary.Operator.LogicalOr)) {
3512                                         Error_OperatorCannotBeApplied ();
3513                                         return null;
3514                                 }
3515
3516                                 //
3517                                 // Optimize null comparisons
3518                                 //
3519                                 if (Oper == Binary.Operator.Equality) {
3520                                         if (left.IsNull)
3521                                                 return new Unary (Unary.Operator.LogicalNot, Nullable.HasValue.Create (right, ec), loc).Resolve (ec);
3522                                         if (right.IsNull)
3523                                                 return new Unary (Unary.Operator.LogicalNot, Nullable.HasValue.Create (left, ec), loc).Resolve (ec);
3524                                 }
3525                                 if (Oper == Binary.Operator.Inequality) {
3526                                         if (left.IsNull)
3527                                                 return Nullable.HasValue.Create (right, ec);
3528                                         if (right.IsNull)
3529                                                 return Nullable.HasValue.Create (left, ec);
3530                                 }
3531                                 
3532                                 if (TypeManager.IsNullableType (left.Type)) {
3533                                         left = left_unwrap = Unwrap.Create (left, ec);
3534                                         if (left == null)
3535                                                 return null;
3536                                 }
3537
3538                                 if (TypeManager.IsNullableType (right.Type)) {
3539                                         right = right_unwrap = Unwrap.Create (right, ec);
3540                                         if (right == null)
3541                                                 return null;
3542                                 }
3543
3544                                 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3545                                     ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3546                                         Expression empty = new EmptyExpression (TypeManager.bool_type);
3547                                         bool_wrap = Wrap.Create (empty, ec);
3548                                         null_value = new Null (bool_wrap.Type, loc).Resolve (ec);
3549
3550                                         type = bool_wrap.Type;
3551                                         is_boolean = true;
3552                                 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3553                                         underlying = new Binary (Oper, left, right).Resolve (ec);
3554                                         if (underlying == null)
3555                                                 return null;
3556                                         type = TypeManager.bool_type;
3557                                         is_equality = true;
3558                                 } else if ((Oper == Binary.Operator.LessThan) ||
3559                                            (Oper == Binary.Operator.GreaterThan) ||
3560                                            (Oper == Binary.Operator.LessThanOrEqual) ||
3561                                            (Oper == Binary.Operator.GreaterThanOrEqual)) {
3562                                         underlying = new Binary (Oper, left, right).Resolve (ec);
3563                                         if (underlying == null)
3564                                                 return null;
3565
3566                                         type = TypeManager.bool_type;
3567                                         is_comparision = true;
3568                                 } else {
3569                                         underlying = new Binary (Oper, left, right).Resolve (ec);
3570                                         if (underlying == null)
3571                                                 return null;
3572
3573                                         underlying = Wrap.Create (underlying, ec);
3574                                         if (underlying == null)
3575                                                 return null;
3576
3577                                         type = underlying.Type;
3578                                         null_value = new Null (type, loc).Resolve (ec);
3579                                 }
3580
3581                                 eclass = ExprClass.Value;
3582                                 return this;
3583                         }
3584
3585                         void EmitBoolean (EmitContext ec)
3586                         {
3587                                 ILGenerator ig = ec.ig;
3588
3589                                 Label left_is_null_label = ig.DefineLabel ();
3590                                 Label right_is_null_label = ig.DefineLabel ();
3591                                 Label is_null_label = ig.DefineLabel ();
3592                                 Label wrap_label = ig.DefineLabel ();
3593                                 Label end_label = ig.DefineLabel ();
3594
3595                                 if (left_unwrap != null) {
3596                                         left_unwrap.EmitCheck (ec);
3597                                         ig.Emit (OpCodes.Brfalse, left_is_null_label);
3598                                 }
3599
3600                                 left.Emit (ec);
3601                                 ig.Emit (OpCodes.Dup);
3602                                 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3603                                         ig.Emit (OpCodes.Brtrue, wrap_label);
3604                                 else
3605                                         ig.Emit (OpCodes.Brfalse, wrap_label);
3606
3607                                 if (right_unwrap != null) {
3608                                         right_unwrap.EmitCheck (ec);
3609                                         ig.Emit (OpCodes.Brfalse, right_is_null_label);
3610                                 }
3611
3612                                 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3613                                         ig.Emit (OpCodes.Pop);
3614
3615                                 right.Emit (ec);
3616                                 if (Oper == Binary.Operator.BitwiseOr)
3617                                         ig.Emit (OpCodes.Or);
3618                                 else if (Oper == Binary.Operator.BitwiseAnd)
3619                                         ig.Emit (OpCodes.And);
3620                                 ig.Emit (OpCodes.Br, wrap_label);
3621
3622                                 ig.MarkLabel (left_is_null_label);
3623                                 if (right_unwrap != null) {
3624                                         right_unwrap.EmitCheck (ec);
3625                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3626                                 }
3627
3628                                 right.Emit (ec);
3629                                 ig.Emit (OpCodes.Dup);
3630                                 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3631                                         ig.Emit (OpCodes.Brtrue, wrap_label);
3632                                 else
3633                                         ig.Emit (OpCodes.Brfalse, wrap_label);
3634
3635                                 ig.MarkLabel (right_is_null_label);
3636                                 ig.Emit (OpCodes.Pop);
3637                                 ig.MarkLabel (is_null_label);
3638                                 null_value.Emit (ec);
3639                                 ig.Emit (OpCodes.Br, end_label);
3640
3641                                 ig.MarkLabel (wrap_label);
3642                                 ig.Emit (OpCodes.Nop);
3643                                 bool_wrap.Emit (ec);
3644                                 ig.Emit (OpCodes.Nop);
3645
3646                                 ig.MarkLabel (end_label);
3647                         }
3648
3649                         void EmitEquality (EmitContext ec)
3650                         {
3651                                 if (left.IsNull || right.IsNull)
3652                                         throw new InternalErrorException ("Unoptimized nullable comparison");
3653
3654                                 ILGenerator ig = ec.ig;
3655
3656                                 Label both_have_value_label = ig.DefineLabel ();
3657                                 Label end_label = ig.DefineLabel ();
3658
3659                                 if (left_unwrap != null && right_unwrap != null) {
3660                                         Label dissimilar_label = ig.DefineLabel ();
3661
3662                                         left_unwrap.EmitCheck (ec);
3663                                         ig.Emit (OpCodes.Dup);
3664                                         right_unwrap.EmitCheck (ec);
3665                                         ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3666
3667                                         ig.Emit (OpCodes.Brtrue, both_have_value_label);
3668
3669                                         // both are null
3670                                         if (Oper == Binary.Operator.Equality)
3671                                                 ig.Emit (OpCodes.Ldc_I4_1);
3672                                         else
3673                                                 ig.Emit (OpCodes.Ldc_I4_0);
3674                                         ig.Emit (OpCodes.Br, end_label);
3675
3676                                         ig.MarkLabel (dissimilar_label);
3677                                         ig.Emit (OpCodes.Pop);
3678                                 } else if (left_unwrap != null) {
3679                                         left_unwrap.EmitCheck (ec);
3680                                         ig.Emit (OpCodes.Brtrue, both_have_value_label);
3681                                 } else if (right_unwrap != null) {
3682                                         right_unwrap.EmitCheck (ec);
3683                                         ig.Emit (OpCodes.Brtrue, both_have_value_label);
3684                                 } else {
3685                                         throw new InternalErrorException ("shouldn't get here");
3686                                 }
3687
3688                                 // one is null while the other isn't
3689                                 if (Oper == Binary.Operator.Equality)
3690                                         ig.Emit (OpCodes.Ldc_I4_0);
3691                                 else
3692                                         ig.Emit (OpCodes.Ldc_I4_1);
3693                                 ig.Emit (OpCodes.Br, end_label);
3694
3695                                 ig.MarkLabel (both_have_value_label);
3696                                 underlying.Emit (ec);
3697
3698                                 ig.MarkLabel (end_label);
3699                         }
3700
3701                         void EmitComparision (EmitContext ec)
3702                         {
3703                                 ILGenerator ig = ec.ig;
3704
3705                                 Label is_null_label = ig.DefineLabel ();
3706                                 Label end_label = ig.DefineLabel ();
3707
3708                                 if (left_unwrap != null) {
3709                                         left_unwrap.EmitCheck (ec);
3710                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3711                                 }
3712
3713                                 if (right_unwrap != null) {
3714                                         right_unwrap.EmitCheck (ec);
3715                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3716                                 }
3717
3718                                 underlying.Emit (ec);
3719                                 ig.Emit (OpCodes.Br, end_label);
3720
3721                                 ig.MarkLabel (is_null_label);
3722                                 ig.Emit (OpCodes.Ldc_I4_0);
3723
3724                                 ig.MarkLabel (end_label);
3725                         }
3726                         
3727                         public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
3728                         {
3729                                 Emit (ec);
3730                                 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
3731                         }                       
3732
3733                         public override void Emit (EmitContext ec)
3734                         {
3735                                 if (left_unwrap != null)
3736                                         left_unwrap.Store (ec);
3737                                 if (right_unwrap != null)
3738                                         right_unwrap.Store (ec);
3739
3740                                 if (is_boolean) {
3741                                         EmitBoolean (ec);
3742                                         return;
3743                                 } else if (is_equality) {
3744                                         EmitEquality (ec);
3745                                         return;
3746                                 } else if (is_comparision) {
3747                                         EmitComparision (ec);
3748                                         return;
3749                                 }
3750
3751                                 ILGenerator ig = ec.ig;
3752
3753                                 Label is_null_label = ig.DefineLabel ();
3754                                 Label end_label = ig.DefineLabel ();
3755
3756                                 if (left_unwrap != null) {
3757                                         left_unwrap.EmitCheck (ec);
3758                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3759                                 }
3760
3761                                 if (right_unwrap != null) {
3762                                         right_unwrap.EmitCheck (ec);
3763                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3764                                 }
3765
3766                                 underlying.Emit (ec);
3767                                 ig.Emit (OpCodes.Br, end_label);
3768
3769                                 ig.MarkLabel (is_null_label);
3770                                 null_value.Emit (ec);
3771
3772                                 ig.MarkLabel (end_label);
3773                         }
3774                 }
3775
3776                 public class NullCoalescingOperator : Expression
3777                 {
3778                         Expression left, right;
3779                         Unwrap unwrap;
3780
3781                         public NullCoalescingOperator (Expression left, Expression right, Location loc)
3782                         {
3783                                 this.left = left;
3784                                 this.right = right;
3785                                 this.loc = loc;
3786                         }
3787                         
3788                         public override Expression CreateExpressionTree (EmitContext ec)
3789                         {
3790                                 UserCast uc = left as UserCast;
3791                                 Expression conversion = null;
3792                                 if (uc != null) {
3793                                         left = uc.Source;
3794
3795                                         ArrayList c_args = new ArrayList (2);
3796                                         c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
3797                                         c_args.Add (new Argument (left.CreateExpressionTree (ec)));
3798                                         conversion = CreateExpressionFactoryCall ("Lambda", c_args);
3799                                 }
3800
3801                                 ArrayList args = new ArrayList (3);
3802                                 args.Add (new Argument (left.CreateExpressionTree (ec)));
3803                                 args.Add (new Argument (right.CreateExpressionTree (ec)));
3804                                 if (conversion != null)
3805                                         args.Add (new Argument (conversion));
3806                                 
3807                                 return CreateExpressionFactoryCall ("Coalesce", args);
3808                         }                       
3809
3810                         public override Expression DoResolve (EmitContext ec)
3811                         {
3812                                 if (type != null)
3813                                         return this;
3814
3815                                 left = left.Resolve (ec);
3816                                 right = right.Resolve (ec);
3817
3818                                 if (left == null || right == null)
3819                                         return null;
3820
3821                                 eclass = ExprClass.Value;
3822                                 Type ltype = left.Type, rtype = right.Type;
3823                                 Expression expr;
3824
3825                                 if (TypeManager.IsNullableType (ltype)) {
3826                                         NullableInfo info = new NullableInfo (ltype);
3827
3828                                         unwrap = Unwrap.Create (left, ec);
3829                                         if (unwrap == null)
3830                                                 return null;
3831
3832                                         expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3833                                         if (expr != null) {
3834                                                 left = unwrap;
3835                                                 right = expr;
3836                                                 type = expr.Type;
3837                                                 return this;
3838                                         }
3839                                 } else if (!TypeManager.IsReferenceType (ltype)) {
3840                                         Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3841                                         return null;
3842                                 }
3843
3844                                 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3845                                 if (expr != null) {
3846                                         type = expr.Type;
3847                                         right = expr;
3848                                         return this;
3849                                 }
3850
3851                                 Expression left_null = unwrap != null ? unwrap : left;
3852                                 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3853                                 if (expr != null) {
3854                                         left = expr;
3855                                         type = rtype;
3856                                         return this;
3857                                 }
3858
3859                                 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3860                                 return null;
3861                         }
3862
3863                         public override void Emit (EmitContext ec)
3864                         {
3865                                 ILGenerator ig = ec.ig;
3866
3867                                 Label is_null_label = ig.DefineLabel ();
3868                                 Label end_label = ig.DefineLabel ();
3869
3870                                 if (unwrap != null) {
3871                                         unwrap.EmitCheck (ec);
3872                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3873
3874                                         left.Emit (ec);
3875                                         ig.Emit (OpCodes.Br, end_label);
3876
3877                                         ig.MarkLabel (is_null_label);
3878                                         right.Emit (ec);
3879
3880                                         ig.MarkLabel (end_label);
3881                                 } else {
3882                                         left.Emit (ec);
3883                                         ig.Emit (OpCodes.Dup);
3884                                         ig.Emit (OpCodes.Brtrue, end_label);
3885
3886                                         ig.MarkLabel (is_null_label);
3887
3888                                         ig.Emit (OpCodes.Pop);
3889                                         right.Emit (ec);
3890
3891                                         ig.MarkLabel (end_label);
3892                                 }
3893                         }
3894                         protected override void CloneTo (CloneContext clonectx, Expression t)
3895                         {
3896                                 NullCoalescingOperator target = (NullCoalescingOperator) t;
3897
3898                                 target.left = left.Clone (clonectx);
3899                                 target.right = right.Clone (clonectx);
3900                         }
3901                 }
3902
3903                 public class LiftedUnaryMutator : ExpressionStatement
3904                 {
3905                         public readonly UnaryMutator.Mode Mode;
3906                         Expression expr, null_value;
3907                         UnaryMutator underlying;
3908                         Unwrap unwrap;
3909
3910                         public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3911                         {
3912                                 this.expr = expr;
3913                                 this.Mode = mode;
3914                                 this.loc = loc;
3915
3916                                 eclass = ExprClass.Value;
3917                         }
3918
3919                         public override Expression DoResolve (EmitContext ec)
3920                         {
3921                                 expr = expr.Resolve (ec);
3922                                 if (expr == null)
3923                                         return null;
3924
3925                                 unwrap = Unwrap.Create (expr, ec);
3926                                 if (unwrap == null)
3927                                         return null;
3928
3929                                 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3930                                 if (underlying == null)
3931                                         return null;
3932
3933                                 null_value = new Null (expr.Type, loc).Resolve (ec);
3934                                 if (null_value == null)
3935                                         return null;
3936
3937                                 type = expr.Type;
3938                                 return this;
3939                         }
3940
3941                         void DoEmit (EmitContext ec, bool is_expr)
3942                         {
3943                                 ILGenerator ig = ec.ig;
3944                                 Label is_null_label = ig.DefineLabel ();
3945                                 Label end_label = ig.DefineLabel ();
3946
3947                                 unwrap.EmitCheck (ec);
3948                                 ig.Emit (OpCodes.Brfalse, is_null_label);
3949
3950                                 if (is_expr)
3951                                         underlying.Emit (ec);
3952                                 else
3953                                         underlying.EmitStatement (ec);
3954                                 ig.Emit (OpCodes.Br, end_label);
3955
3956                                 ig.MarkLabel (is_null_label);
3957                                 if (is_expr)
3958                                         null_value.Emit (ec);
3959
3960                                 ig.MarkLabel (end_label);
3961                         }
3962
3963                         public override void Emit (EmitContext ec)
3964                         {
3965                                 DoEmit (ec, true);
3966                         }
3967
3968                         public override void EmitStatement (EmitContext ec)
3969                         {
3970                                 DoEmit (ec, false);
3971                         }
3972                 }
3973         }
3974 }