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