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