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