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