2006-03-09 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.IsGenericType) {
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                         atype = TypeManager.DropGenericTypeArguments (atype);
1603
1604                         if (atype is TypeBuilder) {
1605                                 if (atype.IsAbstract)
1606                                         return false;
1607
1608                                 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1609                                 foreach (Constructor c in tc.InstanceConstructors) {
1610                                         if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1611                                                 continue;
1612                                         if ((c.Parameters.FixedParameters != null) &&
1613                                             (c.Parameters.FixedParameters.Length != 0))
1614                                                 continue;
1615                                         if (c.Parameters.HasArglist || c.Parameters.HasParams)
1616                                                 continue;
1617
1618                                         return true;
1619                                 }
1620                         }
1621
1622                         MethodGroupExpr mg = Expression.MemberLookup (
1623                                 ec, atype, ".ctor", MemberTypes.Constructor,
1624                                 BindingFlags.Public | BindingFlags.Instance |
1625                                 BindingFlags.DeclaredOnly, loc)
1626                                 as MethodGroupExpr;
1627
1628                         if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
1629                                 foreach (MethodBase mb in mg.Methods) {
1630                                         ParameterData pd = TypeManager.GetParameterData (mb);
1631                                         if (pd.Count == 0)
1632                                                 return true;
1633                                 }
1634                         }
1635
1636                         return false;
1637                 }
1638
1639                 protected abstract string GetSignatureForError ();
1640                 protected abstract void Report_SymbolRelatedToPreviousError ();
1641
1642                 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1643                 {
1644                         Report_SymbolRelatedToPreviousError ();
1645                         Report.SymbolRelatedToPreviousError (atype);
1646                         Report.Error (309, loc, 
1647                                       "The type `{0}' must be convertible to `{1}' in order to " +
1648                                       "use it as parameter `{2}' in the generic type or method `{3}'",
1649                                       TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1650                                       TypeManager.CSharpName (ptype), GetSignatureForError ());
1651                 }
1652
1653                 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1654                                                      MethodBase instantiated, Location loc)
1655                 {
1656                         MethodConstraintChecker checker = new MethodConstraintChecker (
1657                                 definition, definition.GetGenericArguments (),
1658                                 instantiated.GetGenericArguments (), loc);
1659
1660                         return checker.CheckConstraints (ec);
1661                 }
1662
1663                 public static bool CheckConstraints (EmitContext ec, Type gt, Type[] gen_params,
1664                                                      Type[] atypes, Location loc)
1665                 {
1666                         TypeConstraintChecker checker = new TypeConstraintChecker (
1667                                 gt, gen_params, atypes, loc);
1668
1669                         return checker.CheckConstraints (ec);
1670                 }
1671
1672                 protected class MethodConstraintChecker : ConstraintChecker
1673                 {
1674                         MethodBase definition;
1675
1676                         public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1677                                                         Type[] atypes, Location loc)
1678                                 : base (gen_params, atypes, loc)
1679                         {
1680                                 this.definition = definition;
1681                         }
1682
1683                         protected override string GetSignatureForError ()
1684                         {
1685                                 return TypeManager.CSharpSignature (definition);
1686                         }
1687
1688                         protected override void Report_SymbolRelatedToPreviousError ()
1689                         {
1690                                 Report.SymbolRelatedToPreviousError (definition);
1691                         }
1692                 }
1693
1694                 protected class TypeConstraintChecker : ConstraintChecker
1695                 {
1696                         Type gt;
1697
1698                         public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1699                                                       Location loc)
1700                                 : base (gen_params, atypes, loc)
1701                         {
1702                                 this.gt = gt;
1703                         }
1704
1705                         protected override string GetSignatureForError ()
1706                         {
1707                                 return TypeManager.CSharpName (gt);
1708                         }
1709
1710                         protected override void Report_SymbolRelatedToPreviousError ()
1711                         {
1712                                 Report.SymbolRelatedToPreviousError (gt);
1713                         }
1714                 }
1715         }
1716
1717         /// <summary>
1718         ///   A generic method definition.
1719         /// </summary>
1720         public class GenericMethod : DeclSpace
1721         {
1722                 Expression return_type;
1723                 Parameters parameters;
1724
1725                 public GenericMethod (NamespaceEntry ns, TypeContainer parent, MemberName name,
1726                                       Expression return_type, Parameters parameters)
1727                         : base (ns, parent, name, null)
1728                 {
1729                         this.return_type = return_type;
1730                         this.parameters = parameters;
1731                 }
1732
1733                 public override TypeBuilder DefineType ()
1734                 {
1735                         throw new Exception ();
1736                 }
1737
1738                 public override bool Define ()
1739                 {
1740                         ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
1741
1742                         for (int i = 0; i < TypeParameters.Length; i++)
1743                                 if (!TypeParameters [i].Resolve (this))
1744                                         return false;
1745
1746                         return true;
1747                 }
1748
1749                 /// <summary>
1750                 ///   Define and resolve the type parameters.
1751                 ///   We're called from Method.Define().
1752                 /// </summary>
1753                 public bool Define (MethodBuilder mb)
1754                 {
1755                         GenericTypeParameterBuilder[] gen_params;
1756                         TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1757                         string[] snames = new string [names.Length];
1758                         for (int i = 0; i < names.Length; i++)
1759                                 snames [i] = names [i].Name;
1760                         gen_params = mb.DefineGenericParameters (snames);
1761                         for (int i = 0; i < TypeParameters.Length; i++)
1762                                 TypeParameters [i].Define (gen_params [i]);
1763
1764                         if (!Define ())
1765                                 return false;
1766
1767                         for (int i = 0; i < TypeParameters.Length; i++) {
1768                                 if (!TypeParameters [i].ResolveType (ec))
1769                                         return false;
1770                         }
1771
1772                         return true;
1773                 }
1774
1775                 /// <summary>
1776                 ///   We're called from MethodData.Define() after creating the MethodBuilder.
1777                 /// </summary>
1778                 public bool DefineType (EmitContext ec, MethodBuilder mb,
1779                                         MethodInfo implementing, bool is_override)
1780                 {
1781                         for (int i = 0; i < TypeParameters.Length; i++)
1782                                 if (!TypeParameters [i].DefineType (
1783                                             ec, mb, implementing, is_override))
1784                                         return false;
1785
1786                         bool ok = true;
1787                         foreach (Parameter p in parameters.FixedParameters){
1788                                 if (!p.Resolve (ec))
1789                                         ok = false;
1790                         }
1791                         if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec) == null))
1792                                 ok = false;
1793
1794                         return ok;
1795                 }
1796
1797                 public void EmitAttributes (EmitContext ec)
1798                 {
1799                         for (int i = 0; i < TypeParameters.Length; i++)
1800                                 TypeParameters [i].EmitAttributes (ec);
1801
1802                         if (OptAttributes != null)
1803                                 OptAttributes.Emit (ec, this);
1804                 }
1805
1806                 public override bool DefineMembers ()
1807                 {
1808                         return true;
1809                 }
1810
1811                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1812                                                         MemberFilter filter, object criteria)
1813                 {
1814                         throw new Exception ();
1815                 }               
1816
1817                 public override MemberCache MemberCache {
1818                         get {
1819                                 return null;
1820                         }
1821                 }
1822
1823                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1824                 {
1825                         base.ApplyAttributeBuilder (a, cb);
1826                 }
1827
1828                 public override AttributeTargets AttributeTargets {
1829                         get {
1830                                 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1831                         }
1832                 }
1833
1834                 public override string DocCommentHeader {
1835                         get { return "M:"; }
1836                 }
1837         }
1838
1839         public class DefaultValueExpression : Expression
1840         {
1841                 Expression expr;
1842
1843                 public DefaultValueExpression (Expression expr, Location loc)
1844                 {
1845                         this.expr = expr;
1846                         this.loc = loc;
1847                 }
1848
1849                 public override Expression DoResolve (EmitContext ec)
1850                 {
1851                         TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1852                         if (texpr == null)
1853                                 return null;
1854
1855                         type = texpr.Type;
1856
1857                         eclass = ExprClass.Variable;
1858                         return this;
1859                 }
1860
1861                 public override void Emit (EmitContext ec)
1862                 {
1863                         if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
1864                                 LocalTemporary temp_storage = new LocalTemporary (ec, type);
1865
1866                                 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1867                                 ec.ig.Emit (OpCodes.Initobj, type);
1868                                 temp_storage.Emit (ec);
1869                         } else
1870                                 ec.ig.Emit (OpCodes.Ldnull);
1871                 }
1872         }
1873
1874         public class NullableType : TypeExpr
1875         {
1876                 Expression underlying;
1877
1878                 public NullableType (Expression underlying, Location l)
1879                 {
1880                         this.underlying = underlying;
1881                         loc = l;
1882
1883                         eclass = ExprClass.Type;
1884                 }
1885
1886                 public NullableType (Type type, Location loc)
1887                         : this (new TypeExpression (type, loc), loc)
1888                 { }
1889
1890                 public override string Name {
1891                         get { return underlying.ToString () + "?"; }
1892                 }
1893
1894                 public override string FullName {
1895                         get { return underlying.ToString () + "?"; }
1896                 }
1897
1898                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1899                 {
1900                         TypeArguments args = new TypeArguments (loc);
1901                         args.Add (underlying);
1902
1903                         ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1904                         return ctype.ResolveAsTypeTerminal (ec);
1905                 }
1906         }
1907
1908         public partial class TypeManager
1909         {
1910                 //
1911                 // A list of core types that the compiler requires or uses
1912                 //
1913                 static public Type activator_type;
1914                 static public Type generic_ienumerator_type;
1915                 static public Type generic_ienumerable_type;
1916                 static public Type generic_nullable_type;
1917
1918                 // <remarks>
1919                 //   Tracks the generic parameters.
1920                 // </remarks>
1921                 static PtrHashtable builder_to_type_param;
1922
1923                 //
1924                 // These methods are called by code generated by the compiler
1925                 //
1926                 static public MethodInfo activator_create_instance;
1927
1928                 static void InitGenerics ()
1929                 {
1930                         builder_to_type_param = new PtrHashtable ();
1931                 }
1932
1933                 static void CleanUpGenerics ()
1934                 {
1935                         builder_to_type_param = null;
1936                 }
1937
1938                 static void InitGenericCoreTypes ()
1939                 {
1940                         activator_type = CoreLookupType ("System", "Activator");
1941
1942                         generic_ienumerator_type = CoreLookupType (
1943                                 "System.Collections.Generic", "IEnumerator", 1);
1944                         generic_ienumerable_type = CoreLookupType (
1945                                 "System.Collections.Generic", "IEnumerable", 1);
1946                         generic_nullable_type = CoreLookupType (
1947                                 "System", "Nullable", 1);
1948                 }
1949
1950                 static void InitGenericCodeHelpers ()
1951                 {
1952                         // Activator
1953                         Type [] type_arg = { type_type };
1954                         activator_create_instance = GetMethod (
1955                                 activator_type, "CreateInstance", type_arg);
1956                 }
1957
1958                 static Type CoreLookupType (string ns, string name, int arity)
1959                 {
1960                         return CoreLookupType (ns, MemberName.MakeName (name, arity));
1961                 }
1962
1963                 public static void AddTypeParameter (Type t, TypeParameter tparam)
1964                 {
1965                         if (!builder_to_type_param.Contains (t))
1966                                 builder_to_type_param.Add (t, tparam);
1967                 }
1968
1969                 public static TypeContainer LookupGenericTypeContainer (Type t)
1970                 {
1971                         t = DropGenericTypeArguments (t);
1972                         return LookupTypeContainer (t);
1973                 }
1974
1975                 public static TypeParameter LookupTypeParameter (Type t)
1976                 {
1977                         return (TypeParameter) builder_to_type_param [t];
1978                 }
1979
1980                 public static GenericConstraints GetTypeParameterConstraints (Type t)
1981                 {
1982                         if (!t.IsGenericParameter)
1983                                 throw new InvalidOperationException ();
1984
1985                         TypeParameter tparam = LookupTypeParameter (t);
1986                         if (tparam != null)
1987                                 return tparam.GenericConstraints;
1988
1989                         return ReflectionConstraints.GetConstraints (t);
1990                 }
1991
1992                 public static bool HasGenericArguments (Type t)
1993                 {
1994                         return GetNumberOfTypeArguments (t) > 0;
1995                 }
1996
1997                 public static int GetNumberOfTypeArguments (Type t)
1998                 {
1999                         if (t.IsGenericParameter)
2000                                 return 0;
2001                         DeclSpace tc = LookupDeclSpace (t);
2002                         if (tc != null)
2003                                 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2004                         else
2005                                 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2006                 }
2007
2008                 public static Type[] GetTypeArguments (Type t)
2009                 {
2010                         DeclSpace tc = LookupDeclSpace (t);
2011                         if (tc != null) {
2012                                 if (!tc.IsGeneric)
2013                                         return Type.EmptyTypes;
2014
2015                                 TypeParameter[] tparam = tc.TypeParameters;
2016                                 Type[] ret = new Type [tparam.Length];
2017                                 for (int i = 0; i < tparam.Length; i++) {
2018                                         ret [i] = tparam [i].Type;
2019                                         if (ret [i] == null)
2020                                                 throw new InternalErrorException ();
2021                                 }
2022
2023                                 return ret;
2024                         } else
2025                                 return t.GetGenericArguments ();
2026                 }
2027
2028                 public static Type DropGenericTypeArguments (Type t)
2029                 {
2030                         if (!t.IsGenericType)
2031                                 return t;
2032                         // Micro-optimization: a generic typebuilder is always a generic type definition
2033                         if (t is TypeBuilder)
2034                                 return t;
2035                         return t.GetGenericTypeDefinition ();
2036                 }
2037
2038                 public static MethodBase DropGenericMethodArguments (MethodBase m)
2039                 {
2040                         if (m.IsGenericMethodDefinition)
2041                                 return m;
2042                         if (m.IsGenericMethod)
2043                                 return ((MethodInfo) m).GetGenericMethodDefinition ();
2044                         if (!m.DeclaringType.IsGenericType)
2045                                 return m;
2046
2047                         Type t = m.DeclaringType.GetGenericTypeDefinition ();
2048                         BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2049                                 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2050
2051                         if (m is ConstructorInfo) {
2052                                 foreach (ConstructorInfo c in t.GetConstructors (bf))
2053                                         if (c.MetadataToken == m.MetadataToken)
2054                                                 return c;
2055                         } else {
2056                                 foreach (MethodBase mb in t.GetMethods (bf))
2057                                         if (mb.MetadataToken == m.MetadataToken)
2058                                                 return mb;
2059                         }
2060
2061                         return m;
2062                 }
2063
2064                 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2065                 {
2066                         if (fi.DeclaringType.IsGenericTypeDefinition ||
2067                             !fi.DeclaringType.IsGenericType)
2068                                 return fi;
2069
2070                         Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2071                         BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2072                                 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2073
2074                         foreach (FieldInfo f in t.GetFields (bf))
2075                                 if (f.MetadataToken == fi.MetadataToken)
2076                                         return f;
2077
2078                         return fi;
2079                 }
2080
2081                 //
2082                 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
2083                 // For instance "string[]" -> "IEnumerable<string>".
2084                 //
2085                 public static bool IsIEnumerable (Type array, Type enumerator)
2086                 {
2087                         if (!array.IsArray || !enumerator.IsGenericType)
2088                                 return false;
2089
2090                         if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
2091                                 return false;
2092
2093                         Type[] args = GetTypeArguments (enumerator);
2094                         return args [0] == GetElementType (array);
2095                 }
2096
2097                 public static bool IsEqual (Type a, Type b)
2098                 {
2099                         if (a.Equals (b))
2100                                 return true;
2101
2102                         if (a.IsGenericParameter && b.IsGenericParameter) {
2103                                 if (a.DeclaringMethod != b.DeclaringMethod &&
2104                                     (a.DeclaringMethod == null || b.DeclaringMethod == null))
2105                                         return false;
2106                                 return a.GenericParameterPosition == b.GenericParameterPosition;
2107                         }
2108
2109                         if (a.IsArray && b.IsArray) {
2110                                 if (a.GetArrayRank () != b.GetArrayRank ())
2111                                         return false;
2112                                 return IsEqual (a.GetElementType (), b.GetElementType ());
2113                         }
2114
2115                         if (a.IsByRef && b.IsByRef)
2116                                 return IsEqual (a.GetElementType (), b.GetElementType ());
2117
2118                         if (a.IsGenericType && b.IsGenericType) {
2119                                 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2120                                         return false;
2121
2122                                 Type[] aargs = a.GetGenericArguments ();
2123                                 Type[] bargs = b.GetGenericArguments ();
2124
2125                                 if (aargs.Length != bargs.Length)
2126                                         return false;
2127
2128                                 for (int i = 0; i < aargs.Length; i++) {
2129                                         if (!IsEqual (aargs [i], bargs [i]))
2130                                                 return false;
2131                                 }
2132
2133                                 return true;
2134                         }
2135
2136                         //
2137                         // This is to build with the broken circular dependencies between
2138                         // System and System.Configuration in the 2.x profile where we
2139                         // end up with a situation where:
2140                         //
2141                         // System on the second build is referencing the System.Configuration
2142                         // that has references to the first System build.
2143                         //
2144                         // Point in case: NameValueCollection built on the first pass, vs
2145                         // NameValueCollection build on the second one.  The problem is that
2146                         // we need to override some methods sometimes, or we need to 
2147                         //
2148                         if (RootContext.BrokenCircularDeps){
2149                                 if (a.Name == b.Name && a.Namespace == b.Namespace){
2150                                         Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
2151                                         return true;
2152                                 }
2153                         }
2154                         return false;
2155                 }
2156
2157                 /// <summary>
2158                 ///   Check whether `a' and `b' may become equal generic types.
2159                 ///   The algorithm to do that is a little bit complicated.
2160                 /// </summary>
2161                 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2162                                                                Type[] method_infered)
2163                 {
2164                         if (a.IsGenericParameter) {
2165                                 //
2166                                 // If a is an array of a's type, they may never
2167                                 // become equal.
2168                                 //
2169                                 while (b.IsArray) {
2170                                         b = b.GetElementType ();
2171                                         if (a.Equals (b))
2172                                                 return false;
2173                                 }
2174
2175                                 //
2176                                 // If b is a generic parameter or an actual type,
2177                                 // they may become equal:
2178                                 //
2179                                 //    class X<T,U> : I<T>, I<U>
2180                                 //    class X<T> : I<T>, I<float>
2181                                 // 
2182                                 if (b.IsGenericParameter || !b.IsGenericType) {
2183                                         int pos = a.GenericParameterPosition;
2184                                         Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2185                                         if (args [pos] == null) {
2186                                                 args [pos] = b;
2187                                                 return true;
2188                                         }
2189
2190                                         return args [pos] == a;
2191                                 }
2192
2193                                 //
2194                                 // We're now comparing a type parameter with a
2195                                 // generic instance.  They may become equal unless
2196                                 // the type parameter appears anywhere in the
2197                                 // generic instance:
2198                                 //
2199                                 //    class X<T,U> : I<T>, I<X<U>>
2200                                 //        -> error because you could instanciate it as
2201                                 //           X<X<int>,int>
2202                                 //
2203                                 //    class X<T> : I<T>, I<X<T>> -> ok
2204                                 //
2205
2206                                 Type[] bargs = GetTypeArguments (b);
2207                                 for (int i = 0; i < bargs.Length; i++) {
2208                                         if (a.Equals (bargs [i]))
2209                                                 return false;
2210                                 }
2211
2212                                 return true;
2213                         }
2214
2215                         if (b.IsGenericParameter)
2216                                 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2217
2218                         //
2219                         // At this point, neither a nor b are a type parameter.
2220                         //
2221                         // If one of them is a generic instance, let
2222                         // MayBecomeEqualGenericInstances() compare them (if the
2223                         // other one is not a generic instance, they can never
2224                         // become equal).
2225                         //
2226
2227                         if (a.IsGenericType || b.IsGenericType)
2228                                 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2229
2230                         //
2231                         // If both of them are arrays.
2232                         //
2233
2234                         if (a.IsArray && b.IsArray) {
2235                                 if (a.GetArrayRank () != b.GetArrayRank ())
2236                                         return false;
2237                         
2238                                 a = a.GetElementType ();
2239                                 b = b.GetElementType ();
2240
2241                                 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2242                         }
2243
2244                         //
2245                         // Ok, two ordinary types.
2246                         //
2247
2248                         return a.Equals (b);
2249                 }
2250
2251                 //
2252                 // Checks whether two generic instances may become equal for some
2253                 // particular instantiation (26.3.1).
2254                 //
2255                 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2256                                                                    Type[] class_infered,
2257                                                                    Type[] method_infered)
2258                 {
2259                         if (!a.IsGenericType || !b.IsGenericType)
2260                                 return false;
2261                         if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2262                                 return false;
2263
2264                         return MayBecomeEqualGenericInstances (
2265                                 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2266                 }
2267
2268                 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2269                                                                    Type[] class_infered,
2270                                                                    Type[] method_infered)
2271                 {
2272                         if (aargs.Length != bargs.Length)
2273                                 return false;
2274
2275                         for (int i = 0; i < aargs.Length; i++) {
2276                                 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2277                                         return false;
2278                         }
2279
2280                         return true;
2281                 }
2282
2283                 /// <summary>
2284                 ///   Check whether `type' and `parent' are both instantiations of the same
2285                 ///   generic type.  Note that we do not check the type parameters here.
2286                 /// </summary>
2287                 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2288                 {
2289                         int tcount = GetNumberOfTypeArguments (type);
2290                         int pcount = GetNumberOfTypeArguments (parent);
2291
2292                         if (tcount != pcount)
2293                                 return false;
2294
2295                         type = DropGenericTypeArguments (type);
2296                         parent = DropGenericTypeArguments (parent);
2297
2298                         return type.Equals (parent);
2299                 }
2300
2301                 /// <summary>
2302                 ///   Whether `mb' is a generic method definition.
2303                 /// </summary>
2304                 public static bool IsGenericMethodDefinition (MethodBase mb)
2305                 {
2306                         if (mb.DeclaringType is TypeBuilder) {
2307                                 IMethodData method = (IMethodData) builder_to_method [mb];
2308                                 if (method == null)
2309                                         return false;
2310
2311                                 return method.GenericMethod != null;
2312                         }
2313
2314                         return mb.IsGenericMethodDefinition;
2315                 }
2316
2317                 /// <summary>
2318                 ///   Whether `mb' is a generic method definition.
2319                 /// </summary>
2320                 public static bool IsGenericMethod (MethodBase mb)
2321                 {
2322                         if (mb.DeclaringType is TypeBuilder) {
2323                                 IMethodData method = (IMethodData) builder_to_method [mb];
2324                                 if (method == null)
2325                                         return false;
2326
2327                                 return method.GenericMethod != null;
2328                         }
2329
2330                         return mb.IsGenericMethod;
2331                 }
2332
2333                 //
2334                 // Type inference.
2335                 //
2336
2337                 static bool InferType (Type pt, Type at, Type[] infered)
2338                 {
2339                         if (pt == at)
2340                                 return true;
2341
2342                         if (pt.IsGenericParameter) {
2343                                 if (pt.DeclaringMethod == null)
2344                                         return false;
2345
2346                                 int pos = pt.GenericParameterPosition;
2347
2348                                 if (infered [pos] == null) {
2349                                         Type check = at;
2350                                         while (check.IsArray)
2351                                                 check = check.GetElementType ();
2352
2353                                         if (pt == check)
2354                                                 return false;
2355
2356                                         infered [pos] = at;
2357                                         return true;
2358                                 }
2359
2360                                 if (infered [pos] != at)
2361                                         return false;
2362
2363                                 return true;
2364                         }
2365
2366                         if (!pt.ContainsGenericParameters) {
2367                                 if (at.ContainsGenericParameters)
2368                                         return InferType (at, pt, infered);
2369                                 else
2370                                         return true;
2371                         }
2372
2373                         if (at.IsArray) {
2374                                 if (pt.IsArray) {
2375                                         if (at.GetArrayRank () != pt.GetArrayRank ())
2376                                                 return false;
2377
2378                                         return InferType (pt.GetElementType (), at.GetElementType (), infered);
2379                                 }
2380
2381                                 if (!pt.IsGenericType ||
2382                                     (pt.GetGenericTypeDefinition () != generic_ienumerable_type))
2383                                     return false;
2384
2385                                 Type[] args = GetTypeArguments (pt);
2386                                 return InferType (args [0], at.GetElementType (), infered);
2387                         }
2388
2389                         if (pt.IsArray) {
2390                                 if (!at.IsArray ||
2391                                     (pt.GetArrayRank () != at.GetArrayRank ()))
2392                                         return false;
2393
2394                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2395                         }
2396
2397                         if (pt.IsByRef && at.IsByRef)
2398                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2399                         ArrayList list = new ArrayList ();
2400                         if (at.IsGenericType)
2401                                 list.Add (at);
2402                         for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2403                                 list.Add (bt);
2404
2405                         list.AddRange (TypeManager.GetInterfaces (at));
2406
2407                         bool found_one = false;
2408
2409                         foreach (Type type in list) {
2410                                 if (!type.IsGenericType)
2411                                         continue;
2412
2413                                 Type[] infered_types = new Type [infered.Length];
2414
2415                                 if (!InferGenericInstance (pt, type, infered_types))
2416                                         continue;
2417
2418                                 for (int i = 0; i < infered_types.Length; i++) {
2419                                         if (infered [i] == null) {
2420                                                 infered [i] = infered_types [i];
2421                                                 continue;
2422                                         }
2423
2424                                         if (infered [i] != infered_types [i])
2425                                                 return false;
2426                                 }
2427
2428                                 found_one = true;
2429                         }
2430
2431                         return found_one;
2432                 }
2433
2434                 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2435                 {
2436                         Type[] at_args = at.GetGenericArguments ();
2437                         Type[] pt_args = pt.GetGenericArguments ();
2438
2439                         if (at_args.Length != pt_args.Length)
2440                                 return false;
2441
2442                         for (int i = 0; i < at_args.Length; i++) {
2443                                 if (!InferType (pt_args [i], at_args [i], infered_types))
2444                                         return false;
2445                         }
2446
2447                         for (int i = 0; i < infered_types.Length; i++) {
2448                                 if (infered_types [i] == null)
2449                                         return false;
2450                         }
2451
2452                         return true;
2453                 }
2454
2455                 /// <summary>
2456                 ///   Type inference.  Try to infer the type arguments from the params method
2457                 ///   `method', which is invoked with the arguments `arguments'.  This is used
2458                 ///   when resolving an Invocation or a DelegateInvocation and the user
2459                 ///   did not explicitly specify type arguments.
2460                 /// </summary>
2461                 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2462                                                              ref MethodBase method)
2463                 {
2464                         if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2465                                 return true;
2466
2467                         int arg_count;
2468                         
2469                         if (arguments == null)
2470                                 arg_count = 0;
2471                         else
2472                                 arg_count = arguments.Count;
2473                         
2474                         ParameterData pd = TypeManager.GetParameterData (method);
2475
2476                         int pd_count = pd.Count;
2477
2478                         if (pd_count == 0)
2479                                 return false;
2480                         
2481                         if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2482                                 return false;
2483                         
2484                         if (pd_count - 1 > arg_count)
2485                                 return false;
2486                         
2487                         if (pd_count == 1 && arg_count == 0)
2488                                 return true;
2489
2490                         Type[] method_args = method.GetGenericArguments ();
2491                         Type[] infered_types = new Type [method_args.Length];
2492
2493                         //
2494                         // If we have come this far, the case which
2495                         // remains is when the number of parameters is
2496                         // less than or equal to the argument count.
2497                         //
2498                         for (int i = 0; i < pd_count - 1; ++i) {
2499                                 Argument a = (Argument) arguments [i];
2500
2501                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2502                                         continue;
2503
2504                                 Type pt = pd.ParameterType (i);
2505                                 Type at = a.Type;
2506
2507                                 if (!InferType (pt, at, infered_types))
2508                                         return false;
2509                         }
2510
2511                         Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2512
2513                         for (int i = pd_count - 1; i < arg_count; i++) {
2514                                 Argument a = (Argument) arguments [i];
2515
2516                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2517                                         continue;
2518
2519                                 if (!InferType (element_type, a.Type, infered_types))
2520                                         return false;
2521                         }
2522
2523                         for (int i = 0; i < infered_types.Length; i++)
2524                                 if (infered_types [i] == null)
2525                                         return false;
2526
2527                         method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2528                         return true;
2529                 }
2530
2531                 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2532                                                 Type[] infered_types)
2533                 {
2534                         if (infered_types == null)
2535                                 return false;
2536
2537                         for (int i = 0; i < arg_types.Length; i++) {
2538                                 if (arg_types [i] == null)
2539                                         continue;
2540
2541                                 if (!InferType (param_types [i], arg_types [i], infered_types))
2542                                         return false;
2543                         }
2544
2545                         for (int i = 0; i < infered_types.Length; i++)
2546                                 if (infered_types [i] == null)
2547                                         return false;
2548
2549                         return true;
2550                 }
2551
2552                 /// <summary>
2553                 ///   Type inference.  Try to infer the type arguments from `method',
2554                 ///   which is invoked with the arguments `arguments'.  This is used
2555                 ///   when resolving an Invocation or a DelegateInvocation and the user
2556                 ///   did not explicitly specify type arguments.
2557                 /// </summary>
2558                 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2559                                                        ref MethodBase method)
2560                 {
2561                         if (!TypeManager.IsGenericMethod (method))
2562                                 return true;
2563
2564                         int arg_count;
2565                         if (arguments != null)
2566                                 arg_count = arguments.Count;
2567                         else
2568                                 arg_count = 0;
2569
2570                         ParameterData pd = TypeManager.GetParameterData (method);
2571                         if (arg_count != pd.Count)
2572                                 return false;
2573
2574                         Type[] method_args = method.GetGenericArguments ();
2575
2576                         bool is_open = false;
2577                         for (int i = 0; i < method_args.Length; i++) {
2578                                 if (method_args [i].IsGenericParameter) {
2579                                         is_open = true;
2580                                         break;
2581                                 }
2582                         }
2583                         if (!is_open)
2584                                 return true;
2585
2586                         Type[] infered_types = new Type [method_args.Length];
2587
2588                         Type[] param_types = new Type [pd.Count];
2589                         Type[] arg_types = new Type [pd.Count];
2590
2591                         for (int i = 0; i < arg_count; i++) {
2592                                 param_types [i] = pd.ParameterType (i);
2593
2594                                 Argument a = (Argument) arguments [i];
2595                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2596                                     (a.Expr is AnonymousMethod))
2597                                         continue;
2598
2599                                 arg_types [i] = a.Type;
2600                         }
2601
2602                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2603                                 return false;
2604
2605                         method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2606                         return true;
2607                 }
2608
2609                 /// <summary>
2610                 ///   Type inference.
2611                 /// </summary>
2612                 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2613                                                        ref MethodBase method)
2614                 {
2615                         if (!TypeManager.IsGenericMethod (method))
2616                                 return true;
2617
2618                         ParameterData pd = TypeManager.GetParameterData (method);
2619                         if (apd.Count != pd.Count)
2620                                 return false;
2621
2622                         Type[] method_args = method.GetGenericArguments ();
2623                         Type[] infered_types = new Type [method_args.Length];
2624
2625                         Type[] param_types = new Type [pd.Count];
2626                         Type[] arg_types = new Type [pd.Count];
2627
2628                         for (int i = 0; i < apd.Count; i++) {
2629                                 param_types [i] = pd.ParameterType (i);
2630                                 arg_types [i] = apd.ParameterType (i);
2631                         }
2632
2633                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2634                                 return false;
2635
2636                         method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2637                         return true;
2638                 }
2639
2640                 public static bool IsNullableType (Type t)
2641                 {
2642                         return generic_nullable_type == DropGenericTypeArguments (t);
2643                 }
2644         }
2645
2646         public abstract class Nullable
2647         {
2648                 protected sealed class NullableInfo
2649                 {
2650                         public readonly Type Type;
2651                         public readonly Type UnderlyingType;
2652                         public readonly MethodInfo HasValue;
2653                         public readonly MethodInfo Value;
2654                         public readonly ConstructorInfo Constructor;
2655
2656                         public NullableInfo (Type type)
2657                         {
2658                                 Type = type;
2659                                 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2660
2661                                 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2662                                 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2663
2664                                 HasValue = has_value_pi.GetGetMethod (false);
2665                                 Value = value_pi.GetGetMethod (false);
2666                                 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2667                         }
2668                 }
2669
2670                 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2671                 {
2672                         Expression expr;
2673                         NullableInfo info;
2674
2675                         LocalTemporary temp;
2676                         bool has_temp;
2677
2678                         public Unwrap (Expression expr, Location loc)
2679                         {
2680                                 this.expr = expr;
2681                                 this.loc = loc;
2682                         }
2683
2684                         public override Expression DoResolve (EmitContext ec)
2685                         {
2686                                 expr = expr.Resolve (ec);
2687                                 if (expr == null)
2688                                         return null;
2689
2690                                 temp = new LocalTemporary (ec, expr.Type);
2691
2692                                 info = new NullableInfo (expr.Type);
2693                                 type = info.UnderlyingType;
2694                                 eclass = expr.eclass;
2695                                 return this;
2696                         }
2697
2698                         public override void Emit (EmitContext ec)
2699                         {
2700                                 AddressOf (ec, AddressOp.LoadStore);
2701                                 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2702                         }
2703
2704                         public void EmitCheck (EmitContext ec)
2705                         {
2706                                 AddressOf (ec, AddressOp.LoadStore);
2707                                 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2708                         }
2709
2710                         public void Store (EmitContext ec)
2711                         {
2712                                 create_temp (ec);
2713                         }
2714
2715                         void create_temp (EmitContext ec)
2716                         {
2717                                 if ((temp != null) && !has_temp) {
2718                                         expr.Emit (ec);
2719                                         temp.Store (ec);
2720                                         has_temp = true;
2721                                 }
2722                         }
2723
2724                         public void AddressOf (EmitContext ec, AddressOp mode)
2725                         {
2726                                 create_temp (ec);
2727                                 if (temp != null)
2728                                         temp.AddressOf (ec, AddressOp.LoadStore);
2729                                 else
2730                                         ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2731                         }
2732
2733                         public void Emit (EmitContext ec, bool leave_copy)
2734                         {
2735                                 create_temp (ec);
2736                                 if (leave_copy) {
2737                                         if (temp != null)
2738                                                 temp.Emit (ec);
2739                                         else
2740                                                 expr.Emit (ec);
2741                                 }
2742
2743                                 Emit (ec);
2744                         }
2745
2746                         public void EmitAssign (EmitContext ec, Expression source,
2747                                                 bool leave_copy, bool prepare_for_load)
2748                         {
2749                                 InternalWrap wrap = new InternalWrap (source, info, loc);
2750                                 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2751                         }
2752
2753                         protected class InternalWrap : Expression
2754                         {
2755                                 public Expression expr;
2756                                 public NullableInfo info;
2757
2758                                 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2759                                 {
2760                                         this.expr = expr;
2761                                         this.info = info;
2762                                         this.loc = loc;
2763
2764                                         type = info.Type;
2765                                         eclass = ExprClass.Value;
2766                                 }
2767
2768                                 public override Expression DoResolve (EmitContext ec)
2769                                 {
2770                                         return this;
2771                                 }
2772
2773                                 public override void Emit (EmitContext ec)
2774                                 {
2775                                         expr.Emit (ec);
2776                                         ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2777                                 }
2778                         }
2779                 }
2780
2781                 protected class Wrap : Expression
2782                 {
2783                         Expression expr;
2784                         NullableInfo info;
2785
2786                         public Wrap (Expression expr, Location loc)
2787                         {
2788                                 this.expr = expr;
2789                                 this.loc = loc;
2790                         }
2791
2792                         public override Expression DoResolve (EmitContext ec)
2793                         {
2794                                 expr = expr.Resolve (ec);
2795                                 if (expr == null)
2796                                         return null;
2797
2798                                 TypeExpr target_type = new NullableType (expr.Type, loc);
2799                                 target_type = target_type.ResolveAsTypeTerminal (ec);
2800                                 if (target_type == null)
2801                                         return null;
2802
2803                                 type = target_type.Type;
2804                                 info = new NullableInfo (type);
2805                                 eclass = ExprClass.Value;
2806                                 return this;
2807                         }
2808
2809                         public override void Emit (EmitContext ec)
2810                         {
2811                                 expr.Emit (ec);
2812                                 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2813                         }
2814                 }
2815
2816                 public class NullableLiteral : Expression, IMemoryLocation {
2817                         public NullableLiteral (Type target_type, Location loc)
2818                         {
2819                                 this.type = target_type;
2820                                 this.loc = loc;
2821
2822                                 eclass = ExprClass.Value;
2823                         }
2824                 
2825                         public override Expression DoResolve (EmitContext ec)
2826                         {
2827                                 return this;
2828                         }
2829
2830                         public override void Emit (EmitContext ec)
2831                         {
2832                                 LocalTemporary value_target = new LocalTemporary (ec, type);
2833
2834                                 value_target.AddressOf (ec, AddressOp.Store);
2835                                 ec.ig.Emit (OpCodes.Initobj, type);
2836                                 value_target.Emit (ec);
2837                         }
2838
2839                         public void AddressOf (EmitContext ec, AddressOp Mode)
2840                         {
2841                                 LocalTemporary value_target = new LocalTemporary (ec, type);
2842                                         
2843                                 value_target.AddressOf (ec, AddressOp.Store);
2844                                 ec.ig.Emit (OpCodes.Initobj, type);
2845                                 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2846                         }
2847                 }
2848
2849                 public abstract class Lifted : Expression, IMemoryLocation
2850                 {
2851                         Expression expr, underlying, wrap, null_value;
2852                         Unwrap unwrap;
2853
2854                         protected Lifted (Expression expr, Location loc)
2855                         {
2856                                 this.expr = expr;
2857                                 this.loc = loc;
2858                         }
2859
2860                         public override Expression DoResolve (EmitContext ec)
2861                         {
2862                                 expr = expr.Resolve (ec);
2863                                 if (expr == null)
2864                                         return null;
2865
2866                                 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2867                                 if (unwrap == null)
2868                                         return null;
2869
2870                                 underlying = ResolveUnderlying (unwrap, ec);
2871                                 if (underlying == null)
2872                                         return null;
2873
2874                                 wrap = new Wrap (underlying, loc).Resolve (ec);
2875                                 if (wrap == null)
2876                                         return null;
2877
2878                                 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2879                                 if (null_value == null)
2880                                         return null;
2881
2882                                 type = wrap.Type;
2883                                 eclass = ExprClass.Value;
2884                                 return this;
2885                         }
2886
2887                         protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2888
2889                         public override void Emit (EmitContext ec)
2890                         {
2891                                 ILGenerator ig = ec.ig;
2892                                 Label is_null_label = ig.DefineLabel ();
2893                                 Label end_label = ig.DefineLabel ();
2894
2895                                 unwrap.EmitCheck (ec);
2896                                 ig.Emit (OpCodes.Brfalse, is_null_label);
2897
2898                                 wrap.Emit (ec);
2899                                 ig.Emit (OpCodes.Br, end_label);
2900
2901                                 ig.MarkLabel (is_null_label);
2902                                 null_value.Emit (ec);
2903
2904                                 ig.MarkLabel (end_label);
2905                         }
2906
2907                         public void AddressOf (EmitContext ec, AddressOp mode)
2908                         {
2909                                 unwrap.AddressOf (ec, mode);
2910                         }
2911                 }
2912
2913                 public class LiftedConversion : Lifted
2914                 {
2915                         public readonly bool IsUser;
2916                         public readonly bool IsExplicit;
2917                         public readonly Type TargetType;
2918
2919                         public LiftedConversion (Expression expr, Type target_type, bool is_user,
2920                                                  bool is_explicit, Location loc)
2921                                 : base (expr, loc)
2922                         {
2923                                 this.IsUser = is_user;
2924                                 this.IsExplicit = is_explicit;
2925                                 this.TargetType = target_type;
2926                         }
2927
2928                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2929                         {
2930                                 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2931
2932                                 if (IsUser) {
2933                                         return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2934                                 } else {
2935                                         if (IsExplicit)
2936                                                 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2937                                         else
2938                                                 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2939                                 }
2940                         }
2941                 }
2942
2943                 public class LiftedUnaryOperator : Lifted
2944                 {
2945                         public readonly Unary.Operator Oper;
2946
2947                         public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2948                                 : base (expr, loc)
2949                         {
2950                                 this.Oper = op;
2951                         }
2952
2953                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2954                         {
2955                                 return new Unary (Oper, unwrap, loc);
2956                         }
2957                 }
2958
2959                 public class LiftedConditional : Lifted
2960                 {
2961                         Expression true_expr, false_expr;
2962
2963                         public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2964                                                   Location loc)
2965                                 : base (expr, loc)
2966                         {
2967                                 this.true_expr = true_expr;
2968                                 this.false_expr = false_expr;
2969                         }
2970
2971                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2972                         {
2973                                 return new Conditional (unwrap, true_expr, false_expr);
2974                         }
2975                 }
2976
2977                 public class LiftedBinaryOperator : Expression
2978                 {
2979                         public readonly Binary.Operator Oper;
2980
2981                         Expression left, right, original_left, original_right;
2982                         Expression underlying, null_value, bool_wrap;
2983                         Unwrap left_unwrap, right_unwrap;
2984                         bool is_equality, is_comparision, is_boolean;
2985
2986                         public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2987                                                      Location loc)
2988                         {
2989                                 this.Oper = op;
2990                                 this.left = original_left = left;
2991                                 this.right = original_right = right;
2992                                 this.loc = loc;
2993                         }
2994
2995                         public override Expression DoResolve (EmitContext ec)
2996                         {
2997                                 if (TypeManager.IsNullableType (left.Type)) {
2998                                         left_unwrap = new Unwrap (left, loc);
2999                                         left = left_unwrap.Resolve (ec);
3000                                         if (left == null)
3001                                                 return null;
3002                                 }
3003
3004                                 if (TypeManager.IsNullableType (right.Type)) {
3005                                         right_unwrap = new Unwrap (right, loc);
3006                                         right = right_unwrap.Resolve (ec);
3007                                         if (right == null)
3008                                                 return null;
3009                                 }
3010
3011                                 if ((Oper == Binary.Operator.LogicalAnd) ||
3012                                     (Oper == Binary.Operator.LogicalOr)) {
3013                                         Binary.Error_OperatorCannotBeApplied (
3014                                                 loc, Binary.OperName (Oper),
3015                                                 original_left.GetSignatureForError (),
3016                                                 original_right.GetSignatureForError ());
3017                                         return null;
3018                                 }
3019
3020                                 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3021                                     ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3022                                         Expression empty = new EmptyExpression (TypeManager.bool_type);
3023                                         bool_wrap = new Wrap (empty, loc).Resolve (ec);
3024                                         null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3025
3026                                         type = bool_wrap.Type;
3027                                         is_boolean = true;
3028                                 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3029                                         if (!(left is NullLiteral) && !(right is NullLiteral)) {
3030                                                 underlying = new Binary (Oper, left, right).Resolve (ec);
3031                                                 if (underlying == null)
3032                                                         return null;
3033                                         }
3034
3035                                         type = TypeManager.bool_type;
3036                                         is_equality = true;
3037                                 } else if ((Oper == Binary.Operator.LessThan) ||
3038                                            (Oper == Binary.Operator.GreaterThan) ||
3039                                            (Oper == Binary.Operator.LessThanOrEqual) ||
3040                                            (Oper == Binary.Operator.GreaterThanOrEqual)) {
3041                                         underlying = new Binary (Oper, left, right).Resolve (ec);
3042                                         if (underlying == null)
3043                                                 return null;
3044
3045                                         type = TypeManager.bool_type;
3046                                         is_comparision = true;
3047                                 } else {
3048                                         underlying = new Binary (Oper, left, right).Resolve (ec);
3049                                         if (underlying == null)
3050                                                 return null;
3051
3052                                         underlying = new Wrap (underlying, loc).Resolve (ec);
3053                                         if (underlying == null)
3054                                                 return null;
3055
3056                                         type = underlying.Type;
3057                                         null_value = new NullableLiteral (type, loc).Resolve (ec);
3058                                 }
3059
3060                                 eclass = ExprClass.Value;
3061                                 return this;
3062                         }
3063
3064                         void EmitBoolean (EmitContext ec)
3065                         {
3066                                 ILGenerator ig = ec.ig;
3067
3068                                 Label left_is_null_label = ig.DefineLabel ();
3069                                 Label right_is_null_label = ig.DefineLabel ();
3070                                 Label is_null_label = ig.DefineLabel ();
3071                                 Label wrap_label = ig.DefineLabel ();
3072                                 Label end_label = ig.DefineLabel ();
3073
3074                                 if (left_unwrap != null) {
3075                                         left_unwrap.EmitCheck (ec);
3076                                         ig.Emit (OpCodes.Brfalse, left_is_null_label);
3077                                 }
3078
3079                                 left.Emit (ec);
3080                                 ig.Emit (OpCodes.Dup);
3081                                 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3082                                         ig.Emit (OpCodes.Brtrue, wrap_label);
3083                                 else
3084                                         ig.Emit (OpCodes.Brfalse, wrap_label);
3085
3086                                 if (right_unwrap != null) {
3087                                         right_unwrap.EmitCheck (ec);
3088                                         ig.Emit (OpCodes.Brfalse, right_is_null_label);
3089                                 }
3090
3091                                 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3092                                         ig.Emit (OpCodes.Pop);
3093
3094                                 right.Emit (ec);
3095                                 if (Oper == Binary.Operator.BitwiseOr)
3096                                         ig.Emit (OpCodes.Or);
3097                                 else if (Oper == Binary.Operator.BitwiseAnd)
3098                                         ig.Emit (OpCodes.And);
3099                                 ig.Emit (OpCodes.Br, wrap_label);
3100
3101                                 ig.MarkLabel (left_is_null_label);
3102                                 if (right_unwrap != null) {
3103                                         right_unwrap.EmitCheck (ec);
3104                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3105                                 }
3106
3107                                 right.Emit (ec);
3108                                 ig.Emit (OpCodes.Dup);
3109                                 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3110                                         ig.Emit (OpCodes.Brtrue, wrap_label);
3111                                 else
3112                                         ig.Emit (OpCodes.Brfalse, wrap_label);
3113
3114                                 ig.MarkLabel (right_is_null_label);
3115                                 ig.Emit (OpCodes.Pop);
3116                                 ig.MarkLabel (is_null_label);
3117                                 null_value.Emit (ec);
3118                                 ig.Emit (OpCodes.Br, end_label);
3119
3120                                 ig.MarkLabel (wrap_label);
3121                                 ig.Emit (OpCodes.Nop);
3122                                 bool_wrap.Emit (ec);
3123                                 ig.Emit (OpCodes.Nop);
3124
3125                                 ig.MarkLabel (end_label);
3126                         }
3127
3128                         void EmitEquality (EmitContext ec)
3129                         {
3130                                 ILGenerator ig = ec.ig;
3131
3132                                 Label left_not_null_label = ig.DefineLabel ();
3133                                 Label false_label = ig.DefineLabel ();
3134                                 Label true_label = ig.DefineLabel ();
3135                                 Label end_label = ig.DefineLabel ();
3136
3137                                 bool false_label_used = false;
3138                                 bool true_label_used = false;
3139
3140                                 if (left_unwrap != null) {
3141                                         left_unwrap.EmitCheck (ec);
3142                                         if (right is NullLiteral) {
3143                                                 if (Oper == Binary.Operator.Equality) {
3144                                                         true_label_used = true;
3145                                                         ig.Emit (OpCodes.Brfalse, true_label);
3146                                                 } else {
3147                                                         false_label_used = true;
3148                                                         ig.Emit (OpCodes.Brfalse, false_label);
3149                                                 }
3150                                         } else if (right_unwrap != null) {
3151                                                 ig.Emit (OpCodes.Dup);
3152                                                 ig.Emit (OpCodes.Brtrue, left_not_null_label);
3153                                                 right_unwrap.EmitCheck (ec);
3154                                                 ig.Emit (OpCodes.Ceq);
3155                                                 if (Oper == Binary.Operator.Inequality) {
3156                                                         ig.Emit (OpCodes.Ldc_I4_0);
3157                                                         ig.Emit (OpCodes.Ceq);
3158                                                 }
3159                                                 ig.Emit (OpCodes.Br, end_label);
3160
3161                                                 ig.MarkLabel (left_not_null_label);
3162                                                 ig.Emit (OpCodes.Pop);
3163                                         } else {
3164                                                 if (Oper == Binary.Operator.Equality) {
3165                                                         false_label_used = true;
3166                                                         ig.Emit (OpCodes.Brfalse, false_label);
3167                                                 } else {
3168                                                         true_label_used = true;
3169                                                         ig.Emit (OpCodes.Brfalse, true_label);
3170                                                 }
3171                                         }
3172                                 }
3173
3174                                 if (right_unwrap != null) {
3175                                         right_unwrap.EmitCheck (ec);
3176                                         if (left is NullLiteral) {
3177                                                 if (Oper == Binary.Operator.Equality) {
3178                                                         true_label_used = true;
3179                                                         ig.Emit (OpCodes.Brfalse, true_label);
3180                                                 } else {
3181                                                         false_label_used = true;
3182                                                         ig.Emit (OpCodes.Brfalse, false_label);
3183                                                 }
3184                                         } else {
3185                                                 if (Oper == Binary.Operator.Equality) {
3186                                                         false_label_used = true;
3187                                                         ig.Emit (OpCodes.Brfalse, false_label);
3188                                                 } else {
3189                                                         true_label_used = true;
3190                                                         ig.Emit (OpCodes.Brfalse, true_label);
3191                                                 }
3192                                         }
3193                                 }
3194
3195                                 bool left_is_null = left is NullLiteral;
3196                                 bool right_is_null = right is NullLiteral;
3197                                 if (left_is_null || right_is_null) {
3198                                         if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
3199                                             ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
3200                                                 true_label_used = true;
3201                                                 ig.Emit (OpCodes.Br, true_label);
3202                                         } else {
3203                                                 false_label_used = true;
3204                                                 ig.Emit (OpCodes.Br, false_label);
3205                                         }
3206                                 } else {
3207                                         underlying.Emit (ec);
3208                                         ig.Emit (OpCodes.Br, end_label);
3209                                 }
3210
3211                                 ig.MarkLabel (false_label);
3212                                 if (false_label_used) {
3213                                         ig.Emit (OpCodes.Ldc_I4_0);
3214                                         if (true_label_used)
3215                                                 ig.Emit (OpCodes.Br, end_label);
3216                                 }
3217
3218                                 ig.MarkLabel (true_label);
3219                                 if (true_label_used)
3220                                         ig.Emit (OpCodes.Ldc_I4_1);
3221
3222                                 ig.MarkLabel (end_label);
3223                         }
3224
3225                         void EmitComparision (EmitContext ec)
3226                         {
3227                                 ILGenerator ig = ec.ig;
3228
3229                                 Label is_null_label = ig.DefineLabel ();
3230                                 Label end_label = ig.DefineLabel ();
3231
3232                                 if (left_unwrap != null) {
3233                                         left_unwrap.EmitCheck (ec);
3234                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3235                                 }
3236
3237                                 if (right_unwrap != null) {
3238                                         right_unwrap.EmitCheck (ec);
3239                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3240                                 }
3241
3242                                 underlying.Emit (ec);
3243                                 ig.Emit (OpCodes.Br, end_label);
3244
3245                                 ig.MarkLabel (is_null_label);
3246                                 ig.Emit (OpCodes.Ldc_I4_0);
3247
3248                                 ig.MarkLabel (end_label);
3249                         }
3250
3251                         public override void Emit (EmitContext ec)
3252                         {
3253                                 if (left_unwrap != null)
3254                                         left_unwrap.Store (ec);
3255                                 if (right_unwrap != null)
3256                                         right_unwrap.Store (ec);
3257
3258                                 if (is_boolean) {
3259                                         EmitBoolean (ec);
3260                                         return;
3261                                 } else if (is_equality) {
3262                                         EmitEquality (ec);
3263                                         return;
3264                                 } else if (is_comparision) {
3265                                         EmitComparision (ec);
3266                                         return;
3267                                 }
3268
3269                                 ILGenerator ig = ec.ig;
3270
3271                                 Label is_null_label = ig.DefineLabel ();
3272                                 Label end_label = ig.DefineLabel ();
3273
3274                                 if (left_unwrap != null) {
3275                                         left_unwrap.EmitCheck (ec);
3276                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3277                                 }
3278
3279                                 if (right_unwrap != null) {
3280                                         right_unwrap.EmitCheck (ec);
3281                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3282                                 }
3283
3284                                 underlying.Emit (ec);
3285                                 ig.Emit (OpCodes.Br, end_label);
3286
3287                                 ig.MarkLabel (is_null_label);
3288                                 null_value.Emit (ec);
3289
3290                                 ig.MarkLabel (end_label);
3291                         }
3292                 }
3293
3294                 public class OperatorTrueOrFalse : Expression
3295                 {
3296                         public readonly bool IsTrue;
3297
3298                         Expression expr;
3299                         Unwrap unwrap;
3300
3301                         public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3302                         {
3303                                 this.IsTrue = is_true;
3304                                 this.expr = expr;
3305                                 this.loc = loc;
3306                         }
3307
3308                         public override Expression DoResolve (EmitContext ec)
3309                         {
3310                                 unwrap = new Unwrap (expr, loc);
3311                                 expr = unwrap.Resolve (ec);
3312                                 if (expr == null)
3313                                         return null;
3314
3315                                 if (unwrap.Type != TypeManager.bool_type)
3316                                         return null;
3317
3318                                 type = TypeManager.bool_type;
3319                                 eclass = ExprClass.Value;
3320                                 return this;
3321                         }
3322
3323                         public override void Emit (EmitContext ec)
3324                         {
3325                                 ILGenerator ig = ec.ig;
3326
3327                                 Label is_null_label = ig.DefineLabel ();
3328                                 Label end_label = ig.DefineLabel ();
3329
3330                                 unwrap.EmitCheck (ec);
3331                                 ig.Emit (OpCodes.Brfalse, is_null_label);
3332
3333                                 unwrap.Emit (ec);
3334                                 if (!IsTrue) {
3335                                         ig.Emit (OpCodes.Ldc_I4_0);
3336                                         ig.Emit (OpCodes.Ceq);
3337                                 }
3338                                 ig.Emit (OpCodes.Br, end_label);
3339
3340                                 ig.MarkLabel (is_null_label);
3341                                 ig.Emit (OpCodes.Ldc_I4_0);
3342
3343                                 ig.MarkLabel (end_label);
3344                         }
3345                 }
3346
3347                 public class NullCoalescingOperator : Expression
3348                 {
3349                         Expression left, right;
3350                         Expression expr;
3351                         Unwrap unwrap;
3352
3353                         public NullCoalescingOperator (Expression left, Expression right, Location loc)
3354                         {
3355                                 this.left = left;
3356                                 this.right = right;
3357                                 this.loc = loc;
3358
3359                                 eclass = ExprClass.Value;
3360                         }
3361
3362                         public override Expression DoResolve (EmitContext ec)
3363                         {
3364                                 if (type != null)
3365                                         return this;
3366
3367                                 left = left.Resolve (ec);
3368                                 if (left == null)
3369                                         return null;
3370
3371                                 right = right.Resolve (ec);
3372                                 if (right == null)
3373                                         return null;
3374
3375                                 Type ltype = left.Type, rtype = right.Type;
3376
3377                                 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3378                                         Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3379                                         return null;
3380                                 }
3381
3382                                 if (TypeManager.IsNullableType (ltype)) {
3383                                         NullableInfo info = new NullableInfo (ltype);
3384
3385                                         unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
3386                                         if (unwrap == null)
3387                                                 return null;
3388
3389                                         expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3390                                         if (expr != null) {
3391                                                 left = unwrap;
3392                                                 type = expr.Type;
3393                                                 return this;
3394                                         }
3395                                 }
3396
3397                                 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3398                                 if (expr != null) {
3399                                         type = expr.Type;
3400                                         return this;
3401                                 }
3402
3403                                 if (unwrap != null) {
3404                                         expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
3405                                         if (expr != null) {
3406                                                 left = expr;
3407                                                 expr = right;
3408                                                 type = expr.Type;
3409                                                 return this;
3410                                         }
3411                                 }
3412
3413                                 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3414                                 return null;
3415                         }
3416
3417                         public override void Emit (EmitContext ec)
3418                         {
3419                                 ILGenerator ig = ec.ig;
3420
3421                                 Label is_null_label = ig.DefineLabel ();
3422                                 Label end_label = ig.DefineLabel ();
3423
3424                                 if (unwrap != null) {
3425                                         unwrap.EmitCheck (ec);
3426                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3427
3428                                         left.Emit (ec);
3429                                         ig.Emit (OpCodes.Br, end_label);
3430
3431                                         ig.MarkLabel (is_null_label);
3432                                         expr.Emit (ec);
3433
3434                                         ig.MarkLabel (end_label);
3435                                 } else {
3436                                         left.Emit (ec);
3437                                         ig.Emit (OpCodes.Dup);
3438                                         ig.Emit (OpCodes.Brtrue, end_label);
3439
3440                                         ig.MarkLabel (is_null_label);
3441
3442                                         ig.Emit (OpCodes.Pop);
3443                                         expr.Emit (ec);
3444
3445                                         ig.MarkLabel (end_label);
3446                                 }
3447                         }
3448                 }
3449
3450                 public class LiftedUnaryMutator : ExpressionStatement
3451                 {
3452                         public readonly UnaryMutator.Mode Mode;
3453                         Expression expr, null_value;
3454                         UnaryMutator underlying;
3455                         Unwrap unwrap;
3456
3457                         public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3458                         {
3459                                 this.expr = expr;
3460                                 this.Mode = mode;
3461                                 this.loc = loc;
3462
3463                                 eclass = ExprClass.Value;
3464                         }
3465
3466                         public override Expression DoResolve (EmitContext ec)
3467                         {
3468                                 expr = expr.Resolve (ec);
3469                                 if (expr == null)
3470                                         return null;
3471
3472                                 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3473                                 if (unwrap == null)
3474                                         return null;
3475
3476                                 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3477                                 if (underlying == null)
3478                                         return null;
3479
3480                                 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3481                                 if (null_value == null)
3482                                         return null;
3483
3484                                 type = expr.Type;
3485                                 return this;
3486                         }
3487
3488                         void DoEmit (EmitContext ec, bool is_expr)
3489                         {
3490                                 ILGenerator ig = ec.ig;
3491                                 Label is_null_label = ig.DefineLabel ();
3492                                 Label end_label = ig.DefineLabel ();
3493
3494                                 unwrap.EmitCheck (ec);
3495                                 ig.Emit (OpCodes.Brfalse, is_null_label);
3496
3497                                 if (is_expr)
3498                                         underlying.Emit (ec);
3499                                 else
3500                                         underlying.EmitStatement (ec);
3501                                 ig.Emit (OpCodes.Br, end_label);
3502
3503                                 ig.MarkLabel (is_null_label);
3504                                 if (is_expr)
3505                                         null_value.Emit (ec);
3506
3507                                 ig.MarkLabel (end_label);
3508                         }
3509
3510                         public override void Emit (EmitContext ec)
3511                         {
3512                                 DoEmit (ec, true);
3513                         }
3514
3515                         public override void EmitStatement (EmitContext ec)
3516                         {
3517                                 DoEmit (ec, false);
3518                         }
3519                 }
3520         }
3521 }