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