merge from trunk revisions 58933, 58935, 58936
[mono.git] / mcs / gmcs / generic.cs
1 //
2 // generic.cs: Generics support
3 //
4 // Authors: Martin Baulig (martin@ximian.com)
5 //          Miguel de Icaza (miguel@ximian.com)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
11 //
12 using System;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
17 using System.Text;
18 using System.Text.RegularExpressions;
19         
20 namespace Mono.CSharp {
21
22         /// <summary>
23         ///   Abstract base class for type parameter constraints.
24         ///   The type parameter can come from a generic type definition or from reflection.
25         /// </summary>
26         public abstract class GenericConstraints {
27                 public abstract string TypeParameter {
28                         get;
29                 }
30
31                 public abstract GenericParameterAttributes Attributes {
32                         get;
33                 }
34
35                 public bool HasConstructorConstraint {
36                         get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
37                 }
38
39                 public bool HasReferenceTypeConstraint {
40                         get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
41                 }
42
43                 public bool HasValueTypeConstraint {
44                         get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
45                 }
46
47                 public virtual bool HasClassConstraint {
48                         get { return ClassConstraint != null; }
49                 }
50
51                 public abstract Type ClassConstraint {
52                         get;
53                 }
54
55                 public abstract Type[] InterfaceConstraints {
56                         get;
57                 }
58
59                 public abstract Type EffectiveBaseClass {
60                         get;
61                 }
62
63                 // <summary>
64                 //   Returns whether the type parameter is "known to be a reference type".
65                 // </summary>
66                 public virtual bool IsReferenceType {
67                         get {
68                                 if (HasReferenceTypeConstraint)
69                                         return true;
70                                 if (HasValueTypeConstraint)
71                                         return false;
72
73                                 if (ClassConstraint != null) {
74                                         if (ClassConstraint.IsValueType)
75                                                 return false;
76
77                                         if (ClassConstraint != TypeManager.object_type)
78                                                 return true;
79                                 }
80
81                                 foreach (Type t in InterfaceConstraints) {
82                                         if (!t.IsGenericParameter)
83                                                 continue;
84
85                                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
86                                         if ((gc != null) && gc.IsReferenceType)
87                                                 return true;
88                                 }
89
90                                 return false;
91                         }
92                 }
93
94                 // <summary>
95                 //   Returns whether the type parameter is "known to be a value type".
96                 // </summary>
97                 public virtual bool IsValueType {
98                         get {
99                                 if (HasValueTypeConstraint)
100                                         return true;
101                                 if (HasReferenceTypeConstraint)
102                                         return false;
103
104                                 if (ClassConstraint != null) {
105                                         if (!ClassConstraint.IsValueType)
106                                                 return false;
107
108                                         if (ClassConstraint != TypeManager.value_type)
109                                                 return true;
110                                 }
111
112                                 foreach (Type t in InterfaceConstraints) {
113                                         if (!t.IsGenericParameter)
114                                                 continue;
115
116                                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
117                                         if ((gc != null) && gc.IsValueType)
118                                                 return true;
119                                 }
120
121                                 return false;
122                         }
123                 }
124         }
125
126         public enum SpecialConstraint
127         {
128                 Constructor,
129                 ReferenceType,
130                 ValueType
131         }
132
133         /// <summary>
134         ///   Tracks the constraints for a type parameter from a generic type definition.
135         /// </summary>
136         public class Constraints : GenericConstraints {
137                 string name;
138                 ArrayList constraints;
139                 Location loc;
140                 
141                 //
142                 // name is the identifier, constraints is an arraylist of
143                 // Expressions (with types) or `true' for the constructor constraint.
144                 // 
145                 public Constraints (string name, ArrayList constraints,
146                                     Location loc)
147                 {
148                         this.name = name;
149                         this.constraints = constraints;
150                         this.loc = loc;
151                 }
152
153                 public override string TypeParameter {
154                         get {
155                                 return name;
156                         }
157                 }
158
159                 GenericParameterAttributes attrs;
160                 TypeExpr class_constraint;
161                 ArrayList iface_constraints;
162                 ArrayList type_param_constraints;
163                 int num_constraints;
164                 Type class_constraint_type;
165                 Type[] iface_constraint_types;
166                 Type effective_base_type;
167                 bool resolved;
168                 bool resolved_types;
169
170                 /// <summary>
171                 ///   Resolve the constraints - but only resolve things into Expression's, not
172                 ///   into actual types.
173                 /// </summary>
174                 public bool Resolve (EmitContext ec)
175                 {
176                         if (resolved)
177                                 return true;
178
179                         iface_constraints = new ArrayList ();
180                         type_param_constraints = new ArrayList ();
181
182                         foreach (object obj in constraints) {
183                                 if (HasConstructorConstraint) {
184                                         Report.Error (401, loc,
185                                                       "The new() constraint must be last.");
186                                         return false;
187                                 }
188
189                                 if (obj is SpecialConstraint) {
190                                         SpecialConstraint sc = (SpecialConstraint) obj;
191
192                                         if (sc == SpecialConstraint.Constructor) {
193                                                 if (!HasValueTypeConstraint) {
194                                                         attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
195                                                         continue;
196                                                 }
197
198                                                 Report.Error (
199                                                         451, loc, "The new () constraint " +
200                                                         "cannot be used with the `struct' " +
201                                                         "constraint.");
202                                                 return false;
203                                         }
204
205                                         if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
206                                                 Report.Error (449, loc,
207                                                               "The `class' or `struct' " +
208                                                               "constraint must be first");
209                                                 return false;
210                                         }
211
212                                         if (sc == SpecialConstraint.ReferenceType)
213                                                 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
214                                         else
215                                                 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
216                                         continue;
217                                 }
218
219                                 int errors = Report.Errors;
220                                 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec);
221
222                                 if (fn == null) {
223                                         if (errors != Report.Errors)
224                                                 return false;
225
226                                         Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
227                                         return false;
228                                 }
229
230                                 TypeExpr expr;
231                                 ConstructedType cexpr = fn as ConstructedType;
232                                 if (cexpr != null) {
233                                         if (!cexpr.ResolveConstructedType (ec))
234                                                 return false;
235
236                                         expr = cexpr;
237                                 } else
238                                         expr = fn.ResolveAsTypeTerminal (ec);
239
240                                 if ((expr == null) || (expr.Type == null))
241                                         return false;
242
243                                 TypeParameterExpr texpr = expr as TypeParameterExpr;
244                                 if (texpr != null)
245                                         type_param_constraints.Add (expr);
246                                 else if (expr.IsInterface)
247                                         iface_constraints.Add (expr);
248                                 else if (class_constraint != null) {
249                                         Report.Error (406, loc,
250                                                       "`{0}': the class constraint for `{1}' " +
251                                                       "must come before any other constraints.",
252                                                       expr.Name, name);
253                                         return false;
254                                 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
255                                         Report.Error (450, loc, "`{0}': cannot specify both " +
256                                                       "a constraint class and the `class' " +
257                                                       "or `struct' constraint.", expr.Name);
258                                         return false;
259                                 } else
260                                         class_constraint = expr;
261
262                                 num_constraints++;
263                         }
264
265                         ArrayList list = new ArrayList ();
266                         foreach (TypeExpr iface_constraint in iface_constraints) {
267                                 foreach (Type type in list) {
268                                         if (!type.Equals (iface_constraint.Type))
269                                                 continue;
270
271                                         Report.Error (405, loc,
272                                                       "Duplicate constraint `{0}' for type " +
273                                                       "parameter `{1}'.", iface_constraint.GetSignatureForError (),
274                                                       name);
275                                         return false;
276                                 }
277
278                                 list.Add (iface_constraint.Type);
279                         }
280
281                         foreach (TypeParameterExpr expr in type_param_constraints) {
282                                 foreach (Type type in list) {
283                                         if (!type.Equals (expr.Type))
284                                                 continue;
285
286                                         Report.Error (405, loc,
287                                                       "Duplicate constraint `{0}' for type " +
288                                                       "parameter `{1}'.", expr.GetSignatureForError (), name);
289                                         return false;
290                                 }
291
292                                 list.Add (expr.Type);
293                         }
294
295                         iface_constraint_types = new Type [list.Count];
296                         list.CopyTo (iface_constraint_types, 0);
297
298                         if (class_constraint != null) {
299                                 class_constraint_type = class_constraint.Type;
300                                 if (class_constraint_type == null)
301                                         return false;
302
303                                 if (class_constraint_type.IsSealed) {
304                                         Report.Error (701, loc,
305                                                       "`{0}' is not a valid bound.  Bounds " +
306                                                       "must be interfaces or non sealed " +
307                                                       "classes", TypeManager.CSharpName (class_constraint_type));
308                                         return false;
309                                 }
310
311                                 if ((class_constraint_type == TypeManager.array_type) ||
312                                     (class_constraint_type == TypeManager.delegate_type) ||
313                                     (class_constraint_type == TypeManager.enum_type) ||
314                                     (class_constraint_type == TypeManager.value_type) ||
315                                     (class_constraint_type == TypeManager.object_type)) {
316                                         Report.Error (702, loc,
317                                                       "Bound cannot be special class `{0}'",
318                                                       TypeManager.CSharpName (class_constraint_type));
319                                         return false;
320                                 }
321                         }
322
323                         if (class_constraint_type != null)
324                                 effective_base_type = class_constraint_type;
325                         else if (HasValueTypeConstraint)
326                                 effective_base_type = TypeManager.value_type;
327                         else
328                                 effective_base_type = TypeManager.object_type;
329
330                         resolved = true;
331                         return true;
332                 }
333
334                 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
335                 {
336                         seen.Add (tparam, true);
337
338                         Constraints constraints = tparam.Constraints;
339                         if (constraints == null)
340                                 return true;
341
342                         if (constraints.HasValueTypeConstraint) {
343                                 Report.Error (456, loc, "Type parameter `{0}' has " +
344                                               "the `struct' constraint, so it cannot " +
345                                               "be used as a constraint for `{1}'",
346                                               tparam.Name, name);
347                                 return false;
348                         }
349
350                         if (constraints.type_param_constraints == null)
351                                 return true;
352
353                         foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
354                                 if (seen.Contains (expr.TypeParameter)) {
355                                         Report.Error (454, loc, "Circular constraint " +
356                                                       "dependency involving `{0}' and `{1}'",
357                                                       tparam.Name, expr.Name);
358                                         return false;
359                                 }
360
361                                 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
362                                         return false;
363                         }
364
365                         return true;
366                 }
367
368                 /// <summary>
369                 ///   Resolve the constraints into actual types.
370                 /// </summary>
371                 public bool ResolveTypes (EmitContext ec)
372                 {
373                         if (resolved_types)
374                                 return true;
375
376                         resolved_types = true;
377
378                         foreach (object obj in constraints) {
379                                 ConstructedType cexpr = obj as ConstructedType;
380                                 if (cexpr == null)
381                                         continue;
382
383                                 if (!cexpr.CheckConstraints (ec))
384                                         return false;
385                         }
386
387                         foreach (TypeParameterExpr expr in type_param_constraints) {
388                                 Hashtable seen = new Hashtable ();
389                                 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
390                                         return false;
391                         }
392
393                         foreach (TypeExpr iface_constraint in iface_constraints) {
394                                 if (iface_constraint.ResolveType (ec) == null)
395                                         return false;
396                         }
397
398                         if (class_constraint != null) {
399                                 if (class_constraint.ResolveType (ec) == null)
400                                         return false;
401                         }
402
403                         return true;
404                 }
405
406                 /// <summary>
407                 ///   Check whether there are no conflicts in our type parameter constraints.
408                 ///
409                 ///   This is an example:
410                 ///
411                 ///   class Foo<T,U>
412                 ///      where T : class
413                 ///      where U : T, struct
414                 /// </summary>
415                 public bool CheckDependencies (EmitContext ec)
416                 {
417                         foreach (TypeParameterExpr expr in type_param_constraints) {
418                                 if (!CheckDependencies (expr.TypeParameter, ec))
419                                         return false;
420                         }
421
422                         return true;
423                 }
424
425                 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
426                 {
427                         Constraints constraints = tparam.Constraints;
428                         if (constraints == null)
429                                 return true;
430
431                         if (HasValueTypeConstraint && constraints.HasClassConstraint) {
432                                 Report.Error (455, loc, "Type parameter `{0}' inherits " +
433                                               "conflicting constraints `{1}' and `{2}'",
434                                               name, TypeManager.CSharpName (constraints.ClassConstraint),
435                                               "System.ValueType");
436                                 return false;
437                         }
438
439                         if (HasClassConstraint && constraints.HasClassConstraint) {
440                                 Type t1 = ClassConstraint;
441                                 TypeExpr e1 = class_constraint;
442                                 Type t2 = constraints.ClassConstraint;
443                                 TypeExpr e2 = constraints.class_constraint;
444
445                                 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
446                                     !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
447                                         Report.Error (455, loc,
448                                                       "Type parameter `{0}' inherits " +
449                                                       "conflicting constraints `{1}' and `{2}'",
450                                                       name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
451                                         return false;
452                                 }
453                         }
454
455                         if (constraints.type_param_constraints == null)
456                                 return true;
457
458                         foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
459                                 if (!CheckDependencies (expr.TypeParameter, ec))
460                                         return false;
461                         }
462
463                         return true;
464                 }
465
466                 /// <summary>
467                 ///   Set the attributes on the GenericTypeParameterBuilder.
468                 /// </summary>
469                 /// <remarks>
470                 ///   This is not done in Resolve() since Resolve() may be called before
471                 ///   the GenericTypeParameterBuilder is created (partial generic classes).
472                 /// </remarks>
473                 public void Define (GenericTypeParameterBuilder type)
474                 {
475                         type.SetGenericParameterAttributes (attrs);
476                 }
477
478                 public override GenericParameterAttributes Attributes {
479                         get { return attrs; }
480                 }
481
482                 public override bool HasClassConstraint {
483                         get { return class_constraint != null; }
484                 }
485
486                 public override Type ClassConstraint {
487                         get { return class_constraint_type; }
488                 }
489
490                 public override Type[] InterfaceConstraints {
491                         get { return iface_constraint_types; }
492                 }
493
494                 public override Type EffectiveBaseClass {
495                         get { return effective_base_type; }
496                 }
497
498                 public bool IsSubclassOf (Type t)
499                 {
500                         if ((class_constraint_type != null) &&
501                             class_constraint_type.IsSubclassOf (t))
502                                 return true;
503
504                         if (iface_constraint_types == null)
505                                 return false;
506
507                         foreach (Type iface in iface_constraint_types) {
508                                 if (TypeManager.IsSubclassOf (iface, t))
509                                         return true;
510                         }
511
512                         return false;
513                 }
514
515                 /// <summary>
516                 ///   This is used when we're implementing a generic interface method.
517                 ///   Each method type parameter in implementing method must have the same
518                 ///   constraints than the corresponding type parameter in the interface
519                 ///   method.  To do that, we're called on each of the implementing method's
520                 ///   type parameters.
521                 /// </summary>
522                 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
523                 {
524                         if (gc.Attributes != attrs)
525                                 return false;
526
527                         if (HasClassConstraint != gc.HasClassConstraint)
528                                 return false;
529                         if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
530                                 return false;
531
532                         int gc_icount = gc.InterfaceConstraints != null ?
533                                 gc.InterfaceConstraints.Length : 0;
534                         int icount = InterfaceConstraints != null ?
535                                 InterfaceConstraints.Length : 0;
536
537                         if (gc_icount != icount)
538                                 return false;
539
540                         foreach (Type iface in gc.InterfaceConstraints) {
541                                 bool ok = false;
542                                 foreach (Type check in InterfaceConstraints) {
543                                         if (TypeManager.IsEqual (iface, check)) {
544                                                 ok = true;
545                                                 break;
546                                         }
547                                 }
548
549                                 if (!ok)
550                                         return false;
551                         }
552
553                         return true;
554                 }
555         }
556
557         /// <summary>
558         ///   A type parameter from a generic type definition.
559         /// </summary>
560         public class TypeParameter : MemberCore, IMemberContainer {
561                 string name;
562                 DeclSpace decl;
563                 GenericConstraints gc;
564                 Constraints constraints;
565                 Location loc;
566                 GenericTypeParameterBuilder type;
567
568                 public TypeParameter (TypeContainer parent, DeclSpace decl, string name,
569                                       Constraints constraints, Location loc)
570                         : base (parent, new MemberName (name, loc), null)
571                 {
572                         this.name = name;
573                         this.decl = decl;
574                         this.constraints = constraints;
575                         this.loc = loc;
576                 }
577
578                 public GenericConstraints GenericConstraints {
579                         get {
580                                 return gc != null ? gc : constraints;
581                         }
582                 }
583
584                 public Constraints Constraints {
585                         get {
586                                 return constraints;
587                         }
588                 }
589
590                 public bool HasConstructorConstraint {
591                         get {
592                                 if (constraints != null)
593                                         return constraints.HasConstructorConstraint;
594
595                                 return false;
596                         }
597                 }
598
599                 public DeclSpace DeclSpace {
600                         get {
601                                 return decl;
602                         }
603                 }
604
605                 public Type Type {
606                         get {
607                                 return type;
608                         }
609                 }
610
611                 /// <summary>
612                 ///   This is the first method which is called during the resolving
613                 ///   process; we're called immediately after creating the type parameters
614                 ///   with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
615                 ///   MethodBuilder).
616                 ///
617                 ///   We're either called from TypeContainer.DefineType() or from
618                 ///   GenericMethod.Define() (called from Method.Define()).
619                 /// </summary>
620                 public void Define (GenericTypeParameterBuilder type)
621                 {
622                         if (this.type != null)
623                                 throw new InvalidOperationException ();
624
625                         this.type = type;
626                         TypeManager.AddTypeParameter (type, this);
627                 }
628
629                 /// <summary>
630                 ///   This is the second method which is called during the resolving
631                 ///   process - in case of class type parameters, we're called from
632                 ///   TypeContainer.ResolveType() - after it resolved the class'es
633                 ///   base class and interfaces. For method type parameters, we're
634                 ///   called immediately after Define().
635                 ///
636                 ///   We're just resolving the constraints into expressions here, we
637                 ///   don't resolve them into actual types.
638                 ///
639                 ///   Note that in the special case of partial generic classes, we may be
640                 ///   called _before_ Define() and we may also be called multiple types.
641                 /// </summary>
642                 public bool Resolve (DeclSpace ds)
643                 {
644                         if (constraints != null) {
645                                 if (!constraints.Resolve (ds.EmitContext)) {
646                                         constraints = null;
647                                         return false;
648                                 }
649                         }
650
651                         return true;
652                 }
653
654                 /// <summary>
655                 ///   This is the third method which is called during the resolving
656                 ///   process.  We're called immediately after calling Resolve() on
657                 ///   all of the current class'es type parameters.
658                 ///
659                 ///   All we do is setting the attributes on the GenericTypeParameterBuilder.
660                 /// </summary>
661                 /// <remarks>
662                 ///   This is not done in Resolve() since Resolve() may be called before
663                 ///   Define() for partial generic classes.
664                 /// </remarks>
665                 public void DefineConstraints ()
666                 {
667                         if (constraints != null)
668                                 constraints.Define (type);
669                 }
670
671                 /// <summary>
672                 ///   This is the forth method which is called during the resolving
673                 ///   process.  We're called immediately after calling DefineConstraints()
674                 ///   on all of the current class'es type parameters.
675                 ///
676                 ///   Our job is to resolve the constraints to actual types.
677                 ///
678                 ///   Note that we may have circular dependencies on type parameters - this
679                 ///   is why Resolve() and ResolveType() are separate.
680                 /// </summary>
681                 public bool ResolveType (EmitContext ec)
682                 {
683                         if (constraints != null) {
684                                 if (!constraints.ResolveTypes (ec)) {
685                                         constraints = null;
686                                         return false;
687                                 }
688                         }
689
690                         return true;
691                 }
692
693                 /// <summary>
694                 ///   This is the fith and last method which is called during the resolving
695                 ///   process.  We're called after everything is fully resolved and actually
696                 ///   register the constraints with SRE and the TypeManager.
697                 /// </summary>
698                 public bool DefineType (EmitContext ec)
699                 {
700                         return DefineType (ec, null, null, false);
701                 }
702
703                 /// <summary>
704                 ///   This is the fith and last method which is called during the resolving
705                 ///   process.  We're called after everything is fully resolved and actually
706                 ///   register the constraints with SRE and the TypeManager.
707                 ///
708                 ///   The `builder', `implementing' and `is_override' arguments are only
709                 ///   applicable to method type parameters.
710                 /// </summary>
711                 public bool DefineType (EmitContext ec, MethodBuilder builder,
712                                         MethodInfo implementing, bool is_override)
713                 {
714                         if (!ResolveType (ec))
715                                 return false;
716
717                         if (implementing != null) {
718                                 if (is_override && (constraints != null)) {
719                                         Report.Error (
720                                                 460, loc, "Constraints for override and " +
721                                                 "explicit interface implementation methods " +
722                                                 "are inherited from the base method so they " +
723                                                 "cannot be specified directly");
724                                         return false;
725                                 }
726
727                                 MethodBase mb = implementing;
728                                 if (mb.Mono_IsInflatedMethod)
729                                         mb = mb.GetGenericMethodDefinition ();
730
731                                 int pos = type.GenericParameterPosition;
732                                 ParameterData pd = TypeManager.GetParameterData (mb);
733                                 GenericConstraints temp_gc = pd.GenericConstraints (pos);
734                                 Type mparam = mb.GetGenericArguments () [pos];
735
736                                 if (temp_gc != null)
737                                         gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
738                                 else if (constraints != null)
739                                         gc = new InflatedConstraints (constraints, implementing.DeclaringType);
740
741                                 bool ok = true;
742                                 if (constraints != null) {
743                                         if (temp_gc == null)
744                                                 ok = false;
745                                         else if (!constraints.CheckInterfaceMethod (ec, gc))
746                                                 ok = false;
747                                 } else {
748                                         if (!is_override && (temp_gc != null))
749                                                 ok = false;
750                                 }
751
752                                 if (!ok) {
753                                         Report.SymbolRelatedToPreviousError (implementing);
754
755                                         Report.Error (
756                                                 425, loc, "The constraints for type " +
757                                                 "parameter `{0}' of method `{1}' must match " +
758                                                 "the constraints for type parameter `{2}' " +
759                                                 "of interface method `{3}'. Consider using " +
760                                                 "an explicit interface implementation instead",
761                                                 Name, TypeManager.CSharpSignature (builder),
762                                                 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
763                                         return false;
764                                 }
765                         } else if (DeclSpace is Iterator) {
766                                 TypeParameter[] tparams = DeclSpace.TypeParameters;
767                                 Type[] types = new Type [tparams.Length];
768                                 for (int i = 0; i < tparams.Length; i++)
769                                         types [i] = tparams [i].Type;
770
771                                 if (constraints != null)
772                                         gc = new InflatedConstraints (constraints, types);
773                         } else {
774                                 gc = (GenericConstraints) constraints;
775                         }
776
777                         if (gc == null)
778                                 return true;
779
780                         if (gc.HasClassConstraint)
781                                 type.SetBaseTypeConstraint (gc.ClassConstraint);
782
783                         type.SetInterfaceConstraints (gc.InterfaceConstraints);
784                         TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
785
786                         return true;
787                 }
788
789                 /// <summary>
790                 ///   Check whether there are no conflicts in our type parameter constraints.
791                 ///
792                 ///   This is an example:
793                 ///
794                 ///   class Foo<T,U>
795                 ///      where T : class
796                 ///      where U : T, struct
797                 /// </summary>
798                 public bool CheckDependencies (EmitContext ec)
799                 {
800                         if (constraints != null)
801                                 return constraints.CheckDependencies (ec);
802
803                         return true;
804                 }
805
806                 /// <summary>
807                 ///   This is called for each part of a partial generic type definition.
808                 ///
809                 ///   If `new_constraints' is not null and we don't already have constraints,
810                 ///   they become our constraints.  If we already have constraints, we must
811                 ///   check that they're the same.
812                 ///   con
813                 /// </summary>
814                 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
815                 {
816                         if (type == null)
817                                 throw new InvalidOperationException ();
818
819                         if (constraints == null) {
820                                 new_constraints = constraints;
821                                 return true;
822                         } else if (new_constraints == null)
823                                 return true;
824
825                         if (!new_constraints.Resolve (ec))
826                                 return false;
827                         if (!new_constraints.ResolveTypes (ec))
828                                 return false;
829
830                         return constraints.CheckInterfaceMethod (ec, new_constraints);
831                 }
832
833                 public override string DocCommentHeader {
834                         get {
835                                 throw new InvalidOperationException (
836                                         "Unexpected attempt to get doc comment from " + this.GetType () + ".");
837                         }
838                 }
839
840                 //
841                 // MemberContainer
842                 //
843
844                 public override bool Define ()
845                 {
846                         return true;
847                 }
848
849                 public override void ApplyAttributeBuilder (Attribute a,
850                                                             CustomAttributeBuilder cb)
851                 { }
852
853                 public override AttributeTargets AttributeTargets {
854                         get {
855                                 return (AttributeTargets) 0;
856                         }
857                 }
858
859                 public override string[] ValidAttributeTargets {
860                         get {
861                                 return new string [0];
862                         }
863                 }
864
865                 //
866                 // IMemberContainer
867                 //
868
869                 string IMemberContainer.Name {
870                         get { return Name; }
871                 }
872
873                 MemberCache IMemberContainer.BaseCache {
874                         get { return null; }
875                 }
876
877                 bool IMemberContainer.IsInterface {
878                         get { return true; }
879                 }
880
881                 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
882                 {
883                         return FindMembers (mt, bf, null, null);
884                 }
885
886                 MemberCache IMemberContainer.MemberCache {
887                         get { return null; }
888                 }
889
890                 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
891                                                MemberFilter filter, object criteria)
892                 {
893                         if (constraints == null)
894                                 return MemberList.Empty;
895
896                         ArrayList members = new ArrayList ();
897
898                         GenericConstraints gc = (GenericConstraints) constraints;
899
900                         if (gc.HasClassConstraint) {
901                                 MemberList list = TypeManager.FindMembers (
902                                         gc.ClassConstraint, mt, bf, filter, criteria);
903
904                                 members.AddRange (list);
905                         }
906
907                         Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
908                         foreach (Type t in ifaces) {
909                                 MemberList list = TypeManager.FindMembers (
910                                         t, mt, bf, filter, criteria);
911
912                                 members.AddRange (list);
913                         }
914
915                         return new MemberList (members);
916                 }
917
918                 public bool IsSubclassOf (Type t)
919                 {
920                         if (type.Equals (t))
921                                 return true;
922
923                         if (constraints != null)
924                                 return constraints.IsSubclassOf (t);
925
926                         return false;
927                 }
928
929                 public override string ToString ()
930                 {
931                         return "TypeParameter[" + name + "]";
932                 }
933
934                 public static string GetSignatureForError (TypeParameter[] tp)
935                 {
936                         if (tp == null || tp.Length == 0)
937                                 return "";
938
939                         StringBuilder sb = new StringBuilder ("<");
940                         for (int i = 0; i < tp.Length; ++i) {
941                                 if (i > 0)
942                                         sb.Append (",");
943                                 sb.Append (tp[i].GetSignatureForError ());
944                         }
945                         sb.Append ('>');
946                         return sb.ToString ();
947                 }
948
949                 protected class InflatedConstraints : GenericConstraints
950                 {
951                         GenericConstraints gc;
952                         Type base_type;
953                         Type class_constraint;
954                         Type[] iface_constraints;
955                         Type[] dargs;
956
957                         public InflatedConstraints (GenericConstraints gc, Type declaring)
958                                 : this (gc, TypeManager.GetTypeArguments (declaring))
959                         { }
960
961                         public InflatedConstraints (GenericConstraints gc, Type[] dargs)
962                         {
963                                 this.gc = gc;
964                                 this.dargs = dargs;
965
966                                 ArrayList list = new ArrayList ();
967                                 if (gc.HasClassConstraint)
968                                         list.Add (inflate (gc.ClassConstraint));
969                                 foreach (Type iface in gc.InterfaceConstraints)
970                                         list.Add (inflate (iface));
971
972                                 bool has_class_constr = false;
973                                 if (list.Count > 0) {
974                                         Type first = (Type) list [0];
975                                         has_class_constr = !first.IsInterface && !first.IsGenericParameter;
976                                 }
977
978                                 if ((list.Count > 0) && has_class_constr) {
979                                         class_constraint = (Type) list [0];
980                                         iface_constraints = new Type [list.Count - 1];
981                                         list.CopyTo (1, iface_constraints, 0, list.Count - 1);
982                                 } else {
983                                         iface_constraints = new Type [list.Count];
984                                         list.CopyTo (iface_constraints, 0);
985                                 }
986
987                                 if (HasValueTypeConstraint)
988                                         base_type = TypeManager.value_type;
989                                 else if (class_constraint != null)
990                                         base_type = class_constraint;
991                                 else
992                                         base_type = TypeManager.object_type;
993                         }
994
995                         Type inflate (Type t)
996                         {
997                                 if (t == null)
998                                         return null;
999                                 if (t.IsGenericParameter)
1000                                         return dargs [t.GenericParameterPosition];
1001                                 if (t.IsGenericInstance) {
1002                                         t = t.GetGenericTypeDefinition ();
1003                                         t = t.MakeGenericType (dargs);
1004                                 }
1005
1006                                 return t;
1007                         }
1008
1009                         public override string TypeParameter {
1010                                 get { return gc.TypeParameter; }
1011                         }
1012
1013                         public override GenericParameterAttributes Attributes {
1014                                 get { return gc.Attributes; }
1015                         }
1016
1017                         public override Type ClassConstraint {
1018                                 get { return class_constraint; }
1019                         }
1020
1021                         public override Type EffectiveBaseClass {
1022                                 get { return base_type; }
1023                         }
1024
1025                         public override Type[] InterfaceConstraints {
1026                                 get { return iface_constraints; }
1027                         }
1028                 }
1029         }
1030
1031         /// <summary>
1032         ///   A TypeExpr which already resolved to a type parameter.
1033         /// </summary>
1034         public class TypeParameterExpr : TypeExpr {
1035                 TypeParameter type_parameter;
1036
1037                 public override string Name {
1038                         get {
1039                                 return type_parameter.Name;
1040                         }
1041                 }
1042
1043                 public override string FullName {
1044                         get {
1045                                 return type_parameter.Name;
1046                         }
1047                 }
1048
1049                 public TypeParameter TypeParameter {
1050                         get {
1051                                 return type_parameter;
1052                         }
1053                 }
1054                 
1055                 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1056                 {
1057                         this.type_parameter = type_parameter;
1058                         this.loc = loc;
1059                 }
1060
1061                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1062                 {
1063                         type = type_parameter.Type;
1064
1065                         return this;
1066                 }
1067
1068                 public override bool IsInterface {
1069                         get { return false; }
1070                 }
1071
1072                 public override bool CheckAccessLevel (DeclSpace ds)
1073                 {
1074                         return true;
1075                 }
1076
1077                 public void Error_CannotUseAsUnmanagedType (Location loc)
1078                 {
1079                         Report.Error (-203, loc, "Can not use type parameter as unamanged type");
1080                 }
1081         }
1082
1083         /// <summary>
1084         ///   Tracks the type arguments when instantiating a generic type.  We're used in
1085         ///   ConstructedType.
1086         /// </summary>
1087         public class TypeArguments {
1088                 public readonly Location Location;
1089                 ArrayList args;
1090                 Type[] atypes;
1091                 int dimension;
1092                 bool has_type_args;
1093                 bool created;
1094                 
1095                 public TypeArguments (Location loc)
1096                 {
1097                         args = new ArrayList ();
1098                         this.Location = loc;
1099                 }
1100
1101                 public TypeArguments (int dimension, Location loc)
1102                 {
1103                         this.dimension = dimension;
1104                         this.Location = loc;
1105                 }
1106
1107                 public void Add (Expression type)
1108                 {
1109                         if (created)
1110                                 throw new InvalidOperationException ();
1111
1112                         args.Add (type);
1113                 }
1114
1115                 public void Add (TypeArguments new_args)
1116                 {
1117                         if (created)
1118                                 throw new InvalidOperationException ();
1119
1120                         args.AddRange (new_args.args);
1121                 }
1122
1123                 /// <summary>
1124                 ///   We're used during the parsing process: the parser can't distinguish
1125                 ///   between type parameters and type arguments.  Because of that, the
1126                 ///   parser creates a `MemberName' with `TypeArguments' for both cases and
1127                 ///   in case of a generic type definition, we call GetDeclarations().
1128                 /// </summary>
1129                 public string[] GetDeclarations ()
1130                 {
1131                         string[] ret = new string [args.Count];
1132                         for (int i = 0; i < args.Count; i++) {
1133                                 SimpleName sn = args [i] as SimpleName;
1134                                 if (sn != null) {
1135                                         ret [i] = sn.Name;
1136                                         continue;
1137                                 }
1138
1139                                 Report.Error (81, Location, "Type parameter declaration " +
1140                                               "must be an identifier not a type");
1141                                 return null;
1142                         }
1143                         return ret;
1144                 }
1145
1146                 /// <summary>
1147                 ///   We may only be used after Resolve() is called and return the fully
1148                 ///   resolved types.
1149                 /// </summary>
1150                 public Type[] Arguments {
1151                         get {
1152                                 return atypes;
1153                         }
1154                 }
1155
1156                 public bool HasTypeArguments {
1157                         get {
1158                                 return has_type_args;
1159                         }
1160                 }
1161
1162                 public int Count {
1163                         get {
1164                                 if (dimension > 0)
1165                                         return dimension;
1166                                 else
1167                                         return args.Count;
1168                         }
1169                 }
1170
1171                 public bool IsUnbound {
1172                         get {
1173                                 return dimension > 0;
1174                         }
1175                 }
1176
1177                 public override string ToString ()
1178                 {
1179                         StringBuilder s = new StringBuilder ();
1180
1181                         int count = Count;
1182                         for (int i = 0; i < count; i++){
1183                                 //
1184                                 // FIXME: Use TypeManager.CSharpname once we have the type
1185                                 //
1186                                 if (args != null)
1187                                         s.Append (args [i].ToString ());
1188                                 if (i+1 < count)
1189                                         s.Append (",");
1190                         }
1191                         return s.ToString ();
1192                 }
1193
1194                 /// <summary>
1195                 ///   Resolve the type arguments.
1196                 /// </summary>
1197                 public bool Resolve (EmitContext ec)
1198                 {
1199                         int count = args.Count;
1200                         bool ok = true;
1201
1202                         atypes = new Type [count];
1203
1204                         for (int i = 0; i < count; i++){
1205                                 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1206                                 if (te == null) {
1207                                         ok = false;
1208                                         continue;
1209                                 }
1210                                 if (te is TypeParameterExpr)
1211                                         has_type_args = true;
1212
1213                                 if (te.Type.IsPointer) {
1214                                         Report.Error (306, Location, "The type `{0}' may not be used " +
1215                                                       "as a type argument.", TypeManager.CSharpName (te.Type));
1216                                         return false;
1217                                 }
1218
1219                                 atypes [i] = te.Type;
1220                         }
1221                         return ok;
1222                 }
1223         }
1224
1225         /// <summary>
1226         ///   An instantiation of a generic type.
1227         /// </summary>  
1228         public class ConstructedType : TypeExpr {
1229                 string full_name;
1230                 FullNamedExpression name;
1231                 TypeArguments args;
1232                 Type[] gen_params, atypes;
1233                 Type gt;
1234
1235                 /// <summary>
1236                 ///   Instantiate the generic type `fname' with the type arguments `args'.
1237                 /// </summary>          
1238                 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1239                 {
1240                         loc = l;
1241                         this.name = fname;
1242                         this.args = args;
1243
1244                         eclass = ExprClass.Type;
1245                         full_name = name + "<" + args.ToString () + ">";
1246                 }
1247
1248                 protected ConstructedType (TypeArguments args, Location l)
1249                 {
1250                         loc = l;
1251                         this.args = args;
1252
1253                         eclass = ExprClass.Type;
1254                 }
1255
1256                 protected ConstructedType (TypeParameter[] type_params, Location l)
1257                 {
1258                         loc = l;
1259
1260                         args = new TypeArguments (l);
1261                         foreach (TypeParameter type_param in type_params)
1262                                 args.Add (new TypeParameterExpr (type_param, l));
1263
1264                         eclass = ExprClass.Type;
1265                 }
1266
1267                 /// <summary>
1268                 ///   This is used to construct the `this' type inside a generic type definition.
1269                 /// </summary>
1270                 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1271                         : this (type_params, l)
1272                 {
1273                         gt = t.GetGenericTypeDefinition ();
1274
1275                         this.name = new TypeExpression (gt, l);
1276                         full_name = gt.FullName + "<" + args.ToString () + ">";
1277                 }
1278
1279                 /// <summary>
1280                 ///   Instantiate the generic type `t' with the type arguments `args'.
1281                 ///   Use this constructor if you already know the fully resolved
1282                 ///   generic type.
1283                 /// </summary>          
1284                 public ConstructedType (Type t, TypeArguments args, Location l)
1285                         : this (args, l)
1286                 {
1287                         gt = t.GetGenericTypeDefinition ();
1288
1289                         this.name = new TypeExpression (gt, l);
1290                         full_name = gt.FullName + "<" + args.ToString () + ">";
1291                 }
1292
1293                 public TypeArguments TypeArguments {
1294                         get { return args; }
1295                 }
1296
1297                 public override string GetSignatureForError ()
1298                 {
1299                         return TypeManager.CSharpName (gt);
1300                 }
1301
1302                 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1303                                                 Type ctype)
1304                 {
1305                         if (TypeManager.HasGenericArguments (ctype)) {
1306                                 Type[] types = TypeManager.GetTypeArguments (ctype);
1307
1308                                 TypeArguments new_args = new TypeArguments (loc);
1309
1310                                 for (int i = 0; i < types.Length; i++) {
1311                                         Type t = types [i];
1312
1313                                         if (t.IsGenericParameter) {
1314                                                 int pos = t.GenericParameterPosition;
1315                                                 t = args.Arguments [pos];
1316                                         }
1317                                         new_args.Add (new TypeExpression (t, loc));
1318                                 }
1319
1320                                 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1321                                 if (ct.ResolveAsTypeStep (ec) == null)
1322                                         return false;
1323                                 ctype = ct.Type;
1324                         }
1325
1326                         return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1327                 }
1328
1329                 protected bool CheckConstraints (EmitContext ec, int index)
1330                 {
1331                         Type atype = atypes [index];
1332                         Type ptype = gen_params [index];
1333
1334                         if (atype == ptype)
1335                                 return true;
1336
1337                         Expression aexpr = new EmptyExpression (atype);
1338
1339                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1340                         if (gc == null)
1341                                 return true;
1342
1343                         bool is_class, is_struct;
1344                         if (atype.IsGenericParameter) {
1345                                 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1346                                 if (agc != null) {
1347                                         is_class = agc.HasReferenceTypeConstraint;
1348                                         is_struct = agc.HasValueTypeConstraint;
1349                                 } else {
1350                                         is_class = is_struct = false;
1351                                 }
1352                         } else {
1353                                 is_class = atype.IsClass;
1354                                 is_struct = atype.IsValueType;
1355                         }
1356
1357                         //
1358                         // First, check the `class' and `struct' constraints.
1359                         //
1360                         if (gc.HasReferenceTypeConstraint && !is_class) {
1361                                 Report.Error (452, loc, "The type `{0}' must be " +
1362                                               "a reference type in order to use it " +
1363                                               "as type parameter `{1}' in the " +
1364                                               "generic type or method `{2}'.",
1365                                               TypeManager.CSharpName (atype),
1366                                               TypeManager.CSharpName (ptype),
1367                                               GetSignatureForError ());
1368                                 return false;
1369                         } else if (gc.HasValueTypeConstraint && !is_struct) {
1370                                 Report.Error (453, loc, "The type `{0}' must be " +
1371                                               "a value type in order to use it " +
1372                                               "as type parameter `{1}' in the " +
1373                                               "generic type or method `{2}'.",
1374                                               TypeManager.CSharpName (atype),
1375                                               TypeManager.CSharpName (ptype),
1376                                               GetSignatureForError ());
1377                                 return false;
1378                         }
1379
1380                         //
1381                         // The class constraint comes next.
1382                         //
1383                         if (gc.HasClassConstraint) {
1384                                 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1385                                         Error_TypeMustBeConvertible (atype, gc.ClassConstraint, ptype);
1386                                         return false;
1387                                 }
1388                         }
1389
1390                         //
1391                         // Now, check the interface constraints.
1392                         //
1393                         foreach (Type it in gc.InterfaceConstraints) {
1394                                 Type itype;
1395                                 if (it.IsGenericParameter)
1396                                         itype = atypes [it.GenericParameterPosition];
1397                                 else
1398                                         itype = it;
1399
1400                                 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1401                                         Error_TypeMustBeConvertible (atype, itype, ptype);
1402                                         return false;
1403                                 }
1404                         }
1405
1406                         //
1407                         // Finally, check the constructor constraint.
1408                         //
1409
1410                         if (!gc.HasConstructorConstraint)
1411                                 return true;
1412
1413                         if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1414                                 return true;
1415
1416                         if (HasDefaultConstructor (ec, atype))
1417                                 return true;
1418
1419                         Report.SymbolRelatedToPreviousError (gt);
1420                         Report.SymbolRelatedToPreviousError (atype);
1421                         Report.Error (310, loc, "The type `{0}' must have a public " +
1422                                       "parameterless constructor in order to use it " +
1423                                       "as parameter `{1}' in the generic type or " +
1424                                       "method `{2}'",
1425                                       TypeManager.CSharpName (atype),
1426                                       TypeManager.CSharpName (ptype),
1427                                       GetSignatureForError ());
1428                         return false;
1429                 }
1430
1431                 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1432                 {
1433                         Report.SymbolRelatedToPreviousError (gt);
1434                         Report.SymbolRelatedToPreviousError (atype);
1435                         Report.Error (309, loc, "The type `{0}' must be convertible to `{1}' in order to " +
1436                                           "use it as parameter `{2}' in the generic type or method `{3}'",
1437                                           TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1438                                           TypeManager.CSharpName (ptype), GetSignatureForError ());
1439                 }
1440
1441                 bool HasDefaultConstructor (EmitContext ec, Type atype)
1442                 {
1443                         if (atype is TypeBuilder) {
1444                                 if (atype.IsAbstract)
1445                                         return false;
1446
1447                                 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1448                                 foreach (Constructor c in tc.InstanceConstructors) {
1449                                         if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1450                                                 continue;
1451                                         if ((c.Parameters.FixedParameters != null) &&
1452                                             (c.Parameters.FixedParameters.Length != 0))
1453                                                 continue;
1454                                         if (c.Parameters.HasArglist ||
1455                                             (c.Parameters.ArrayParameter != null))
1456                                                 continue;
1457
1458                                         return true;
1459                                 }
1460                         }
1461
1462                         MethodGroupExpr mg = Expression.MemberLookup (
1463                                 ec, atype, ".ctor", MemberTypes.Constructor,
1464                                 BindingFlags.Public | BindingFlags.Instance |
1465                                 BindingFlags.DeclaredOnly, loc)
1466                                 as MethodGroupExpr;
1467
1468                         if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
1469                                 foreach (MethodBase mb in mg.Methods) {
1470                                         ParameterData pd = TypeManager.GetParameterData (mb);
1471                                         if (pd.Count == 0)
1472                                                 return true;
1473                                 }
1474                         }
1475
1476                         return false;
1477                 }
1478
1479                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1480                 {
1481                         if (!ResolveConstructedType (ec))
1482                                 return null;
1483
1484                         return this;
1485                 }
1486
1487                 /// <summary>
1488                 ///   Check the constraints; we're called from ResolveAsTypeTerminal()
1489                 ///   after fully resolving the constructed type.
1490                 /// </summary>
1491                 public bool CheckConstraints (EmitContext ec)
1492                 {
1493                         for (int i = 0; i < gen_params.Length; i++) {
1494                                 if (!CheckConstraints (ec, i))
1495                                         return false;
1496                         }
1497
1498                         return true;
1499                 }
1500
1501                 /// <summary>
1502                 ///   Resolve the constructed type, but don't check the constraints.
1503                 /// </summary>
1504                 public bool ResolveConstructedType (EmitContext ec)
1505                 {
1506                         if (type != null)
1507                                 return true;
1508                         // If we already know the fully resolved generic type.
1509                         if (gt != null)
1510                                 return DoResolveType (ec);
1511
1512                         int num_args;
1513                         Type t = name.Type;
1514
1515                         if (t == null) {
1516                                 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1517                                 return false;
1518                         }
1519
1520                         num_args = TypeManager.GetNumberOfTypeArguments (t);
1521                         if (num_args == 0) {
1522                                 Report.Error (308, loc,
1523                                               "The non-generic type `{0}' cannot " +
1524                                               "be used with type arguments.",
1525                                               TypeManager.CSharpName (t));
1526                                 return false;
1527                         }
1528
1529                         gt = t.GetGenericTypeDefinition ();
1530                         return DoResolveType (ec);
1531                 }
1532
1533                 bool DoResolveType (EmitContext ec)
1534                 {
1535                         //
1536                         // Resolve the arguments.
1537                         //
1538                         if (args.Resolve (ec) == false)
1539                                 return false;
1540
1541                         gen_params = gt.GetGenericArguments ();
1542                         atypes = args.Arguments;
1543
1544                         if (atypes.Length != gen_params.Length) {
1545                                 Report.Error (305, loc,
1546                                               "Using the generic type `{0}' " +
1547                                               "requires {1} type arguments",
1548                                               TypeManager.CSharpName (gt),
1549                                               gen_params.Length.ToString ());
1550                                 return false;
1551                         }
1552
1553                         //
1554                         // Now bind the parameters.
1555                         //
1556                         type = gt.MakeGenericType (atypes);
1557                         return true;
1558                 }
1559
1560                 public Expression GetSimpleName (EmitContext ec)
1561                 {
1562                         return this;
1563                 }
1564
1565                 public override bool CheckAccessLevel (DeclSpace ds)
1566                 {
1567                         return ds.CheckAccessLevel (gt);
1568                 }
1569
1570                 public override bool AsAccessible (DeclSpace ds, int flags)
1571                 {
1572                         return ds.AsAccessible (gt, flags);
1573                 }
1574
1575                 public override bool IsClass {
1576                         get { return gt.IsClass; }
1577                 }
1578
1579                 public override bool IsValueType {
1580                         get { return gt.IsValueType; }
1581                 }
1582
1583                 public override bool IsInterface {
1584                         get { return gt.IsInterface; }
1585                 }
1586
1587                 public override bool IsSealed {
1588                         get { return gt.IsSealed; }
1589                 }
1590
1591                 public override bool Equals (object obj)
1592                 {
1593                         ConstructedType cobj = obj as ConstructedType;
1594                         if (cobj == null)
1595                                 return false;
1596
1597                         if ((type == null) || (cobj.type == null))
1598                                 return false;
1599
1600                         return type == cobj.type;
1601                 }
1602
1603                 public override int GetHashCode ()
1604                 {
1605                         return base.GetHashCode ();
1606                 }
1607
1608                 public override string Name {
1609                         get {
1610                                 return full_name;
1611                         }
1612                 }
1613
1614
1615                 public override string FullName {
1616                         get {
1617                                 return full_name;
1618                         }
1619                 }
1620         }
1621
1622         /// <summary>
1623         ///   A generic method definition.
1624         /// </summary>
1625         public class GenericMethod : DeclSpace
1626         {
1627                 Expression return_type;
1628                 Parameters parameters;
1629
1630                 public GenericMethod (NamespaceEntry ns, TypeContainer parent, MemberName name,
1631                                       Expression return_type, Parameters parameters)
1632                         : base (ns, parent, name, null)
1633                 {
1634                         this.return_type = return_type;
1635                         this.parameters = parameters;
1636                 }
1637
1638                 public override TypeBuilder DefineType ()
1639                 {
1640                         throw new Exception ();
1641                 }
1642
1643                 public override bool Define ()
1644                 {
1645                         ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1646
1647                         for (int i = 0; i < TypeParameters.Length; i++)
1648                                 if (!TypeParameters [i].Resolve (this))
1649                                         return false;
1650
1651                         return true;
1652                 }
1653
1654                 /// <summary>
1655                 ///   Define and resolve the type parameters.
1656                 ///   We're called from Method.Define().
1657                 /// </summary>
1658                 public bool Define (MethodBuilder mb)
1659                 {
1660                         GenericTypeParameterBuilder[] gen_params;
1661                         string[] names = MemberName.TypeArguments.GetDeclarations ();
1662                         gen_params = mb.DefineGenericParameters (names);
1663                         for (int i = 0; i < TypeParameters.Length; i++)
1664                                 TypeParameters [i].Define (gen_params [i]);
1665
1666                         if (!Define ())
1667                                 return false;
1668
1669                         for (int i = 0; i < TypeParameters.Length; i++) {
1670                                 if (!TypeParameters [i].ResolveType (ec))
1671                                         return false;
1672                         }
1673
1674                         for (int i = 0; i < TypeParameters.Length; i++)
1675                                 TypeParameters [i].DefineConstraints ();
1676
1677                         return true;
1678                 }
1679
1680                 /// <summary>
1681                 ///   We're called from MethodData.Define() after creating the MethodBuilder.
1682                 /// </summary>
1683                 public bool DefineType (EmitContext ec, MethodBuilder mb,
1684                                         MethodInfo implementing, bool is_override)
1685                 {
1686                         for (int i = 0; i < TypeParameters.Length; i++)
1687                                 if (!TypeParameters [i].DefineType (
1688                                             ec, mb, implementing, is_override))
1689                                         return false;
1690
1691                         bool ok = true;
1692                         if (parameters.FixedParameters != null) {
1693                                 foreach (Parameter p in parameters.FixedParameters){
1694                                         if (!p.Resolve (ec))
1695                                                 ok = false;
1696                                 }
1697                         }
1698                         if (parameters.ArrayParameter != null) {
1699                                 if (!parameters.ArrayParameter.Resolve (ec))
1700                                         ok = false;
1701                         }
1702                         if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec) == null))
1703                                 ok = false;
1704
1705                         return ok;
1706                 }
1707
1708                 public override bool DefineMembers (TypeContainer parent)
1709                 {
1710                         return true;
1711                 }
1712
1713                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1714                                                         MemberFilter filter, object criteria)
1715                 {
1716                         throw new Exception ();
1717                 }               
1718
1719                 public override MemberCache MemberCache {
1720                         get {
1721                                 return null;
1722                         }
1723                 }
1724
1725                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1726                 {
1727                         // FIXME
1728                 }
1729
1730                 public override AttributeTargets AttributeTargets {
1731                         get {
1732                                 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1733                         }
1734                 }
1735
1736                 public override string DocCommentHeader {
1737                         get { return "M:"; }
1738                 }
1739         }
1740
1741         public class DefaultValueExpression : Expression
1742         {
1743                 Expression expr;
1744
1745                 public DefaultValueExpression (Expression expr, Location loc)
1746                 {
1747                         this.expr = expr;
1748                         this.loc = loc;
1749                 }
1750
1751                 public override Expression DoResolve (EmitContext ec)
1752                 {
1753                         TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1754                         if (texpr == null)
1755                                 return null;
1756
1757                         type = texpr.Type;
1758
1759                         eclass = ExprClass.Variable;
1760                         return this;
1761                 }
1762
1763                 public override void Emit (EmitContext ec)
1764                 {
1765                         if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1766                                 LocalTemporary temp_storage = new LocalTemporary (ec, type);
1767
1768                                 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1769                                 ec.ig.Emit (OpCodes.Initobj, type);
1770                                 temp_storage.Emit (ec);
1771                         } else
1772                                 ec.ig.Emit (OpCodes.Ldnull);
1773                 }
1774         }
1775
1776         public class NullableType : TypeExpr
1777         {
1778                 Expression underlying;
1779
1780                 public NullableType (Expression underlying, Location l)
1781                 {
1782                         this.underlying = underlying;
1783                         loc = l;
1784
1785                         eclass = ExprClass.Type;
1786                 }
1787
1788                 public NullableType (Type type, Location loc)
1789                         : this (new TypeExpression (type, loc), loc)
1790                 { }
1791
1792                 public override string Name {
1793                         get { return underlying.ToString () + "?"; }
1794                 }
1795
1796                 public override string FullName {
1797                         get { return underlying.ToString () + "?"; }
1798                 }
1799
1800                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1801                 {
1802                         TypeArguments args = new TypeArguments (loc);
1803                         args.Add (underlying);
1804
1805                         ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1806                         return ctype.ResolveAsTypeTerminal (ec);
1807                 }
1808         }
1809
1810         public partial class TypeManager
1811         {
1812                 //
1813                 // A list of core types that the compiler requires or uses
1814                 //
1815                 static public Type activator_type;
1816                 static public Type generic_ienumerator_type;
1817                 static public Type generic_ienumerable_type;
1818                 static public Type generic_nullable_type;
1819
1820                 // <remarks>
1821                 //   Tracks the generic parameters.
1822                 // </remarks>
1823                 static PtrHashtable builder_to_type_param;
1824
1825                 //
1826                 // These methods are called by code generated by the compiler
1827                 //
1828                 static public MethodInfo activator_create_instance;
1829
1830                 static void InitGenerics ()
1831                 {
1832                         builder_to_type_param = new PtrHashtable ();
1833                 }
1834
1835                 static void CleanUpGenerics ()
1836                 {
1837                         builder_to_type_param = null;
1838                 }
1839
1840                 static void InitGenericCoreTypes ()
1841                 {
1842                         activator_type = CoreLookupType ("System", "Activator");
1843
1844                         generic_ienumerator_type = CoreLookupType (
1845                                 "System.Collections.Generic", "IEnumerator", 1);
1846                         generic_ienumerable_type = CoreLookupType (
1847                                 "System.Collections.Generic", "IEnumerable", 1);
1848                         generic_nullable_type = CoreLookupType (
1849                                 "System", "Nullable", 1);
1850                 }
1851
1852                 static void InitGenericCodeHelpers ()
1853                 {
1854                         // Activator
1855                         Type [] type_arg = { type_type };
1856                         activator_create_instance = GetMethod (
1857                                 activator_type, "CreateInstance", type_arg);
1858                 }
1859
1860                 static Type CoreLookupType (string ns, string name, int arity)
1861                 {
1862                         return CoreLookupType (ns, MemberName.MakeName (name, arity));
1863                 }
1864
1865                 public static void AddTypeParameter (Type t, TypeParameter tparam)
1866                 {
1867                         if (!builder_to_type_param.Contains (t))
1868                                 builder_to_type_param.Add (t, tparam);
1869                 }
1870
1871                 public static TypeContainer LookupGenericTypeContainer (Type t)
1872                 {
1873                         while (t.IsGenericInstance)
1874                                 t = t.GetGenericTypeDefinition ();
1875
1876                         return LookupTypeContainer (t);
1877                 }
1878
1879                 public static TypeParameter LookupTypeParameter (Type t)
1880                 {
1881                         return (TypeParameter) builder_to_type_param [t];
1882                 }
1883
1884                 public static GenericConstraints GetTypeParameterConstraints (Type t)
1885                 {
1886                         if (!t.IsGenericParameter)
1887                                 throw new InvalidOperationException ();
1888
1889                         TypeParameter tparam = LookupTypeParameter (t);
1890                         if (tparam != null)
1891                                 return tparam.GenericConstraints;
1892
1893                         return new ReflectionConstraints (t);
1894                 }
1895
1896                 public static bool IsGeneric (Type t)
1897                 {
1898                         DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1899
1900                         return ds.IsGeneric;
1901                 }
1902
1903                 public static bool HasGenericArguments (Type t)
1904                 {
1905                         return GetNumberOfTypeArguments (t) > 0;
1906                 }
1907
1908                 public static int GetNumberOfTypeArguments (Type t)
1909                 {
1910                         if (t.IsGenericParameter)
1911                                 return 0;
1912                         DeclSpace tc = LookupDeclSpace (t);
1913                         if (tc != null)
1914                                 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1915                         else
1916                                 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
1917                 }
1918
1919                 public static Type[] GetTypeArguments (Type t)
1920                 {
1921                         DeclSpace tc = LookupDeclSpace (t);
1922                         if (tc != null) {
1923                                 if (!tc.IsGeneric)
1924                                         return Type.EmptyTypes;
1925
1926                                 TypeParameter[] tparam = tc.TypeParameters;
1927                                 Type[] ret = new Type [tparam.Length];
1928                                 for (int i = 0; i < tparam.Length; i++) {
1929                                         ret [i] = tparam [i].Type;
1930                                         if (ret [i] == null)
1931                                                 throw new InternalErrorException ();
1932                                 }
1933
1934                                 return ret;
1935                         } else
1936                                 return t.GetGenericArguments ();
1937                 }
1938
1939                 //
1940                 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
1941                 // For instance "string[]" -> "IEnumerable<string>".
1942                 //
1943                 public static bool IsIEnumerable (Type array, Type enumerator)
1944                 {
1945                         if (!array.IsArray || !enumerator.IsGenericInstance)
1946                                 return false;
1947
1948                         if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
1949                                 return false;
1950
1951                         Type[] args = GetTypeArguments (enumerator);
1952                         return args [0] == GetElementType (array);
1953                 }
1954
1955                 public static bool IsEqual (Type a, Type b)
1956                 {
1957                         if (a.Equals (b))
1958                                 return true;
1959
1960                         if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1961                                 //
1962                                 // `a' is a generic type definition's TypeBuilder and `b' is a
1963                                 // generic instance of the same type.
1964                                 //
1965                                 // Example:
1966                                 //
1967                                 // class Stack<T>
1968                                 // {
1969                                 //     void Test (Stack<T> stack) { }
1970                                 // }
1971                                 //
1972                                 // The first argument of `Test' will be the generic instance
1973                                 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1974                                 //
1975                                 //
1976                                 // We hit this via Closure.Filter() for gen-82.cs.
1977                                 //
1978                                 if (a != b.GetGenericTypeDefinition ())
1979                                         return false;
1980
1981                                 Type[] aparams = a.GetGenericArguments ();
1982                                 Type[] bparams = b.GetGenericArguments ();
1983
1984                                 if (aparams.Length != bparams.Length)
1985                                         return false;
1986
1987                                 for (int i = 0; i < aparams.Length; i++)
1988                                         if (!IsEqual (aparams [i], bparams [i]))
1989                                                 return false;
1990
1991                                 return true;
1992                         }
1993
1994                         if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
1995                                 return IsEqual (b, a);
1996
1997                         if (a.IsGenericParameter && b.IsGenericParameter) {
1998                                 if (a.DeclaringMethod != b.DeclaringMethod &&
1999                                     (a.DeclaringMethod == null || b.DeclaringMethod == null))
2000                                         return false;
2001                                 return a.GenericParameterPosition == b.GenericParameterPosition;
2002                         }
2003
2004                         if (a.IsArray && b.IsArray) {
2005                                 if (a.GetArrayRank () != b.GetArrayRank ())
2006                                         return false;
2007                                 return IsEqual (a.GetElementType (), b.GetElementType ());
2008                         }
2009
2010                         if (a.IsGenericInstance && b.IsGenericInstance) {
2011                                 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2012                                         return false;
2013
2014                                 Type[] aargs = a.GetGenericArguments ();
2015                                 Type[] bargs = b.GetGenericArguments ();
2016
2017                                 if (aargs.Length != bargs.Length)
2018                                         return false;
2019
2020                                 for (int i = 0; i < aargs.Length; i++) {
2021                                         if (!IsEqual (aargs [i], bargs [i]))
2022                                                 return false;
2023                                 }
2024
2025                                 return true;
2026                         }
2027
2028                         return false;
2029                 }
2030
2031                 /// <summary>
2032                 ///   Check whether `a' and `b' may become equal generic types.
2033                 ///   The algorithm to do that is a little bit complicated.
2034                 /// </summary>
2035                 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2036                                                                Type[] method_infered)
2037                 {
2038                         if (a.IsGenericParameter) {
2039                                 //
2040                                 // If a is an array of a's type, they may never
2041                                 // become equal.
2042                                 //
2043                                 while (b.IsArray) {
2044                                         b = b.GetElementType ();
2045                                         if (a.Equals (b))
2046                                                 return false;
2047                                 }
2048
2049                                 //
2050                                 // If b is a generic parameter or an actual type,
2051                                 // they may become equal:
2052                                 //
2053                                 //    class X<T,U> : I<T>, I<U>
2054                                 //    class X<T> : I<T>, I<float>
2055                                 // 
2056                                 if (b.IsGenericParameter || !b.IsGenericInstance) {
2057                                         int pos = a.GenericParameterPosition;
2058                                         Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2059                                         if (args [pos] == null) {
2060                                                 args [pos] = b;
2061                                                 return true;
2062                                         }
2063
2064                                         return args [pos] == a;
2065                                 }
2066
2067                                 //
2068                                 // We're now comparing a type parameter with a
2069                                 // generic instance.  They may become equal unless
2070                                 // the type parameter appears anywhere in the
2071                                 // generic instance:
2072                                 //
2073                                 //    class X<T,U> : I<T>, I<X<U>>
2074                                 //        -> error because you could instanciate it as
2075                                 //           X<X<int>,int>
2076                                 //
2077                                 //    class X<T> : I<T>, I<X<T>> -> ok
2078                                 //
2079
2080                                 Type[] bargs = GetTypeArguments (b);
2081                                 for (int i = 0; i < bargs.Length; i++) {
2082                                         if (a.Equals (bargs [i]))
2083                                                 return false;
2084                                 }
2085
2086                                 return true;
2087                         }
2088
2089                         if (b.IsGenericParameter)
2090                                 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2091
2092                         //
2093                         // At this point, neither a nor b are a type parameter.
2094                         //
2095                         // If one of them is a generic instance, let
2096                         // MayBecomeEqualGenericInstances() compare them (if the
2097                         // other one is not a generic instance, they can never
2098                         // become equal).
2099                         //
2100
2101                         if (a.IsGenericInstance || b.IsGenericInstance)
2102                                 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2103
2104                         //
2105                         // If both of them are arrays.
2106                         //
2107
2108                         if (a.IsArray && b.IsArray) {
2109                                 if (a.GetArrayRank () != b.GetArrayRank ())
2110                                         return false;
2111                         
2112                                 a = a.GetElementType ();
2113                                 b = b.GetElementType ();
2114
2115                                 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2116                         }
2117
2118                         //
2119                         // Ok, two ordinary types.
2120                         //
2121
2122                         return a.Equals (b);
2123                 }
2124
2125                 //
2126                 // Checks whether two generic instances may become equal for some
2127                 // particular instantiation (26.3.1).
2128                 //
2129                 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2130                                                                    Type[] class_infered,
2131                                                                    Type[] method_infered)
2132                 {
2133                         if (!a.IsGenericInstance || !b.IsGenericInstance)
2134                                 return false;
2135                         if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2136                                 return false;
2137
2138                         return MayBecomeEqualGenericInstances (
2139                                 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2140                 }
2141
2142                 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2143                                                                    Type[] class_infered,
2144                                                                    Type[] method_infered)
2145                 {
2146                         if (aargs.Length != bargs.Length)
2147                                 return false;
2148
2149                         for (int i = 0; i < aargs.Length; i++) {
2150                                 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2151                                         return false;
2152                         }
2153
2154                         return true;
2155                 }
2156
2157                 /// <summary>
2158                 ///   Check whether `type' and `parent' are both instantiations of the same
2159                 ///   generic type.  Note that we do not check the type parameters here.
2160                 /// </summary>
2161                 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2162                 {
2163                         int tcount = GetNumberOfTypeArguments (type);
2164                         int pcount = GetNumberOfTypeArguments (parent);
2165
2166                         if (type.IsGenericInstance)
2167                                 type = type.GetGenericTypeDefinition ();
2168                         if (parent.IsGenericInstance)
2169                                 parent = parent.GetGenericTypeDefinition ();
2170
2171                         if (tcount != pcount)
2172                                 return false;
2173
2174                         return type.Equals (parent);
2175                 }
2176
2177                 /// <summary>
2178                 ///   Whether `mb' is a generic method definition.
2179                 /// </summary>
2180                 public static bool IsGenericMethod (MethodBase mb)
2181                 {
2182                         if (mb.DeclaringType is TypeBuilder) {
2183                                 IMethodData method = (IMethodData) builder_to_method [mb];
2184                                 if (method == null)
2185                                         return false;
2186
2187                                 return method.GenericMethod != null;
2188                         }
2189
2190                         return mb.IsGenericMethodDefinition;
2191                 }
2192
2193                 //
2194                 // Type inference.
2195                 //
2196
2197                 static bool InferType (Type pt, Type at, Type[] infered)
2198                 {
2199                         if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
2200                                 int pos = pt.GenericParameterPosition;
2201
2202                                 if (infered [pos] == null) {
2203                                         Type check = at;
2204                                         while (check.IsArray)
2205                                                 check = check.GetElementType ();
2206
2207                                         if (pt == check)
2208                                                 return false;
2209
2210                                         infered [pos] = at;
2211                                         return true;
2212                                 }
2213
2214                                 if (infered [pos] != at)
2215                                         return false;
2216
2217                                 return true;
2218                         }
2219
2220                         if (!pt.ContainsGenericParameters) {
2221                                 if (at.ContainsGenericParameters)
2222                                         return InferType (at, pt, infered);
2223                                 else
2224                                         return true;
2225                         }
2226
2227                         if (at.IsArray) {
2228                                 if (!pt.IsArray ||
2229                                     (at.GetArrayRank () != pt.GetArrayRank ()))
2230                                         return false;
2231
2232                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2233                         }
2234
2235                         if (pt.IsArray) {
2236                                 if (!at.IsArray ||
2237                                     (pt.GetArrayRank () != at.GetArrayRank ()))
2238                                         return false;
2239
2240                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2241                         }
2242
2243                         if (pt.IsByRef && at.IsByRef)
2244                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2245                         ArrayList list = new ArrayList ();
2246                         if (at.IsGenericInstance)
2247                                 list.Add (at);
2248                         for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2249                                 list.Add (bt);
2250
2251                         list.AddRange (TypeManager.GetInterfaces (at));
2252
2253                         bool found_one = false;
2254
2255                         foreach (Type type in list) {
2256                                 if (!type.IsGenericInstance)
2257                                         continue;
2258
2259                                 Type[] infered_types = new Type [infered.Length];
2260
2261                                 if (!InferGenericInstance (pt, type, infered_types))
2262                                         continue;
2263
2264                                 for (int i = 0; i < infered_types.Length; i++) {
2265                                         if (infered [i] == null) {
2266                                                 infered [i] = infered_types [i];
2267                                                 continue;
2268                                         }
2269
2270                                         if (infered [i] != infered_types [i])
2271                                                 return false;
2272                                 }
2273
2274                                 found_one = true;
2275                         }
2276
2277                         return found_one;
2278                 }
2279
2280                 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2281                 {
2282                         Type[] at_args = at.GetGenericArguments ();
2283                         Type[] pt_args = pt.GetGenericArguments ();
2284
2285                         if (at_args.Length != pt_args.Length)
2286                                 return false;
2287
2288                         for (int i = 0; i < at_args.Length; i++) {
2289                                 if (!InferType (pt_args [i], at_args [i], infered_types))
2290                                         return false;
2291                         }
2292
2293                         for (int i = 0; i < infered_types.Length; i++) {
2294                                 if (infered_types [i] == null)
2295                                         return false;
2296                         }
2297
2298                         return true;
2299                 }
2300
2301                 /// <summary>
2302                 ///   Type inference.  Try to infer the type arguments from the params method
2303                 ///   `method', which is invoked with the arguments `arguments'.  This is used
2304                 ///   when resolving an Invocation or a DelegateInvocation and the user
2305                 ///   did not explicitly specify type arguments.
2306                 /// </summary>
2307                 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2308                                                              ref MethodBase method)
2309                 {
2310                         if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2311                                 return true;
2312
2313                         int arg_count;
2314                         
2315                         if (arguments == null)
2316                                 arg_count = 0;
2317                         else
2318                                 arg_count = arguments.Count;
2319                         
2320                         ParameterData pd = TypeManager.GetParameterData (method);
2321
2322                         int pd_count = pd.Count;
2323
2324                         if (pd_count == 0)
2325                                 return false;
2326                         
2327                         if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2328                                 return false;
2329                         
2330                         if (pd_count - 1 > arg_count)
2331                                 return false;
2332                         
2333                         if (pd_count == 1 && arg_count == 0)
2334                                 return true;
2335
2336                         Type[] method_args = method.GetGenericArguments ();
2337                         Type[] infered_types = new Type [method_args.Length];
2338
2339                         //
2340                         // If we have come this far, the case which
2341                         // remains is when the number of parameters is
2342                         // less than or equal to the argument count.
2343                         //
2344                         for (int i = 0; i < pd_count - 1; ++i) {
2345                                 Argument a = (Argument) arguments [i];
2346
2347                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2348                                         continue;
2349
2350                                 Type pt = pd.ParameterType (i);
2351                                 Type at = a.Type;
2352
2353                                 if (!InferType (pt, at, infered_types))
2354                                         return false;
2355                         }
2356
2357                         Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2358
2359                         for (int i = pd_count - 1; i < arg_count; i++) {
2360                                 Argument a = (Argument) arguments [i];
2361
2362                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2363                                         continue;
2364
2365                                 if (!InferType (element_type, a.Type, infered_types))
2366                                         return false;
2367                         }
2368
2369                         for (int i = 0; i < infered_types.Length; i++)
2370                                 if (infered_types [i] == null)
2371                                         return false;
2372
2373                         method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2374                         return true;
2375                 }
2376
2377                 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2378                                                 Type[] infered_types)
2379                 {
2380                         if (infered_types == null)
2381                                 return false;
2382
2383                         for (int i = 0; i < arg_types.Length; i++) {
2384                                 if (arg_types [i] == null)
2385                                         continue;
2386
2387                                 if (!InferType (param_types [i], arg_types [i], infered_types))
2388                                         return false;
2389                         }
2390
2391                         for (int i = 0; i < infered_types.Length; i++)
2392                                 if (infered_types [i] == null)
2393                                         return false;
2394
2395                         return true;
2396                 }
2397
2398                 /// <summary>
2399                 ///   Type inference.  Try to infer the type arguments from `method',
2400                 ///   which is invoked with the arguments `arguments'.  This is used
2401                 ///   when resolving an Invocation or a DelegateInvocation and the user
2402                 ///   did not explicitly specify type arguments.
2403                 /// </summary>
2404                 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2405                                                        ref MethodBase method)
2406                 {
2407                         if (!TypeManager.IsGenericMethod (method))
2408                                 return true;
2409
2410                         int arg_count;
2411                         if (arguments != null)
2412                                 arg_count = arguments.Count;
2413                         else
2414                                 arg_count = 0;
2415
2416                         ParameterData pd = TypeManager.GetParameterData (method);
2417                         if (arg_count != pd.Count)
2418                                 return false;
2419
2420                         Type[] method_args = method.GetGenericArguments ();
2421
2422                         bool is_open = false;
2423                         for (int i = 0; i < method_args.Length; i++) {
2424                                 if (method_args [i].IsGenericParameter) {
2425                                         is_open = true;
2426                                         break;
2427                                 }
2428                         }
2429                         if (!is_open)
2430                                 return true;
2431
2432                         Type[] infered_types = new Type [method_args.Length];
2433
2434                         Type[] param_types = new Type [pd.Count];
2435                         Type[] arg_types = new Type [pd.Count];
2436
2437                         for (int i = 0; i < arg_count; i++) {
2438                                 param_types [i] = pd.ParameterType (i);
2439
2440                                 Argument a = (Argument) arguments [i];
2441                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2442                                     (a.Expr is AnonymousMethod))
2443                                         continue;
2444
2445                                 arg_types [i] = a.Type;
2446                         }
2447
2448                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2449                                 return false;
2450
2451                         method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2452                         return true;
2453                 }
2454
2455                 /// <summary>
2456                 ///   Type inference.
2457                 /// </summary>
2458                 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2459                                                        ref MethodBase method)
2460                 {
2461                         if (!TypeManager.IsGenericMethod (method))
2462                                 return true;
2463
2464                         ParameterData pd = TypeManager.GetParameterData (method);
2465                         if (apd.Count != pd.Count)
2466                                 return false;
2467
2468                         Type[] method_args = method.GetGenericArguments ();
2469                         Type[] infered_types = new Type [method_args.Length];
2470
2471                         Type[] param_types = new Type [pd.Count];
2472                         Type[] arg_types = new Type [pd.Count];
2473
2474                         for (int i = 0; i < apd.Count; i++) {
2475                                 param_types [i] = pd.ParameterType (i);
2476                                 arg_types [i] = apd.ParameterType (i);
2477                         }
2478
2479                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2480                                 return false;
2481
2482                         method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2483                         return true;
2484                 }
2485
2486                 public static bool IsNullableType (Type t)
2487                 {
2488                         if (!t.IsGenericInstance)
2489                                 return false;
2490
2491                         Type gt = t.GetGenericTypeDefinition ();
2492                         return gt == generic_nullable_type;
2493                 }
2494         }
2495
2496         public abstract class Nullable
2497         {
2498                 protected sealed class NullableInfo
2499                 {
2500                         public readonly Type Type;
2501                         public readonly Type UnderlyingType;
2502                         public readonly MethodInfo HasValue;
2503                         public readonly MethodInfo Value;
2504                         public readonly ConstructorInfo Constructor;
2505
2506                         public NullableInfo (Type type)
2507                         {
2508                                 Type = type;
2509                                 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2510
2511                                 PropertyInfo has_value_pi = type.GetProperty ("HasValue");
2512                                 PropertyInfo value_pi = type.GetProperty ("Value");
2513
2514                                 HasValue = has_value_pi.GetGetMethod (false);
2515                                 Value = value_pi.GetGetMethod (false);
2516                                 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2517                         }
2518                 }
2519
2520                 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2521                 {
2522                         Expression expr;
2523                         NullableInfo info;
2524
2525                         LocalTemporary temp;
2526                         bool has_temp;
2527
2528                         public Unwrap (Expression expr, Location loc)
2529                         {
2530                                 this.expr = expr;
2531                                 this.loc = loc;
2532                         }
2533
2534                         public override Expression DoResolve (EmitContext ec)
2535                         {
2536                                 expr = expr.Resolve (ec);
2537                                 if (expr == null)
2538                                         return null;
2539
2540                                 if (!(expr is IMemoryLocation))
2541                                         temp = new LocalTemporary (ec, expr.Type);
2542
2543                                 info = new NullableInfo (expr.Type);
2544                                 type = info.UnderlyingType;
2545                                 eclass = expr.eclass;
2546                                 return this;
2547                         }
2548
2549                         public override void Emit (EmitContext ec)
2550                         {
2551                                 AddressOf (ec, AddressOp.LoadStore);
2552                                 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2553                         }
2554
2555                         public void EmitCheck (EmitContext ec)
2556                         {
2557                                 AddressOf (ec, AddressOp.LoadStore);
2558                                 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2559                         }
2560
2561                         void create_temp (EmitContext ec)
2562                         {
2563                                 if ((temp != null) && !has_temp) {
2564                                         expr.Emit (ec);
2565                                         temp.Store (ec);
2566                                         has_temp = true;
2567                                 }
2568                         }
2569
2570                         public void AddressOf (EmitContext ec, AddressOp mode)
2571                         {
2572                                 create_temp (ec);
2573                                 if (temp != null)
2574                                         temp.AddressOf (ec, AddressOp.LoadStore);
2575                                 else
2576                                         ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2577                         }
2578
2579                         public void Emit (EmitContext ec, bool leave_copy)
2580                         {
2581                                 create_temp (ec);
2582                                 if (leave_copy) {
2583                                         if (temp != null)
2584                                                 temp.Emit (ec);
2585                                         else
2586                                                 expr.Emit (ec);
2587                                 }
2588
2589                                 Emit (ec);
2590                         }
2591
2592                         public void EmitAssign (EmitContext ec, Expression source,
2593                                                 bool leave_copy, bool prepare_for_load)
2594                         {
2595                                 source.Emit (ec);
2596                                 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2597
2598                                 if (leave_copy)
2599                                         ec.ig.Emit (OpCodes.Dup);
2600
2601                                 Expression empty = new EmptyExpression (expr.Type);
2602                                 ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
2603                         }
2604                 }
2605
2606                 protected class Wrap : Expression
2607                 {
2608                         Expression expr;
2609                         NullableInfo info;
2610
2611                         public Wrap (Expression expr, Location loc)
2612                         {
2613                                 this.expr = expr;
2614                                 this.loc = loc;
2615                         }
2616
2617                         public override Expression DoResolve (EmitContext ec)
2618                         {
2619                                 expr = expr.Resolve (ec);
2620                                 if (expr == null)
2621                                         return null;
2622
2623                                 TypeExpr target_type = new NullableType (expr.Type, loc);
2624                                 target_type = target_type.ResolveAsTypeTerminal (ec);
2625                                 if (target_type == null)
2626                                         return null;
2627
2628                                 type = target_type.Type;
2629                                 info = new NullableInfo (type);
2630                                 eclass = ExprClass.Value;
2631                                 return this;
2632                         }
2633
2634                         public override void Emit (EmitContext ec)
2635                         {
2636                                 expr.Emit (ec);
2637                                 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2638                         }
2639                 }
2640
2641                 public class NullableLiteral : Expression, IMemoryLocation {
2642                         public NullableLiteral (Type target_type, Location loc)
2643                         {
2644                                 this.type = target_type;
2645                                 this.loc = loc;
2646
2647                                 eclass = ExprClass.Value;
2648                         }
2649                 
2650                         public override Expression DoResolve (EmitContext ec)
2651                         {
2652                                 return this;
2653                         }
2654
2655                         public override void Emit (EmitContext ec)
2656                         {
2657                                 LocalTemporary value_target = new LocalTemporary (ec, type);
2658
2659                                 value_target.AddressOf (ec, AddressOp.Store);
2660                                 ec.ig.Emit (OpCodes.Initobj, type);
2661                                 value_target.Emit (ec);
2662                         }
2663
2664                         public void AddressOf (EmitContext ec, AddressOp Mode)
2665                         {
2666                                 LocalTemporary value_target = new LocalTemporary (ec, type);
2667                                         
2668                                 value_target.AddressOf (ec, AddressOp.Store);
2669                                 ec.ig.Emit (OpCodes.Initobj, type);
2670                                 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2671                         }
2672                 }
2673
2674                 public abstract class Lifted : Expression, IMemoryLocation
2675                 {
2676                         Expression expr, underlying, wrap, null_value;
2677                         Unwrap unwrap;
2678
2679                         protected Lifted (Expression expr, Location loc)
2680                         {
2681                                 this.expr = expr;
2682                                 this.loc = loc;
2683                         }
2684
2685                         public override Expression DoResolve (EmitContext ec)
2686                         {
2687                                 expr = expr.Resolve (ec);
2688                                 if (expr == null)
2689                                         return null;
2690
2691                                 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2692                                 if (unwrap == null)
2693                                         return null;
2694
2695                                 underlying = ResolveUnderlying (unwrap, ec);
2696                                 if (underlying == null)
2697                                         return null;
2698
2699                                 wrap = new Wrap (underlying, loc).Resolve (ec);
2700                                 if (wrap == null)
2701                                         return null;
2702
2703                                 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2704                                 if (null_value == null)
2705                                         return null;
2706
2707                                 type = wrap.Type;
2708                                 eclass = ExprClass.Value;
2709                                 return this;
2710                         }
2711
2712                         protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2713
2714                         public override void Emit (EmitContext ec)
2715                         {
2716                                 ILGenerator ig = ec.ig;
2717                                 Label is_null_label = ig.DefineLabel ();
2718                                 Label end_label = ig.DefineLabel ();
2719
2720                                 unwrap.EmitCheck (ec);
2721                                 ig.Emit (OpCodes.Brfalse, is_null_label);
2722
2723                                 wrap.Emit (ec);
2724                                 ig.Emit (OpCodes.Br, end_label);
2725
2726                                 ig.MarkLabel (is_null_label);
2727                                 null_value.Emit (ec);
2728
2729                                 ig.MarkLabel (end_label);
2730                         }
2731
2732                         public void AddressOf (EmitContext ec, AddressOp mode)
2733                         {
2734                                 unwrap.AddressOf (ec, mode);
2735                         }
2736                 }
2737
2738                 public class LiftedConversion : Lifted
2739                 {
2740                         public readonly bool IsUser;
2741                         public readonly bool IsExplicit;
2742                         public readonly Type TargetType;
2743
2744                         public LiftedConversion (Expression expr, Type target_type, bool is_user,
2745                                                  bool is_explicit, Location loc)
2746                                 : base (expr, loc)
2747                         {
2748                                 this.IsUser = is_user;
2749                                 this.IsExplicit = is_explicit;
2750                                 this.TargetType = target_type;
2751                         }
2752
2753                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2754                         {
2755                                 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2756
2757                                 if (IsUser) {
2758                                         return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2759                                 } else {
2760                                         if (IsExplicit)
2761                                                 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2762                                         else
2763                                                 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2764                                 }
2765                         }
2766                 }
2767
2768                 public class LiftedUnaryOperator : Lifted
2769                 {
2770                         public readonly Unary.Operator Oper;
2771
2772                         public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2773                                 : base (expr, loc)
2774                         {
2775                                 this.Oper = op;
2776                         }
2777
2778                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2779                         {
2780                                 return new Unary (Oper, unwrap, loc);
2781                         }
2782                 }
2783
2784                 public class LiftedConditional : Lifted
2785                 {
2786                         Expression true_expr, false_expr;
2787
2788                         public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2789                                                   Location loc)
2790                                 : base (expr, loc)
2791                         {
2792                                 this.true_expr = true_expr;
2793                                 this.false_expr = false_expr;
2794                         }
2795
2796                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2797                         {
2798                                 return new Conditional (unwrap, true_expr, false_expr);
2799                         }
2800                 }
2801
2802                 public class LiftedBinaryOperator : Expression
2803                 {
2804                         public readonly Binary.Operator Oper;
2805
2806                         Expression left, right, underlying, null_value, bool_wrap;
2807                         Unwrap left_unwrap, right_unwrap;
2808                         bool is_equality, is_comparision, is_boolean;
2809
2810                         public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2811                                                      Location loc)
2812                         {
2813                                 this.Oper = op;
2814                                 this.left = left;
2815                                 this.right = right;
2816                                 this.loc = loc;
2817                         }
2818
2819                         public override Expression DoResolve (EmitContext ec)
2820                         {
2821                                 if (TypeManager.IsNullableType (left.Type)) {
2822                                         left_unwrap = new Unwrap (left, loc);
2823                                         left = left_unwrap.Resolve (ec);
2824                                         if (left == null)
2825                                                 return null;
2826                                 }
2827
2828                                 if (TypeManager.IsNullableType (right.Type)) {
2829                                         right_unwrap = new Unwrap (right, loc);
2830                                         right = right_unwrap.Resolve (ec);
2831                                         if (right == null)
2832                                                 return null;
2833                                 }
2834
2835                                 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
2836                                      (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
2837                                     ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2838                                         Expression empty = new EmptyExpression (TypeManager.bool_type);
2839                                         bool_wrap = new Wrap (empty, loc).Resolve (ec);
2840                                         null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2841
2842                                         type = bool_wrap.Type;
2843                                         is_boolean = true;
2844                                 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2845                                         if (!(left is NullLiteral) && !(right is NullLiteral)) {
2846                                                 underlying = new Binary (Oper, left, right).Resolve (ec);
2847                                                 if (underlying == null)
2848                                                         return null;
2849                                         }
2850
2851                                         type = TypeManager.bool_type;
2852                                         is_equality = true;
2853                                 } else if ((Oper == Binary.Operator.LessThan) ||
2854                                            (Oper == Binary.Operator.GreaterThan) ||
2855                                            (Oper == Binary.Operator.LessThanOrEqual) ||
2856                                            (Oper == Binary.Operator.GreaterThanOrEqual)) {
2857                                         underlying = new Binary (Oper, left, right).Resolve (ec);
2858                                         if (underlying == null)
2859                                                 return null;
2860
2861                                         type = TypeManager.bool_type;
2862                                         is_comparision = true;
2863                                 } else {
2864                                         underlying = new Binary (Oper, left, right).Resolve (ec);
2865                                         if (underlying == null)
2866                                                 return null;
2867
2868                                         underlying = new Wrap (underlying, loc).Resolve (ec);
2869                                         if (underlying == null)
2870                                                 return null;
2871
2872                                         type = underlying.Type;
2873                                         null_value = new NullableLiteral (type, loc).Resolve (ec);
2874                                 }
2875
2876                                 eclass = ExprClass.Value;
2877                                 return this;
2878                         }
2879
2880                         void EmitBoolean (EmitContext ec)
2881                         {
2882                                 ILGenerator ig = ec.ig;
2883
2884                                 Label left_is_null_label = ig.DefineLabel ();
2885                                 Label right_is_null_label = ig.DefineLabel ();
2886                                 Label is_null_label = ig.DefineLabel ();
2887                                 Label wrap_label = ig.DefineLabel ();
2888                                 Label end_label = ig.DefineLabel ();
2889
2890                                 if (left_unwrap != null) {
2891                                         left_unwrap.EmitCheck (ec);
2892                                         ig.Emit (OpCodes.Brfalse, left_is_null_label);
2893                                 }
2894
2895                                 left.Emit (ec);
2896                                 ig.Emit (OpCodes.Dup);
2897                                 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2898                                         ig.Emit (OpCodes.Brtrue, wrap_label);
2899                                 else
2900                                         ig.Emit (OpCodes.Brfalse, wrap_label);
2901
2902                                 if (right_unwrap != null) {
2903                                         right_unwrap.EmitCheck (ec);
2904                                         ig.Emit (OpCodes.Brfalse, right_is_null_label);
2905                                 }
2906
2907                                 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2908                                         ig.Emit (OpCodes.Pop);
2909
2910                                 right.Emit (ec);
2911                                 if (Oper == Binary.Operator.BitwiseOr)
2912                                         ig.Emit (OpCodes.Or);
2913                                 else if (Oper == Binary.Operator.BitwiseAnd)
2914                                         ig.Emit (OpCodes.And);
2915                                 ig.Emit (OpCodes.Br, wrap_label);
2916
2917                                 ig.MarkLabel (left_is_null_label);
2918                                 if (right_unwrap != null) {
2919                                         right_unwrap.EmitCheck (ec);
2920                                         ig.Emit (OpCodes.Brfalse, is_null_label);
2921                                 }
2922
2923                                 right.Emit (ec);
2924                                 ig.Emit (OpCodes.Dup);
2925                                 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2926                                         ig.Emit (OpCodes.Brtrue, wrap_label);
2927                                 else
2928                                         ig.Emit (OpCodes.Brfalse, wrap_label);
2929
2930                                 ig.MarkLabel (right_is_null_label);
2931                                 ig.Emit (OpCodes.Pop);
2932                                 ig.MarkLabel (is_null_label);
2933                                 null_value.Emit (ec);
2934                                 ig.Emit (OpCodes.Br, end_label);
2935
2936                                 ig.MarkLabel (wrap_label);
2937                                 ig.Emit (OpCodes.Nop);
2938                                 bool_wrap.Emit (ec);
2939                                 ig.Emit (OpCodes.Nop);
2940
2941                                 ig.MarkLabel (end_label);
2942                         }
2943
2944                         void EmitEquality (EmitContext ec)
2945                         {
2946                                 ILGenerator ig = ec.ig;
2947
2948                                 Label left_not_null_label = ig.DefineLabel ();
2949                                 Label false_label = ig.DefineLabel ();
2950                                 Label true_label = ig.DefineLabel ();
2951                                 Label end_label = ig.DefineLabel ();
2952
2953                                 bool false_label_used = false;
2954                                 bool true_label_used = false;
2955
2956                                 if (left_unwrap != null) {
2957                                         left_unwrap.EmitCheck (ec);
2958                                         if (right is NullLiteral) {
2959                                                 if (Oper == Binary.Operator.Equality) {
2960                                                         true_label_used = true;
2961                                                         ig.Emit (OpCodes.Brfalse, true_label);
2962                                                 } else {
2963                                                         false_label_used = true;
2964                                                         ig.Emit (OpCodes.Brfalse, false_label);
2965                                                 }
2966                                         } else if (right_unwrap != null) {
2967                                                 ig.Emit (OpCodes.Dup);
2968                                                 ig.Emit (OpCodes.Brtrue, left_not_null_label);
2969                                                 right_unwrap.EmitCheck (ec);
2970                                                 ig.Emit (OpCodes.Ceq);
2971                                                 if (Oper == Binary.Operator.Inequality) {
2972                                                         ig.Emit (OpCodes.Ldc_I4_0);
2973                                                         ig.Emit (OpCodes.Ceq);
2974                                                 }
2975                                                 ig.Emit (OpCodes.Br, end_label);
2976
2977                                                 ig.MarkLabel (left_not_null_label);
2978                                                 ig.Emit (OpCodes.Pop);
2979                                         } else {
2980                                                 if (Oper == Binary.Operator.Equality) {
2981                                                         false_label_used = true;
2982                                                         ig.Emit (OpCodes.Brfalse, false_label);
2983                                                 } else {
2984                                                         true_label_used = true;
2985                                                         ig.Emit (OpCodes.Brfalse, true_label);
2986                                                 }
2987                                         }
2988                                 }
2989
2990                                 if (right_unwrap != null) {
2991                                         right_unwrap.EmitCheck (ec);
2992                                         if (left is NullLiteral) {
2993                                                 if (Oper == Binary.Operator.Equality) {
2994                                                         true_label_used = true;
2995                                                         ig.Emit (OpCodes.Brfalse, true_label);
2996                                                 } else {
2997                                                         false_label_used = true;
2998                                                         ig.Emit (OpCodes.Brfalse, false_label);
2999                                                 }
3000                                         } else {
3001                                                 if (Oper == Binary.Operator.Equality) {
3002                                                         false_label_used = true;
3003                                                         ig.Emit (OpCodes.Brfalse, false_label);
3004                                                 } else {
3005                                                         true_label_used = true;
3006                                                         ig.Emit (OpCodes.Brfalse, true_label);
3007                                                 }
3008                                         }
3009                                 }
3010
3011                                 bool left_is_null = left is NullLiteral;
3012                                 bool right_is_null = right is NullLiteral;
3013                                 if (left_is_null || right_is_null) {
3014                                         if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
3015                                             ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
3016                                                 true_label_used = true;
3017                                                 ig.Emit (OpCodes.Br, true_label);
3018                                         } else {
3019                                                 false_label_used = true;
3020                                                 ig.Emit (OpCodes.Br, false_label);
3021                                         }
3022                                 } else {
3023                                         underlying.Emit (ec);
3024                                         ig.Emit (OpCodes.Br, end_label);
3025                                 }
3026
3027                                 ig.MarkLabel (false_label);
3028                                 if (false_label_used) {
3029                                         ig.Emit (OpCodes.Ldc_I4_0);
3030                                         if (true_label_used)
3031                                                 ig.Emit (OpCodes.Br, end_label);
3032                                 }
3033
3034                                 ig.MarkLabel (true_label);
3035                                 if (true_label_used)
3036                                         ig.Emit (OpCodes.Ldc_I4_1);
3037
3038                                 ig.MarkLabel (end_label);
3039                         }
3040
3041                         void EmitComparision (EmitContext ec)
3042                         {
3043                                 ILGenerator ig = ec.ig;
3044
3045                                 Label is_null_label = ig.DefineLabel ();
3046                                 Label end_label = ig.DefineLabel ();
3047
3048                                 if (left_unwrap != null) {
3049                                         left_unwrap.EmitCheck (ec);
3050                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3051                                 }
3052
3053                                 if (right_unwrap != null) {
3054                                         right_unwrap.EmitCheck (ec);
3055                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3056                                 }
3057
3058                                 underlying.Emit (ec);
3059                                 ig.Emit (OpCodes.Br, end_label);
3060
3061                                 ig.MarkLabel (is_null_label);
3062                                 ig.Emit (OpCodes.Ldc_I4_0);
3063
3064                                 ig.MarkLabel (end_label);
3065                         }
3066
3067                         public override void Emit (EmitContext ec)
3068                         {
3069                                 if (is_boolean) {
3070                                         EmitBoolean (ec);
3071                                         return;
3072                                 } else if (is_equality) {
3073                                         EmitEquality (ec);
3074                                         return;
3075                                 } else if (is_comparision) {
3076                                         EmitComparision (ec);
3077                                         return;
3078                                 }
3079
3080                                 ILGenerator ig = ec.ig;
3081
3082                                 Label is_null_label = ig.DefineLabel ();
3083                                 Label end_label = ig.DefineLabel ();
3084
3085                                 if (left_unwrap != null) {
3086                                         left_unwrap.EmitCheck (ec);
3087                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3088                                 }
3089
3090                                 if (right_unwrap != null) {
3091                                         right_unwrap.EmitCheck (ec);
3092                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3093                                 }
3094
3095                                 underlying.Emit (ec);
3096                                 ig.Emit (OpCodes.Br, end_label);
3097
3098                                 ig.MarkLabel (is_null_label);
3099                                 null_value.Emit (ec);
3100
3101                                 ig.MarkLabel (end_label);
3102                         }
3103                 }
3104
3105                 public class OperatorTrueOrFalse : Expression
3106                 {
3107                         public readonly bool IsTrue;
3108
3109                         Expression expr;
3110                         Unwrap unwrap;
3111
3112                         public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3113                         {
3114                                 this.IsTrue = is_true;
3115                                 this.expr = expr;
3116                                 this.loc = loc;
3117                         }
3118
3119                         public override Expression DoResolve (EmitContext ec)
3120                         {
3121                                 unwrap = new Unwrap (expr, loc);
3122                                 expr = unwrap.Resolve (ec);
3123                                 if (expr == null)
3124                                         return null;
3125
3126                                 if (unwrap.Type != TypeManager.bool_type)
3127                                         return null;
3128
3129                                 type = TypeManager.bool_type;
3130                                 eclass = ExprClass.Value;
3131                                 return this;
3132                         }
3133
3134                         public override void Emit (EmitContext ec)
3135                         {
3136                                 ILGenerator ig = ec.ig;
3137
3138                                 Label is_null_label = ig.DefineLabel ();
3139                                 Label end_label = ig.DefineLabel ();
3140
3141                                 unwrap.EmitCheck (ec);
3142                                 ig.Emit (OpCodes.Brfalse, is_null_label);
3143
3144                                 unwrap.Emit (ec);
3145                                 if (!IsTrue) {
3146                                         ig.Emit (OpCodes.Ldc_I4_0);
3147                                         ig.Emit (OpCodes.Ceq);
3148                                 }
3149                                 ig.Emit (OpCodes.Br, end_label);
3150
3151                                 ig.MarkLabel (is_null_label);
3152                                 ig.Emit (OpCodes.Ldc_I4_0);
3153
3154                                 ig.MarkLabel (end_label);
3155                         }
3156                 }
3157
3158                 public class NullCoalescingOperator : Expression
3159                 {
3160                         Expression left, right;
3161                         Expression expr;
3162                         Unwrap unwrap;
3163
3164                         public NullCoalescingOperator (Expression left, Expression right, Location loc)
3165                         {
3166                                 this.left = left;
3167                                 this.right = right;
3168                                 this.loc = loc;
3169
3170                                 eclass = ExprClass.Value;
3171                         }
3172
3173                         public override Expression DoResolve (EmitContext ec)
3174                         {
3175                                 if (type != null)
3176                                         return this;
3177
3178                                 left = left.Resolve (ec);
3179                                 if (left == null)
3180                                         return null;
3181
3182                                 right = right.Resolve (ec);
3183                                 if (right == null)
3184                                         return null;
3185
3186                                 Type ltype = left.Type, rtype = right.Type;
3187
3188                                 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3189                                         Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3190                                         return null;
3191                                 }
3192
3193                                 if (TypeManager.IsNullableType (ltype)) {
3194                                         NullableInfo info = new NullableInfo (ltype);
3195
3196                                         unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
3197                                         if (unwrap == null)
3198                                                 return null;
3199
3200                                         expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3201                                         if (expr != null) {
3202                                                 left = unwrap;
3203                                                 type = expr.Type;
3204                                                 return this;
3205                                         }
3206                                 }
3207
3208                                 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3209                                 if (expr != null) {
3210                                         type = expr.Type;
3211                                         return this;
3212                                 }
3213
3214                                 if (unwrap != null) {
3215                                         expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3216                                         if (expr != null) {
3217                                                 left = expr;
3218                                                 expr = right;
3219                                                 type = expr.Type;
3220                                                 return this;
3221                                         }
3222                                 }
3223
3224                                 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3225                                 return null;
3226                         }
3227
3228                         public override void Emit (EmitContext ec)
3229                         {
3230                                 ILGenerator ig = ec.ig;
3231
3232                                 Label is_null_label = ig.DefineLabel ();
3233                                 Label end_label = ig.DefineLabel ();
3234
3235                                 if (unwrap != null) {
3236                                         unwrap.EmitCheck (ec);
3237                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3238
3239                                         left.Emit (ec);
3240                                         ig.Emit (OpCodes.Br, end_label);
3241
3242                                         ig.MarkLabel (is_null_label);
3243                                         expr.Emit (ec);
3244
3245                                         ig.MarkLabel (end_label);
3246                                 } else {
3247                                         left.Emit (ec);
3248                                         ig.Emit (OpCodes.Dup);
3249                                         ig.Emit (OpCodes.Brtrue, end_label);
3250
3251                                         ig.MarkLabel (is_null_label);
3252
3253                                         ig.Emit (OpCodes.Pop);
3254                                         expr.Emit (ec);
3255
3256                                         ig.MarkLabel (end_label);
3257                                 }
3258                         }
3259                 }
3260
3261                 public class LiftedUnaryMutator : ExpressionStatement
3262                 {
3263                         public readonly UnaryMutator.Mode Mode;
3264                         Expression expr, null_value;
3265                         UnaryMutator underlying;
3266                         Unwrap unwrap;
3267
3268                         public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3269                         {
3270                                 this.expr = expr;
3271                                 this.Mode = mode;
3272                                 this.loc = loc;
3273
3274                                 eclass = ExprClass.Value;
3275                         }
3276
3277                         public override Expression DoResolve (EmitContext ec)
3278                         {
3279                                 expr = expr.Resolve (ec);
3280                                 if (expr == null)
3281                                         return null;
3282
3283                                 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3284                                 if (unwrap == null)
3285                                         return null;
3286
3287                                 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3288                                 if (underlying == null)
3289                                         return null;
3290
3291                                 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3292                                 if (null_value == null)
3293                                         return null;
3294
3295                                 type = expr.Type;
3296                                 return this;
3297                         }
3298
3299                         void DoEmit (EmitContext ec, bool is_expr)
3300                         {
3301                                 ILGenerator ig = ec.ig;
3302                                 Label is_null_label = ig.DefineLabel ();
3303                                 Label end_label = ig.DefineLabel ();
3304
3305                                 unwrap.EmitCheck (ec);
3306                                 ig.Emit (OpCodes.Brfalse, is_null_label);
3307
3308                                 if (is_expr)
3309                                         underlying.Emit (ec);
3310                                 else
3311                                         underlying.EmitStatement (ec);
3312                                 ig.Emit (OpCodes.Br, end_label);
3313
3314                                 ig.MarkLabel (is_null_label);
3315                                 if (is_expr)
3316                                         null_value.Emit (ec);
3317
3318                                 ig.MarkLabel (end_label);
3319                         }
3320
3321                         public override void Emit (EmitContext ec)
3322                         {
3323                                 DoEmit (ec, true);
3324                         }
3325
3326                         public override void EmitStatement (EmitContext ec)
3327                         {
3328                                 DoEmit (ec, false);
3329                         }
3330                 }
3331         }
3332 }