2005-03-07 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / gmcs / generic.cs
1 //
2 // generic.cs: Generics support
3 //
4 // Authors: Martin Baulig (martin@ximian.com)
5 //          Miguel de Icaza (miguel@ximian.com)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
11 //
12 using System;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
17 using System.Text;
18 using System.Text.RegularExpressions;
19         
20 namespace Mono.CSharp {
21
22         public abstract class GenericConstraints {
23                 public abstract GenericParameterAttributes Attributes {
24                         get;
25                 }
26
27                 public bool HasConstructorConstraint {
28                         get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
29                 }
30
31                 public bool HasReferenceTypeConstraint {
32                         get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
33                 }
34
35                 public bool HasValueTypeConstraint {
36                         get { return (Attributes & GenericParameterAttributes.ValueTypeConstraint) != 0; }
37                 }
38
39                 public virtual bool HasClassConstraint {
40                         get { return ClassConstraint != null; }
41                 }
42
43                 public abstract Type ClassConstraint {
44                         get;
45                 }
46
47                 public abstract Type[] InterfaceConstraints {
48                         get;
49                 }
50
51                 public abstract Type EffectiveBaseClass {
52                         get;
53                 }
54
55                 // <summary>
56                 //   Returns whether the type parameter is "known to be a reference type".
57                 // </summary>
58                 public virtual bool IsReferenceType {
59                         get {
60                                 if (HasReferenceTypeConstraint)
61                                         return true;
62                                 if (HasValueTypeConstraint)
63                                         return false;
64
65                                 if (ClassConstraint != null) {
66                                         if (ClassConstraint.IsValueType)
67                                                 return false;
68
69                                         if (ClassConstraint != TypeManager.object_type)
70                                                 return true;
71                                 }
72
73                                 foreach (Type t in InterfaceConstraints) {
74                                         if (!t.IsGenericParameter)
75                                                 continue;
76
77                                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
78                                         if ((gc != null) && gc.IsReferenceType)
79                                                 return true;
80                                 }
81
82                                 return false;
83                         }
84                 }
85
86                 // <summary>
87                 //   Returns whether the type parameter is "known to be a value type".
88                 // </summary>
89                 public virtual bool IsValueType {
90                         get {
91                                 if (HasValueTypeConstraint)
92                                         return true;
93                                 if (HasReferenceTypeConstraint)
94                                         return false;
95
96                                 if (ClassConstraint != null) {
97                                         if (!ClassConstraint.IsValueType)
98                                                 return false;
99
100                                         if (ClassConstraint != TypeManager.value_type)
101                                                 return true;
102                                 }
103
104                                 foreach (Type t in InterfaceConstraints) {
105                                         if (!t.IsGenericParameter)
106                                                 continue;
107
108                                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
109                                         if ((gc != null) && gc.IsValueType)
110                                                 return true;
111                                 }
112
113                                 return false;
114                         }
115                 }
116         }
117
118         public enum SpecialConstraint
119         {
120                 Constructor,
121                 ReferenceType,
122                 ValueType
123         }
124
125         //
126         // Tracks the constraints for a type parameter
127         //
128         public class Constraints : GenericConstraints {
129                 string name;
130                 ArrayList constraints;
131                 Location loc;
132                 
133                 //
134                 // name is the identifier, constraints is an arraylist of
135                 // Expressions (with types) or `true' for the constructor constraint.
136                 // 
137                 public Constraints (string name, ArrayList constraints,
138                                     Location loc)
139                 {
140                         this.name = name;
141                         this.constraints = constraints;
142                         this.loc = loc;
143                 }
144
145                 public string TypeParameter {
146                         get {
147                                 return name;
148                         }
149                 }
150
151                 GenericParameterAttributes attrs;
152                 TypeExpr class_constraint;
153                 ArrayList iface_constraints;
154                 ArrayList type_param_constraints;
155                 int num_constraints, first_constraint;
156                 Type class_constraint_type;
157                 Type[] iface_constraint_types;
158                 Type effective_base_type;
159
160                 public bool Resolve (EmitContext ec)
161                 {
162                         iface_constraints = new ArrayList ();
163                         type_param_constraints = new ArrayList ();
164
165                         foreach (object obj in constraints) {
166                                 if (HasConstructorConstraint) {
167                                         Report.Error (401, loc,
168                                                       "The new() constraint must be last.");
169                                         return false;
170                                 }
171
172                                 if (obj is SpecialConstraint) {
173                                         SpecialConstraint sc = (SpecialConstraint) obj;
174
175                                         if (sc == SpecialConstraint.Constructor) {
176                                                 if (!HasValueTypeConstraint) {
177                                                         attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
178                                                         continue;
179                                                 }
180
181                                                 Report.Error (
182                                                         451, loc, "The new () constraint " +
183                                                         "cannot be used with the `struct' " +
184                                                         "constraint.");
185                                                 return false;
186                                         }
187
188                                         if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
189                                                 Report.Error (449, loc,
190                                                               "The `class' or `struct' " +
191                                                               "constraint must be first");
192                                                 return false;
193                                         }
194
195                                         if (sc == SpecialConstraint.ReferenceType)
196                                                 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
197                                         else
198                                                 attrs |= GenericParameterAttributes.ValueTypeConstraint;
199                                         continue;
200                                 }
201
202                                 TypeExpr expr;
203                                 if (obj is ConstructedType) {
204                                         ConstructedType cexpr = (ConstructedType) obj;
205                                         if (!cexpr.ResolveConstructedType (ec))
206                                                 return false;
207                                         expr = cexpr;
208                                 } else
209                                         expr = ((Expression) obj).ResolveAsTypeTerminal (ec);
210
211                                 if (expr == null)
212                                         return false;
213
214                                 TypeParameterExpr texpr = expr as TypeParameterExpr;
215                                 if (texpr != null)
216                                         type_param_constraints.Add (expr);
217                                 else if (expr.IsInterface)
218                                         iface_constraints.Add (expr);
219                                 else if (class_constraint != null) {
220                                         Report.Error (406, loc,
221                                                       "`{0}': the class constraint for `{1}' " +
222                                                       "must come before any other constraints.",
223                                                       expr.Name, name);
224                                         return false;
225                                 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
226                                         Report.Error (450, loc, "`{0}': cannot specify both " +
227                                                       "a constraint class and the `class' " +
228                                                       "or `struct' constraint.", expr.Name);
229                                         return false;
230                                 } else
231                                         class_constraint = expr;
232
233                                 num_constraints++;
234                         }
235
236                         return true;
237                 }
238
239                 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
240                 {
241                         seen.Add (tparam, true);
242
243                         Constraints constraints = tparam.Constraints;
244                         if (constraints == null)
245                                 return true;
246
247                         if (constraints.HasValueTypeConstraint) {
248                                 Report.Error (456, loc, "Type parameter `{0}' has " +
249                                               "the `struct' constraint, so it cannot " +
250                                               "be used as a constraint for `{1}'",
251                                               tparam.Name, name);
252                                 return false;
253                         }
254
255                         if (constraints.type_param_constraints == null)
256                                 return true;
257
258                         foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
259                                 if (seen.Contains (expr.TypeParameter)) {
260                                         Report.Error (454, loc, "Circular constraint " +
261                                                       "dependency involving `{0}' and `{1}'",
262                                                       tparam.Name, expr.Name);
263                                         return false;
264                                 }
265
266                                 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
267                                         return false;
268                         }
269
270                         return true;
271                 }
272
273                 public bool ResolveTypes (EmitContext ec)
274                 {
275                         if (effective_base_type != null)
276                                 return true;
277
278                         foreach (object obj in constraints) {
279                                 ConstructedType cexpr = obj as ConstructedType;
280                                 if (cexpr == null)
281                                         continue;
282
283                                 if (!cexpr.CheckConstraints (ec))
284                                         return false;
285                         }
286
287                         foreach (TypeParameterExpr expr in type_param_constraints) {
288                                 Hashtable seen = new Hashtable ();
289                                 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
290                                         return false;
291                         }
292
293                         ArrayList list = new ArrayList ();
294
295                         foreach (TypeExpr iface_constraint in iface_constraints) {
296                                 foreach (Type type in list) {
297                                         if (!type.Equals (iface_constraint.Type))
298                                                 continue;
299
300                                         Report.Error (405, loc,
301                                                       "Duplicate constraint `{0}' for type " +
302                                                       "parameter `{1}'.", iface_constraint.Type,
303                                                       name);
304                                         return false;
305                                 }
306
307                                 list.Add (iface_constraint.Type);
308                         }
309
310                         foreach (TypeParameterExpr expr in type_param_constraints) {
311                                 foreach (Type type in list) {
312                                         if (!type.Equals (expr.Type))
313                                                 continue;
314
315                                         Report.Error (405, loc,
316                                                       "Duplicate constraint `{0}' for type " +
317                                                       "parameter `{1}'.", expr.Type, name);
318                                         return false;
319                                 }
320
321                                 list.Add (expr.Type);
322                         }
323
324                         iface_constraint_types = new Type [list.Count];
325                         list.CopyTo (iface_constraint_types, 0);
326
327                         if (class_constraint != null) {
328                                 class_constraint_type = class_constraint.Type;
329                                 if (class_constraint_type == null)
330                                         return false;
331
332                                 if (class_constraint_type.IsSealed) {
333                                         Report.Error (701, loc,
334                                                       "`{0}' is not a valid bound.  Bounds " +
335                                                       "must be interfaces or non sealed " +
336                                                       "classes", class_constraint_type);
337                                         return false;
338                                 }
339
340                                 if ((class_constraint_type == TypeManager.array_type) ||
341                                     (class_constraint_type == TypeManager.delegate_type) ||
342                                     (class_constraint_type == TypeManager.enum_type) ||
343                                     (class_constraint_type == TypeManager.value_type) ||
344                                     (class_constraint_type == TypeManager.object_type)) {
345                                         Report.Error (702, loc,
346                                                       "Bound cannot be special class `{0}'",
347                                                       class_constraint_type);
348                                         return false;
349                                 }
350                         }
351
352                         if (class_constraint_type != null)
353                                 effective_base_type = class_constraint_type;
354                         else if (HasValueTypeConstraint)
355                                 effective_base_type = TypeManager.value_type;
356                         else
357                                 effective_base_type = TypeManager.object_type;
358
359                         return true;
360                 }
361
362                 public bool CheckDependencies (EmitContext ec)
363                 {
364                         foreach (TypeParameterExpr expr in type_param_constraints) {
365                                 if (!CheckDependencies (expr.TypeParameter, ec))
366                                         return false;
367                         }
368
369                         return true;
370                 }
371
372                 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
373                 {
374                         Constraints constraints = tparam.Constraints;
375                         if (constraints == null)
376                                 return true;
377
378                         if (HasValueTypeConstraint && constraints.HasClassConstraint) {
379                                 Report.Error (455, loc, "Type parameter `{0}' inherits " +
380                                               "conflicting constraints `{1}' and `{2}'",
381                                               name, constraints.ClassConstraint,
382                                               "System.ValueType");
383                                 return false;
384                         }
385
386                         if (HasClassConstraint && constraints.HasClassConstraint) {
387                                 Type t1 = ClassConstraint;
388                                 TypeExpr e1 = class_constraint;
389                                 Type t2 = constraints.ClassConstraint;
390                                 TypeExpr e2 = constraints.class_constraint;
391
392                                 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
393                                     !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
394                                         Report.Error (455, loc,
395                                                       "Type parameter `{0}' inherits " +
396                                                       "conflicting constraints `{1}' and `{2}'",
397                                                       name, t1, t2);
398                                         return false;
399                                 }
400                         }
401
402                         if (constraints.type_param_constraints == null)
403                                 return true;
404
405                         foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
406                                 if (!CheckDependencies (expr.TypeParameter, ec))
407                                         return false;
408                         }
409
410                         return true;
411                 }
412
413                 public void Define (GenericTypeParameterBuilder type)
414                 {
415                         type.SetGenericParameterAttributes (attrs);
416                 }
417
418                 public override GenericParameterAttributes Attributes {
419                         get { return attrs; }
420                 }
421
422                 public override bool HasClassConstraint {
423                         get { return class_constraint != null; }
424                 }
425
426                 public override Type ClassConstraint {
427                         get { return class_constraint_type; }
428                 }
429
430                 public override Type[] InterfaceConstraints {
431                         get { return iface_constraint_types; }
432                 }
433
434                 public override Type EffectiveBaseClass {
435                         get { return effective_base_type; }
436                 }
437
438                 internal bool IsSubclassOf (Type t)
439                 {
440                         if ((class_constraint_type != null) &&
441                             class_constraint_type.IsSubclassOf (t))
442                                 return true;
443
444                         if (iface_constraint_types == null)
445                                 return false;
446
447                         foreach (Type iface in iface_constraint_types) {
448                                 if (TypeManager.IsSubclassOf (iface, t))
449                                         return true;
450                         }
451
452                         return false;
453                 }
454
455                 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
456                 {
457                         if (gc.Attributes != attrs)
458                                 return false;
459
460                         if (HasClassConstraint != gc.HasClassConstraint)
461                                 return false;
462                         if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
463                                 return false;
464
465                         int gc_icount = gc.InterfaceConstraints != null ?
466                                 gc.InterfaceConstraints.Length : 0;
467                         int icount = InterfaceConstraints != null ?
468                                 InterfaceConstraints.Length : 0;
469
470                         if (gc_icount != icount)
471                                 return false;
472
473                         foreach (Type iface in gc.InterfaceConstraints) {
474                                 bool ok = false;
475                                 foreach (Type check in InterfaceConstraints) {
476                                         if (TypeManager.IsEqual (iface, check)) {
477                                                 ok = true;
478                                                 break;
479                                         }
480                                 }
481
482                                 if (!ok)
483                                         return false;
484                         }
485
486                         return true;
487                 }
488         }
489
490         //
491         // This type represents a generic type parameter
492         //
493         public class TypeParameter : MemberCore, IMemberContainer {
494                 string name;
495                 GenericConstraints gc;
496                 Constraints constraints;
497                 Location loc;
498                 GenericTypeParameterBuilder type;
499
500                 public TypeParameter (TypeContainer parent, string name,
501                                       Constraints constraints, Location loc)
502                         : base (parent, new MemberName (name), null, loc)
503                 {
504                         this.name = name;
505                         this.constraints = constraints;
506                         this.loc = loc;
507                 }
508
509                 public GenericConstraints GenericConstraints {
510                         get {
511                                 return gc != null ? gc : constraints;
512                         }
513                 }
514
515                 public Constraints Constraints {
516                         get {
517                                 return constraints;
518                         }
519                 }
520
521                 public bool HasConstructorConstraint {
522                         get {
523                                 if (constraints != null)
524                                         return constraints.HasConstructorConstraint;
525
526                                 return false;
527                         }
528                 }
529
530                 public Type Type {
531                         get {
532                                 return type;
533                         }
534                 }
535
536                 public bool Resolve (DeclSpace ds)
537                 {
538                         if (constraints != null) {
539                                 if (!constraints.Resolve (ds.EmitContext)) {
540                                         constraints = null;
541                                         return false;
542                                 }
543                         }
544
545                         return true;
546                 }
547
548                 public void Define (GenericTypeParameterBuilder type)
549                 {
550                         if (this.type != null)
551                                 throw new InvalidOperationException ();
552
553                         this.type = type;
554                         TypeManager.AddTypeParameter (type, this);
555                 }
556
557                 public void DefineConstraints ()
558                 {
559                         if (constraints != null)
560                                 constraints.Define (type);
561                 }
562
563                 public bool ResolveType (EmitContext ec)
564                 {
565                         if (constraints != null) {
566                                 if (!constraints.ResolveTypes (ec)) {
567                                         constraints = null;
568                                         return false;
569                                 }
570                         }
571
572                         return true;
573                 }
574
575                 public bool DefineType (EmitContext ec)
576                 {
577                         return DefineType (ec, null, null, false);
578                 }
579
580                 public bool DefineType (EmitContext ec, MethodBuilder builder,
581                                         MethodInfo implementing, bool is_override)
582                 {
583                         if (!ResolveType (ec))
584                                 return false;
585
586                         if (implementing != null) {
587                                 if (is_override && (constraints != null)) {
588                                         Report.Error (
589                                                 460, loc, "Constraints for override and " +
590                                                 "explicit interface implementation methods " +
591                                                 "are inherited from the base method so they " +
592                                                 "cannot be specified directly");
593                                         return false;
594                                 }
595
596                                 MethodBase mb = implementing;
597                                 if (mb.Mono_IsInflatedMethod)
598                                         mb = mb.GetGenericMethodDefinition ();
599
600                                 int pos = type.GenericParameterPosition;
601                                 ParameterData pd = Invocation.GetParameterData (mb);
602                                 GenericConstraints temp_gc = pd.GenericConstraints (pos);
603                                 Type mparam = mb.GetGenericArguments () [pos];
604
605                                 if (temp_gc != null)
606                                         gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
607                                 else if (constraints != null)
608                                         gc = new InflatedConstraints (constraints, implementing.DeclaringType);
609
610                                 bool ok = true;
611                                 if (constraints != null) {
612                                         if (temp_gc == null)
613                                                 ok = false;
614                                         else if (!constraints.CheckInterfaceMethod (ec, gc))
615                                                 ok = false;
616                                 } else {
617                                         if (!is_override && (temp_gc != null))
618                                                 ok = false;
619                                 }
620
621                                 if (!ok) {
622                                         Report.SymbolRelatedToPreviousError (implementing);
623
624                                         Report.Error (
625                                                 425, loc, "The constraints for type " +
626                                                 "parameter `{0}' of method `{1}' must match " +
627                                                 "the constraints for type parameter `{2}' " +
628                                                 "of interface method `{3}'.  Consider using " +
629                                                 "an explicit interface implementation instead",
630                                                 Name, TypeManager.CSharpSignature (builder),
631                                                 mparam, TypeManager.CSharpSignature (mb));
632                                         return false;
633                                 }
634                         } else {
635                                 gc = (GenericConstraints) constraints;
636                         }
637
638                         if (gc == null)
639                                 return true;
640
641                         if (gc.HasClassConstraint)
642                                 type.SetBaseTypeConstraint (gc.ClassConstraint);
643
644                         type.SetInterfaceConstraints (gc.InterfaceConstraints);
645                         TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
646
647                         return true;
648                 }
649
650                 public bool CheckDependencies (EmitContext ec)
651                 {
652                         if (constraints != null)
653                                 return constraints.CheckDependencies (ec);
654
655                         return true;
656                 }
657
658                 public bool UpdateConstraints (EmitContext ec, Constraints new_constraints, bool check)
659                 {
660                         //
661                         // We're used in partial generic type definitions.
662                         // If `check' is false, we just encountered the first ClassPart which has
663                         // constraints - they become our "real" constraints.
664                         // Otherwise we're called after the type parameters have already been defined
665                         // and check whether the constraints are the same in all parts.
666                         //
667                         if (!check) {
668                                 if (type != null)
669                                         throw new InvalidOperationException ();
670                                 constraints = new_constraints;
671                                 return true;
672                         }
673
674                         if (type == null)
675                                 throw new InvalidOperationException ();
676
677                         if (constraints == null)
678                                 return new_constraints == null;
679                         else if (new_constraints == null)
680                                 return false;
681
682                         if (!new_constraints.Resolve (ec))
683                                 return false;
684                         if (!new_constraints.ResolveTypes (ec))
685                                 return false;
686
687                         return constraints.CheckInterfaceMethod (ec, new_constraints);
688                 }
689
690                 public override string DocCommentHeader {
691                         get {
692                                 throw new InvalidOperationException (
693                                         "Unexpected attempt to get doc comment from " + this.GetType () + ".");
694                         }
695                 }
696
697                 //
698                 // MemberContainer
699                 //
700
701                 public override bool Define ()
702                 {
703                         return true;
704                 }
705
706                 protected override void VerifyObsoleteAttribute ()
707                 { }
708
709                 public override void ApplyAttributeBuilder (Attribute a,
710                                                             CustomAttributeBuilder cb)
711                 { }
712
713                 public override AttributeTargets AttributeTargets {
714                         get {
715                                 return (AttributeTargets) 0;
716                         }
717                 }
718
719                 public override string[] ValidAttributeTargets {
720                         get {
721                                 return new string [0];
722                         }
723                 }
724
725                 //
726                 // IMemberContainer
727                 //
728
729                 string IMemberContainer.Name {
730                         get { return Name; }
731                 }
732
733                 MemberCache IMemberContainer.BaseCache {
734                         get { return null; }
735                 }
736
737                 bool IMemberContainer.IsInterface {
738                         get { return true; }
739                 }
740
741                 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
742                 {
743                         return FindMembers (mt, bf, null, null);
744                 }
745
746                 MemberCache IMemberContainer.MemberCache {
747                         get { return null; }
748                 }
749
750                 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
751                                                MemberFilter filter, object criteria)
752                 {
753                         if (constraints == null)
754                                 return MemberList.Empty;
755
756                         ArrayList members = new ArrayList ();
757
758                         GenericConstraints gc = (GenericConstraints) constraints;
759
760                         if (gc.HasClassConstraint) {
761                                 MemberList list = TypeManager.FindMembers (
762                                         gc.ClassConstraint, mt, bf, filter, criteria);
763
764                                 members.AddRange (list);
765                         }
766
767                         foreach (Type t in gc.InterfaceConstraints) {
768                                 MemberList list = TypeManager.FindMembers (
769                                         t, mt, bf, filter, criteria);
770
771                                 members.AddRange (list);
772                         }
773
774                         return new MemberList (members);
775                 }
776
777                 public bool IsSubclassOf (Type t)
778                 {
779                         if (type.Equals (t))
780                                 return true;
781
782                         if (constraints != null)
783                                 return constraints.IsSubclassOf (t);
784
785                         return false;
786                 }
787
788                 public override string ToString ()
789                 {
790                         return "TypeParameter[" + name + "]";
791                 }
792
793                 protected class InflatedConstraints : GenericConstraints
794                 {
795                         GenericConstraints gc;
796                         Type base_type;
797                         Type class_constraint;
798                         Type[] iface_constraints;
799                         Type[] dargs;
800                         Type declaring;
801
802                         public InflatedConstraints (GenericConstraints gc, Type declaring)
803                         {
804                                 this.gc = gc;
805                                 this.declaring = declaring;
806
807                                 dargs = TypeManager.GetTypeArguments (declaring);
808
809                                 ArrayList list = new ArrayList ();
810                                 if (gc.HasClassConstraint)
811                                         list.Add (inflate (gc.ClassConstraint));
812                                 foreach (Type iface in gc.InterfaceConstraints)
813                                         list.Add (inflate (iface));
814
815                                 bool has_class_constr = false;
816                                 if (list.Count > 0) {
817                                         Type first = (Type) list [0];
818                                         has_class_constr = !first.IsInterface && !first.IsGenericParameter;
819                                 }
820
821                                 if ((list.Count > 0) && has_class_constr) {
822                                         class_constraint = (Type) list [0];
823                                         iface_constraints = new Type [list.Count - 1];
824                                         list.CopyTo (1, iface_constraints, 0, list.Count - 1);
825                                 } else {
826                                         iface_constraints = new Type [list.Count];
827                                         list.CopyTo (iface_constraints, 0);
828                                 }
829
830                                 if (HasValueTypeConstraint)
831                                         base_type = TypeManager.value_type;
832                                 else if (class_constraint != null)
833                                         base_type = class_constraint;
834                                 else
835                                         base_type = TypeManager.object_type;
836                         }
837
838                         Type inflate (Type t)
839                         {
840                                 if (t == null)
841                                         return null;
842                                 if (t.IsGenericParameter)
843                                         return dargs [t.GenericParameterPosition];
844                                 if (t.IsGenericInstance) {
845                                         t = t.GetGenericTypeDefinition ();
846                                         t = t.BindGenericParameters (dargs);
847                                 }
848
849                                 return t;
850                         }
851
852                         public override GenericParameterAttributes Attributes {
853                                 get { return gc.Attributes; }
854                         }
855
856                         public override Type ClassConstraint {
857                                 get { return class_constraint; }
858                         }
859
860                         public override Type EffectiveBaseClass {
861                                 get { return base_type; }
862                         }
863
864                         public override Type[] InterfaceConstraints {
865                                 get { return iface_constraints; }
866                         }
867                 }
868         }
869
870         //
871         // This type represents a generic type parameter reference.
872         //
873         // These expressions are born in a fully resolved state.
874         //
875         public class TypeParameterExpr : TypeExpr {
876                 TypeParameter type_parameter;
877
878                 public override string Name {
879                         get {
880                                 return type_parameter.Name;
881                         }
882                 }
883
884                 public override string FullName {
885                         get {
886                                 return type_parameter.Name;
887                         }
888                 }
889
890                 public TypeParameter TypeParameter {
891                         get {
892                                 return type_parameter;
893                         }
894                 }
895                 
896                 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
897                 {
898                         this.type_parameter = type_parameter;
899                         this.loc = loc;
900                 }
901
902                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
903                 {
904                         type = type_parameter.Type;
905
906                         return this;
907                 }
908
909                 public override bool IsInterface {
910                         get { return false; }
911                 }
912
913                 public override bool CheckAccessLevel (DeclSpace ds)
914                 {
915                         return true;
916                 }
917
918                 public void Error_CannotUseAsUnmanagedType (Location loc)
919                 {
920                         Report.Error (-203, loc, "Can not use type parameter as unamanged type");
921                 }
922         }
923
924         public class TypeArguments {
925                 public readonly Location Location;
926                 ArrayList args;
927                 Type[] atypes;
928                 int dimension;
929                 bool has_type_args;
930                 bool created;
931                 
932                 public TypeArguments (Location loc)
933                 {
934                         args = new ArrayList ();
935                         this.Location = loc;
936                 }
937
938                 public TypeArguments (int dimension, Location loc)
939                 {
940                         this.dimension = dimension;
941                         this.Location = loc;
942                 }
943
944                 public void Add (Expression type)
945                 {
946                         if (created)
947                                 throw new InvalidOperationException ();
948
949                         args.Add (type);
950                 }
951
952                 public void Add (TypeArguments new_args)
953                 {
954                         if (created)
955                                 throw new InvalidOperationException ();
956
957                         args.AddRange (new_args.args);
958                 }
959
960                 public string[] GetDeclarations ()
961                 {
962                         string[] ret = new string [args.Count];
963                         for (int i = 0; i < args.Count; i++) {
964                                 SimpleName sn = args [i] as SimpleName;
965                                 if (sn != null) {
966                                         ret [i] = sn.Name;
967                                         continue;
968                                 }
969
970                                 Report.Error (81, Location, "Type parameter declaration " +
971                                               "must be an identifier not a type");
972                                 return null;
973                         }
974                         return ret;
975                 }
976
977                 public Type[] Arguments {
978                         get {
979                                 return atypes;
980                         }
981                 }
982
983                 public bool HasTypeArguments {
984                         get {
985                                 return has_type_args;
986                         }
987                 }
988
989                 public int Count {
990                         get {
991                                 if (dimension > 0)
992                                         return dimension;
993                                 else
994                                         return args.Count;
995                         }
996                 }
997
998                 public bool IsUnbound {
999                         get {
1000                                 return dimension > 0;
1001                         }
1002                 }
1003
1004                 public override string ToString ()
1005                 {
1006                         StringBuilder s = new StringBuilder ();
1007
1008                         int count = Count;
1009                         for (int i = 0; i < count; i++){
1010                                 //
1011                                 // FIXME: Use TypeManager.CSharpname once we have the type
1012                                 //
1013                                 if (args != null)
1014                                         s.Append (args [i].ToString ());
1015                                 if (i+1 < count)
1016                                         s.Append (",");
1017                         }
1018                         return s.ToString ();
1019                 }
1020
1021                 public bool Resolve (EmitContext ec)
1022                 {
1023                         int count = args.Count;
1024                         bool ok = true;
1025
1026                         atypes = new Type [count];
1027
1028                         for (int i = 0; i < count; i++){
1029                                 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
1030                                 if (te == null) {
1031                                         ok = false;
1032                                         continue;
1033                                 }
1034                                 if (te is TypeParameterExpr)
1035                                         has_type_args = true;
1036
1037                                 if (te.Type.IsPointer) {
1038                                         Report.Error (306, Location, "The type `{0}' may not be used " +
1039                                                       "as a type argument.", TypeManager.CSharpName (te.Type));
1040                                         return false;
1041                                 }
1042
1043                                 atypes [i] = te.Type;
1044                         }
1045                         return ok;
1046                 }
1047         }
1048         
1049         public class ConstructedType : TypeExpr {
1050                 string name, full_name;
1051                 TypeArguments args;
1052                 Type[] gen_params, atypes;
1053                 Type gt;
1054                 
1055                 public ConstructedType (string name, TypeArguments args, Location l)
1056                 {
1057                         loc = l;
1058                         this.name = MemberName.MakeName (name, args.Count);
1059                         this.args = args;
1060
1061                         eclass = ExprClass.Type;
1062                         full_name = name + "<" + args.ToString () + ">";
1063                 }
1064
1065                 public ConstructedType (string name, TypeParameter[] type_params, Location l)
1066                         : this (type_params, l)
1067                 {
1068                         loc = l;
1069
1070                         this.name = name;
1071                         full_name = name + "<" + args.ToString () + ">";
1072                 }
1073
1074                 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1075                 {
1076                         loc = l;
1077                         this.name = fname.FullName;
1078                         this.args = args;
1079
1080                         eclass = ExprClass.Type;
1081                         full_name = name + "<" + args.ToString () + ">";
1082                 }
1083
1084                 protected ConstructedType (TypeArguments args, Location l)
1085                 {
1086                         loc = l;
1087                         this.args = args;
1088
1089                         eclass = ExprClass.Type;
1090                 }
1091
1092                 protected ConstructedType (TypeParameter[] type_params, Location l)
1093                 {
1094                         loc = l;
1095
1096                         args = new TypeArguments (l);
1097                         foreach (TypeParameter type_param in type_params)
1098                                 args.Add (new TypeParameterExpr (type_param, l));
1099
1100                         eclass = ExprClass.Type;
1101                 }
1102
1103                 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1104                         : this (type_params, l)
1105                 {
1106                         gt = t.GetGenericTypeDefinition ();
1107
1108                         this.name = gt.FullName;
1109                         full_name = gt.FullName + "<" + args.ToString () + ">";
1110                 }
1111
1112                 public ConstructedType (Type t, TypeArguments args, Location l)
1113                         : this (args, l)
1114                 {
1115                         gt = t.GetGenericTypeDefinition ();
1116
1117                         this.name = gt.FullName;
1118                         full_name = gt.FullName + "<" + args.ToString () + ">";
1119                 }
1120
1121                 public TypeArguments TypeArguments {
1122                         get { return args; }
1123                 }
1124
1125                 protected string DeclarationName {
1126                         get {
1127                                 StringBuilder sb = new StringBuilder ();
1128                                 sb.Append (gt.FullName);
1129                                 sb.Append ("<");
1130                                 for (int i = 0; i < gen_params.Length; i++) {
1131                                         if (i > 0)
1132                                                 sb.Append (",");
1133                                         sb.Append (gen_params [i]);
1134                                 }
1135                                 sb.Append (">");
1136                                 return sb.ToString ();
1137                         }
1138                 }
1139
1140                 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1141                                                 Type ctype)
1142                 {
1143                         if (TypeManager.HasGenericArguments (ctype)) {
1144                                 Type[] types = TypeManager.GetTypeArguments (ctype);
1145
1146                                 TypeArguments new_args = new TypeArguments (loc);
1147
1148                                 for (int i = 0; i < types.Length; i++) {
1149                                         Type t = types [i];
1150
1151                                         if (t.IsGenericParameter) {
1152                                                 int pos = t.GenericParameterPosition;
1153                                                 t = args.Arguments [pos];
1154                                         }
1155                                         new_args.Add (new TypeExpression (t, loc));
1156                                 }
1157
1158                                 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1159                                 if (ct.ResolveAsTypeTerminal (ec) == null)
1160                                         return false;
1161                                 ctype = ct.Type;
1162                         }
1163
1164                         return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1165                 }
1166
1167                 protected bool CheckConstraints (EmitContext ec, int index)
1168                 {
1169                         Type atype = atypes [index];
1170                         Type ptype = gen_params [index];
1171
1172                         if (atype == ptype)
1173                                 return true;
1174
1175                         Expression aexpr = new EmptyExpression (atype);
1176
1177                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1178                         if (gc == null)
1179                                 return true;
1180
1181                         bool is_class, is_struct;
1182                         if (atype.IsGenericParameter) {
1183                                 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1184                                 if (agc != null) {
1185                                         is_class = agc.HasReferenceTypeConstraint;
1186                                         is_struct = agc.HasValueTypeConstraint;
1187                                 } else {
1188                                         is_class = is_struct = false;
1189                                 }
1190                         } else {
1191                                 is_class = atype.IsClass;
1192                                 is_struct = atype.IsValueType;
1193                         }
1194
1195                         //
1196                         // First, check the `class' and `struct' constraints.
1197                         //
1198                         if (gc.HasReferenceTypeConstraint && !is_class) {
1199                                 Report.Error (452, loc, "The type `{0}' must be " +
1200                                               "a reference type in order to use it " +
1201                                               "as type parameter `{1}' in the " +
1202                                               "generic type or method `{2}'.",
1203                                               atype, ptype, DeclarationName);
1204                                 return false;
1205                         } else if (gc.HasValueTypeConstraint && !is_struct) {
1206                                 Report.Error (453, loc, "The type `{0}' must be " +
1207                                               "a value type in order to use it " +
1208                                               "as type parameter `{1}' in the " +
1209                                               "generic type or method `{2}'.",
1210                                               atype, ptype, DeclarationName);
1211                                 return false;
1212                         }
1213
1214                         //
1215                         // The class constraint comes next.
1216                         //
1217                         if (gc.HasClassConstraint) {
1218                                 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1219                                         Report.Error (309, loc, "The type `{0}' must be " +
1220                                                       "convertible to `{1}' in order to " +
1221                                                       "use it as parameter `{2}' in the " +
1222                                                       "generic type or method `{3}'",
1223                                                       atype, gc.ClassConstraint, ptype, DeclarationName);
1224                                         return false;
1225                                 }
1226                         }
1227
1228                         //
1229                         // Now, check the interface constraints.
1230                         //
1231                         foreach (Type it in gc.InterfaceConstraints) {
1232                                 Type itype;
1233                                 if (it.IsGenericParameter)
1234                                         itype = atypes [it.GenericParameterPosition];
1235                                 else
1236                                         itype = it;
1237
1238                                 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1239                                         Report.Error (309, loc, "The type `{0}' must be " +
1240                                                       "convertible to `{1}' in order to " +
1241                                                       "use it as parameter `{2}' in the " +
1242                                                       "generic type or method `{3}'",
1243                                                       atype, itype, ptype, DeclarationName);
1244                                         return false;
1245                                 }
1246                         }
1247
1248                         //
1249                         // Finally, check the constructor constraint.
1250                         //
1251
1252                         if (!gc.HasConstructorConstraint)
1253                                 return true;
1254
1255                         if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1256                                 return true;
1257
1258                         MethodGroupExpr mg = Expression.MemberLookup (
1259                                 ec, atype, ".ctor", MemberTypes.Constructor,
1260                                 BindingFlags.Public | BindingFlags.Instance |
1261                                 BindingFlags.DeclaredOnly, loc)
1262                                 as MethodGroupExpr;
1263
1264                         if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
1265                                 Report.Error (310, loc, "The type `{0}' must have a public " +
1266                                               "parameterless constructor in order to use it " +
1267                                               "as parameter `{1}' in the generic type or " +
1268                                               "method `{2}'", atype, ptype, DeclarationName);
1269                                 return false;
1270                         }
1271
1272                         return true;
1273                 }
1274
1275                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1276                 {
1277                         if (!ResolveConstructedType (ec))
1278                                 return null;
1279
1280                         return this;
1281                 }
1282
1283                 public bool CheckConstraints (EmitContext ec)
1284                 {
1285                         for (int i = 0; i < gen_params.Length; i++) {
1286                                 if (!CheckConstraints (ec, i))
1287                                         return false;
1288                         }
1289
1290                         return true;
1291                 }
1292
1293                 public override TypeExpr ResolveAsTypeTerminal (EmitContext ec)
1294                 {
1295                         if (base.ResolveAsTypeTerminal (ec) == null)
1296                                 return null;
1297
1298                         if (!CheckConstraints (ec))
1299                                 return null;
1300
1301                         return this;
1302                 }
1303
1304                 public bool ResolveConstructedType (EmitContext ec)
1305                 {
1306                         if (type != null)
1307                                 return true;
1308                         if (gt != null)
1309                                 return DoResolveType (ec);
1310
1311                         //
1312                         // First, resolve the generic type.
1313                         //
1314                         DeclSpace ds;
1315                         Type nested = ec.DeclSpace.FindNestedType (loc, name, out ds);
1316                         if (nested != null) {
1317                                 gt = nested.GetGenericTypeDefinition ();
1318
1319                                 TypeArguments new_args = new TypeArguments (loc);
1320                                 if (ds.IsGeneric) {
1321                                         foreach (TypeParameter param in ds.TypeParameters)
1322                                                 new_args.Add (new TypeParameterExpr (param, loc));
1323                                 }
1324                                 new_args.Add (args);
1325
1326                                 args = new_args;
1327                                 return DoResolveType (ec);
1328                         }
1329
1330                         Type t;
1331                         int num_args;
1332
1333                         SimpleName sn = new SimpleName (name, loc);
1334                         TypeExpr resolved = sn.ResolveAsTypeTerminal (ec);
1335                         if (resolved == null)
1336                                 return false;
1337
1338                         t = resolved.Type;
1339                         if (t == null) {
1340                                 Report.Error (246, loc, "Cannot find type `{0}'<...>",
1341                                               Basename);
1342                                 return false;
1343                         }
1344
1345                         num_args = TypeManager.GetNumberOfTypeArguments (t);
1346                         if (num_args == 0) {
1347                                 Report.Error (308, loc,
1348                                               "The non-generic type `{0}' cannot " +
1349                                               "be used with type arguments.",
1350                                               TypeManager.CSharpName (t));
1351                                 return false;
1352                         }
1353
1354                         gt = t.GetGenericTypeDefinition ();
1355                         return DoResolveType (ec);
1356                 }
1357
1358                 bool DoResolveType (EmitContext ec)
1359                 {
1360                         //
1361                         // Resolve the arguments.
1362                         //
1363                         if (args.Resolve (ec) == false)
1364                                 return false;
1365
1366                         gen_params = gt.GetGenericArguments ();
1367                         atypes = args.Arguments;
1368
1369                         if (atypes.Length != gen_params.Length) {
1370                                 Report.Error (305, loc,
1371                                               "Using the generic type `{0}' " +
1372                                               "requires {1} type arguments",
1373                                               TypeManager.GetFullName (gt),
1374                                               gen_params.Length);
1375                                 return false;
1376                         }
1377
1378                         //
1379                         // Now bind the parameters.
1380                         //
1381                         type = gt.BindGenericParameters (atypes);
1382                         return true;
1383                 }
1384
1385                 public Expression GetSimpleName (EmitContext ec)
1386                 {
1387                         return new SimpleName (Basename, args, loc);
1388                 }
1389
1390                 public override bool CheckAccessLevel (DeclSpace ds)
1391                 {
1392                         return ds.CheckAccessLevel (gt);
1393                 }
1394
1395                 public override bool AsAccessible (DeclSpace ds, int flags)
1396                 {
1397                         return ds.AsAccessible (gt, flags);
1398                 }
1399
1400                 public override bool IsClass {
1401                         get { return gt.IsClass; }
1402                 }
1403
1404                 public override bool IsValueType {
1405                         get { return gt.IsValueType; }
1406                 }
1407
1408                 public override bool IsInterface {
1409                         get { return gt.IsInterface; }
1410                 }
1411
1412                 public override bool IsSealed {
1413                         get { return gt.IsSealed; }
1414                 }
1415
1416                 public override bool IsAttribute {
1417                         get { return false; }
1418                 }
1419
1420                 public override bool Equals (object obj)
1421                 {
1422                         ConstructedType cobj = obj as ConstructedType;
1423                         if (cobj == null)
1424                                 return false;
1425
1426                         if ((type == null) || (cobj.type == null))
1427                                 return false;
1428
1429                         return type == cobj.type;
1430                 }
1431
1432                 public override int GetHashCode ()
1433                 {
1434                         return base.GetHashCode ();
1435                 }
1436
1437                 public string Basename {
1438                         get {
1439                                 int pos = name.LastIndexOf ('`');
1440                                 if (pos >= 0)
1441                                         return name.Substring (0, pos);
1442                                 else
1443                                         return name;
1444                         }
1445                 }
1446
1447                 public override string Name {
1448                         get {
1449                                 return full_name;
1450                         }
1451                 }
1452
1453
1454                 public override string FullName {
1455                         get {
1456                                 return full_name;
1457                         }
1458                 }
1459         }
1460
1461         public class GenericMethod : DeclSpace
1462         {
1463                 public GenericMethod (NamespaceEntry ns, TypeContainer parent,
1464                                       MemberName name, Location l)
1465                         : base (ns, parent, name, null, l)
1466                 { }
1467
1468                 public override TypeBuilder DefineType ()
1469                 {
1470                         throw new Exception ();
1471                 }
1472
1473                 public override bool Define ()
1474                 {
1475                         for (int i = 0; i < TypeParameters.Length; i++)
1476                                 if (!TypeParameters [i].Resolve (Parent))
1477                                         return false;
1478
1479                         return true;
1480                 }
1481
1482                 public bool Define (MethodBuilder mb, Type return_type)
1483                 {
1484                         if (!Define ())
1485                                 return false;
1486
1487                         GenericTypeParameterBuilder[] gen_params;
1488                         string[] names = MemberName.TypeArguments.GetDeclarations ();
1489                         gen_params = mb.DefineGenericParameters (names);
1490                         for (int i = 0; i < TypeParameters.Length; i++)
1491                                 TypeParameters [i].Define (gen_params [i]);
1492
1493                         ec = new EmitContext (
1494                                 this, this, Location, null, return_type, ModFlags, false);
1495
1496                         for (int i = 0; i < TypeParameters.Length; i++) {
1497                                 if (!TypeParameters [i].ResolveType (ec))
1498                                         return false;
1499                         }
1500
1501                         return true;
1502                 }
1503
1504                 public bool DefineType (EmitContext ec, MethodBuilder mb,
1505                                         MethodInfo implementing, bool is_override)
1506                 {
1507                         for (int i = 0; i < TypeParameters.Length; i++)
1508                                 if (!TypeParameters [i].DefineType (
1509                                             ec, mb, implementing, is_override))
1510                                         return false;
1511
1512                         return true;
1513                 }
1514
1515                 public override bool DefineMembers (TypeContainer parent)
1516                 {
1517                         return true;
1518                 }
1519
1520                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1521                                                         MemberFilter filter, object criteria)
1522                 {
1523                         throw new Exception ();
1524                 }               
1525
1526                 public override MemberCache MemberCache {
1527                         get {
1528                                 return null;
1529                         }
1530                 }
1531
1532                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1533                 {
1534                         // FIXME
1535                 }
1536
1537                 protected override void VerifyObsoleteAttribute()
1538                 {
1539                         // FIXME
1540                 }
1541
1542                 public override AttributeTargets AttributeTargets {
1543                         get {
1544                                 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1545                         }
1546                 }
1547
1548                 public override string DocCommentHeader {
1549                         get { return "M:"; }
1550                 }
1551         }
1552
1553         public class DefaultValueExpression : Expression
1554         {
1555                 Expression expr;
1556                 LocalTemporary temp_storage;
1557
1558                 public DefaultValueExpression (Expression expr, Location loc)
1559                 {
1560                         this.expr = expr;
1561                         this.loc = loc;
1562                 }
1563
1564                 public override Expression DoResolve (EmitContext ec)
1565                 {
1566                         TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1567                         if (texpr == null)
1568                                 return null;
1569
1570                         type = texpr.Type;
1571                         if (type.IsGenericParameter || TypeManager.IsValueType (type))
1572                                 temp_storage = new LocalTemporary (ec, type);
1573
1574                         eclass = ExprClass.Variable;
1575                         return this;
1576                 }
1577
1578                 public override void Emit (EmitContext ec)
1579                 {
1580                         if (temp_storage != null) {
1581                                 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1582                                 ec.ig.Emit (OpCodes.Initobj, type);
1583                                 temp_storage.Emit (ec);
1584                         } else
1585                                 ec.ig.Emit (OpCodes.Ldnull);
1586                 }
1587         }
1588
1589         public class NullableType : TypeExpr
1590         {
1591                 Expression underlying;
1592
1593                 public NullableType (Expression underlying, Location l)
1594                 {
1595                         this.underlying = underlying;
1596                         loc = l;
1597
1598                         eclass = ExprClass.Type;
1599                 }
1600
1601                 public NullableType (Type type, Location loc)
1602                         : this (new TypeExpression (type, loc), loc)
1603                 { }
1604
1605                 public override string Name {
1606                         get { return underlying.ToString () + "?"; }
1607                 }
1608
1609                 public override string FullName {
1610                         get { return underlying.ToString () + "?"; }
1611                 }
1612
1613                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1614                 {
1615                         TypeArguments args = new TypeArguments (loc);
1616                         args.Add (underlying);
1617
1618                         ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1619                         return ctype.ResolveAsTypeTerminal (ec);
1620                 }
1621         }
1622
1623         public partial class TypeManager
1624         {
1625                 //
1626                 // A list of core types that the compiler requires or uses
1627                 //
1628                 static public Type new_constraint_attr_type;
1629                 static public Type activator_type;
1630                 static public Type generic_ienumerator_type;
1631                 static public Type generic_ienumerable_type;
1632                 static public Type generic_nullable_type;
1633
1634                 // <remarks>
1635                 //   Tracks the generic parameters.
1636                 // </remarks>
1637                 static PtrHashtable builder_to_type_param;
1638
1639                 //
1640                 // These methods are called by code generated by the compiler
1641                 //
1642                 static public MethodInfo activator_create_instance;
1643
1644                 static void InitGenerics ()
1645                 {
1646                         builder_to_type_param = new PtrHashtable ();
1647                 }
1648
1649                 static void CleanUpGenerics ()
1650                 {
1651                         builder_to_type_param = null;
1652                 }
1653
1654                 static void InitGenericCoreTypes ()
1655                 {
1656                         activator_type = CoreLookupType ("System.Activator");
1657                         new_constraint_attr_type = CoreLookupType (
1658                                 "System.Runtime.CompilerServices.NewConstraintAttribute");
1659
1660                         generic_ienumerator_type = CoreLookupType ("System.Collections.Generic.IEnumerator", 1);
1661                         generic_ienumerable_type = CoreLookupType ("System.Collections.Generic.IEnumerable", 1);
1662                         generic_nullable_type = CoreLookupType ("System.Nullable", 1);
1663                 }
1664
1665                 static void InitGenericCodeHelpers ()
1666                 {
1667                         // Activator
1668                         Type [] type_arg = { type_type };
1669                         activator_create_instance = GetMethod (
1670                                 activator_type, "CreateInstance", type_arg);
1671                 }
1672
1673                 static Type CoreLookupType (string name, int arity)
1674                 {
1675                         return CoreLookupType (MemberName.MakeName (name, arity));
1676                 }
1677
1678                 public static void AddTypeParameter (Type t, TypeParameter tparam)
1679                 {
1680                         if (!builder_to_type_param.Contains (t))
1681                                 builder_to_type_param.Add (t, tparam);
1682                 }
1683
1684                 public static TypeContainer LookupGenericTypeContainer (Type t)
1685                 {
1686                         while (t.IsGenericInstance)
1687                                 t = t.GetGenericTypeDefinition ();
1688
1689                         return LookupTypeContainer (t);
1690                 }
1691
1692                 public static TypeParameter LookupTypeParameter (Type t)
1693                 {
1694                         return (TypeParameter) builder_to_type_param [t];
1695                 }
1696
1697                 public static bool HasConstructorConstraint (Type t)
1698                 {
1699                         GenericConstraints gc = GetTypeParameterConstraints (t);
1700                         if (gc == null)
1701                                 return false;
1702
1703                         return (gc.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
1704                 }
1705
1706                 public static GenericConstraints GetTypeParameterConstraints (Type t)
1707                 {
1708                         if (!t.IsGenericParameter)
1709                                 throw new InvalidOperationException ();
1710
1711                         TypeParameter tparam = LookupTypeParameter (t);
1712                         if (tparam != null)
1713                                 return tparam.GenericConstraints;
1714
1715                         return new ReflectionConstraints (t);
1716                 }
1717
1718                 public static bool IsGeneric (Type t)
1719                 {
1720                         DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1721
1722                         return ds.IsGeneric;
1723                 }
1724
1725                 public static bool HasGenericArguments (Type t)
1726                 {
1727                         return GetNumberOfTypeArguments (t) > 0;
1728                 }
1729
1730                 public static int GetNumberOfTypeArguments (Type t)
1731                 {
1732                         DeclSpace tc = LookupDeclSpace (t);
1733                         if (tc != null)
1734                                 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1735                         else
1736                                 return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
1737                 }
1738
1739                 public static Type[] GetTypeArguments (Type t)
1740                 {
1741                         DeclSpace tc = LookupDeclSpace (t);
1742                         if (tc != null) {
1743                                 if (!tc.IsGeneric)
1744                                         return Type.EmptyTypes;
1745
1746                                 TypeParameter[] tparam = tc.TypeParameters;
1747                                 Type[] ret = new Type [tparam.Length];
1748                                 for (int i = 0; i < tparam.Length; i++) {
1749                                         ret [i] = tparam [i].Type;
1750                                         if (ret [i] == null)
1751                                                 throw new InternalErrorException ();
1752                                 }
1753
1754                                 return ret;
1755                         } else
1756                                 return t.GetGenericArguments ();
1757                 }
1758
1759                 public static bool IsEqual (Type a, Type b)
1760                 {
1761                         if (a.Equals (b))
1762                                 return true;
1763
1764                         if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1765                                 //
1766                                 // `a' is a generic type definition's TypeBuilder and `b' is a
1767                                 // generic instance of the same type.
1768                                 //
1769                                 // Example:
1770                                 //
1771                                 // class Stack<T>
1772                                 // {
1773                                 //     void Test (Stack<T> stack) { }
1774                                 // }
1775                                 //
1776                                 // The first argument of `Test' will be the generic instance
1777                                 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1778                                 //
1779                                 //
1780                                 // We hit this via Closure.Filter() for gen-82.cs.
1781                                 //
1782                                 if (a != b.GetGenericTypeDefinition ())
1783                                         return false;
1784
1785                                 Type[] aparams = a.GetGenericArguments ();
1786                                 Type[] bparams = b.GetGenericArguments ();
1787
1788                                 if (aparams.Length != bparams.Length)
1789                                         return false;
1790
1791                                 for (int i = 0; i < aparams.Length; i++)
1792                                         if (!IsEqual (aparams [i], bparams [i]))
1793                                                 return false;
1794
1795                                 return true;
1796                         }
1797
1798                         if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
1799                                 return IsEqual (b, a);
1800
1801                         if (a.IsGenericParameter && b.IsGenericParameter) {
1802                                 if ((a.DeclaringMethod == null) || (b.DeclaringMethod == null))
1803                                         return false;
1804                                 return a.GenericParameterPosition == b.GenericParameterPosition;
1805                         }
1806
1807                         if (a.IsArray && b.IsArray) {
1808                                 if (a.GetArrayRank () != b.GetArrayRank ())
1809                                         return false;
1810                                 return IsEqual (a.GetElementType (), b.GetElementType ());
1811                         }
1812
1813                         if (a.IsGenericInstance && b.IsGenericInstance) {
1814                                 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1815                                         return false;
1816
1817                                 Type[] aargs = a.GetGenericArguments ();
1818                                 Type[] bargs = b.GetGenericArguments ();
1819
1820                                 if (aargs.Length != bargs.Length)
1821                                         return false;
1822
1823                                 for (int i = 0; i < aargs.Length; i++) {
1824                                         if (!IsEqual (aargs [i], bargs [i]))
1825                                                 return false;
1826                                 }
1827
1828                                 return true;
1829                         }
1830
1831                         return false;
1832                 }
1833
1834                 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered, Type[] method_infered)
1835                 {
1836                         if (a.IsGenericParameter) {
1837                                 //
1838                                 // If a is an array of a's type, they may never
1839                                 // become equal.
1840                                 //
1841                                 while (b.IsArray) {
1842                                         b = b.GetElementType ();
1843                                         if (a.Equals (b))
1844                                                 return false;
1845                                 }
1846
1847                                 //
1848                                 // If b is a generic parameter or an actual type,
1849                                 // they may become equal:
1850                                 //
1851                                 //    class X<T,U> : I<T>, I<U>
1852                                 //    class X<T> : I<T>, I<float>
1853                                 // 
1854                                 if (b.IsGenericParameter || !b.IsGenericInstance) {
1855                                         int pos = a.GenericParameterPosition;
1856                                         Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
1857                                         if (args [pos] == null) {
1858                                                 args [pos] = b;
1859                                                 return true;
1860                                         }
1861
1862                                         return args [pos] == a;
1863                                 }
1864
1865                                 //
1866                                 // We're now comparing a type parameter with a
1867                                 // generic instance.  They may become equal unless
1868                                 // the type parameter appears anywhere in the
1869                                 // generic instance:
1870                                 //
1871                                 //    class X<T,U> : I<T>, I<X<U>>
1872                                 //        -> error because you could instanciate it as
1873                                 //           X<X<int>,int>
1874                                 //
1875                                 //    class X<T> : I<T>, I<X<T>> -> ok
1876                                 //
1877
1878                                 Type[] bargs = GetTypeArguments (b);
1879                                 for (int i = 0; i < bargs.Length; i++) {
1880                                         if (a.Equals (bargs [i]))
1881                                                 return false;
1882                                 }
1883
1884                                 return true;
1885                         }
1886
1887                         if (b.IsGenericParameter)
1888                                 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
1889
1890                         //
1891                         // At this point, neither a nor b are a type parameter.
1892                         //
1893                         // If one of them is a generic instance, let
1894                         // MayBecomeEqualGenericInstances() compare them (if the
1895                         // other one is not a generic instance, they can never
1896                         // become equal).
1897                         //
1898
1899                         if (a.IsGenericInstance || b.IsGenericInstance)
1900                                 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
1901
1902                         //
1903                         // If both of them are arrays.
1904                         //
1905
1906                         if (a.IsArray && b.IsArray) {
1907                                 if (a.GetArrayRank () != b.GetArrayRank ())
1908                                         return false;
1909                         
1910                                 a = a.GetElementType ();
1911                                 b = b.GetElementType ();
1912
1913                                 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
1914                         }
1915
1916                         //
1917                         // Ok, two ordinary types.
1918                         //
1919
1920                         return a.Equals (b);
1921                 }
1922
1923                 //
1924                 // Checks whether two generic instances may become equal for some
1925                 // particular instantiation (26.3.1).
1926                 //
1927                 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1928                                                                    Type[] class_infered, Type[] method_infered)
1929                 {
1930                         if (!a.IsGenericInstance || !b.IsGenericInstance)
1931                                 return false;
1932                         if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1933                                 return false;
1934
1935                         return MayBecomeEqualGenericInstances (
1936                                 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
1937                 }
1938
1939                 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1940                                                                    Type[] class_infered, Type[] method_infered)
1941                 {
1942                         if (aargs.Length != bargs.Length)
1943                                 return false;
1944
1945                         for (int i = 0; i < aargs.Length; i++) {
1946                                 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
1947                                         return false;
1948                         }
1949
1950                         return true;
1951                 }
1952
1953                 public static bool IsEqualGenericInstance (Type type, Type parent)
1954                 {
1955                         int tcount = GetNumberOfTypeArguments (type);
1956                         int pcount = GetNumberOfTypeArguments (parent);
1957
1958                         if (type.IsGenericInstance)
1959                                 type = type.GetGenericTypeDefinition ();
1960                         if (parent.IsGenericInstance)
1961                                 parent = parent.GetGenericTypeDefinition ();
1962
1963                         if (tcount != pcount)
1964                                 return false;
1965
1966                         return type.Equals (parent);
1967                 }
1968
1969                 static public bool IsGenericMethod (MethodBase mb)
1970                 {
1971                         if (mb.DeclaringType is TypeBuilder) {
1972                                 IMethodData method = (IMethodData) builder_to_method [mb];
1973                                 if (method == null)
1974                                         return false;
1975
1976                                 return method.GenericMethod != null;
1977                         }
1978
1979                         return mb.IsGenericMethodDefinition;
1980                 }
1981
1982                 //
1983                 // Type inference.
1984                 //
1985
1986                 static bool InferType (Type pt, Type at, Type[] infered)
1987                 {
1988                         if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
1989                                 int pos = pt.GenericParameterPosition;
1990
1991                                 if (infered [pos] == null) {
1992                                         Type check = at;
1993                                         while (check.IsArray)
1994                                                 check = check.GetElementType ();
1995
1996                                         if (pt == check)
1997                                                 return false;
1998
1999                                         infered [pos] = at;
2000                                         return true;
2001                                 }
2002
2003                                 if (infered [pos] != at)
2004                                         return false;
2005
2006                                 return true;
2007                         }
2008
2009                         if (!pt.ContainsGenericParameters) {
2010                                 if (at.ContainsGenericParameters)
2011                                         return InferType (at, pt, infered);
2012                                 else
2013                                         return true;
2014                         }
2015
2016                         if (at.IsArray) {
2017                                 if (!pt.IsArray ||
2018                                     (at.GetArrayRank () != pt.GetArrayRank ()))
2019                                         return false;
2020
2021                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2022                         }
2023
2024                         if (pt.IsArray) {
2025                                 if (!at.IsArray ||
2026                                     (pt.GetArrayRank () != at.GetArrayRank ()))
2027                                         return false;
2028
2029                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2030                         }
2031
2032                         if (pt.IsByRef && at.IsByRef)
2033                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2034                         ArrayList list = new ArrayList ();
2035                         if (at.IsGenericInstance)
2036                                 list.Add (at);
2037                         else {
2038                                 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2039                                         list.Add (bt);
2040
2041                                 list.AddRange (TypeManager.GetInterfaces (at));
2042                         }
2043
2044                         bool found_one = false;
2045
2046                         foreach (Type type in list) {
2047                                 if (!type.IsGenericInstance)
2048                                         continue;
2049
2050                                 Type[] infered_types = new Type [infered.Length];
2051
2052                                 if (!InferGenericInstance (pt, type, infered_types))
2053                                         continue;
2054
2055                                 for (int i = 0; i < infered_types.Length; i++) {
2056                                         if (infered [i] == null) {
2057                                                 infered [i] = infered_types [i];
2058                                                 continue;
2059                                         }
2060
2061                                         if (infered [i] != infered_types [i])
2062                                                 return false;
2063                                 }
2064
2065                                 found_one = true;
2066                         }
2067
2068                         return found_one;
2069                 }
2070
2071                 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2072                 {
2073                         Type[] at_args = at.GetGenericArguments ();
2074                         Type[] pt_args = pt.GetGenericArguments ();
2075
2076                         if (at_args.Length != pt_args.Length)
2077                                 return false;
2078
2079                         for (int i = 0; i < at_args.Length; i++) {
2080                                 if (!InferType (pt_args [i], at_args [i], infered_types))
2081                                         return false;
2082                         }
2083
2084                         for (int i = 0; i < infered_types.Length; i++) {
2085                                 if (infered_types [i] == null)
2086                                         return false;
2087                         }
2088
2089                         return true;
2090                 }
2091
2092                 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2093                                                              ref MethodBase method)
2094                 {
2095                         if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2096                                 return true;
2097
2098                         int arg_count;
2099                         
2100                         if (arguments == null)
2101                                 arg_count = 0;
2102                         else
2103                                 arg_count = arguments.Count;
2104                         
2105                         ParameterData pd = Invocation.GetParameterData (method);
2106
2107                         int pd_count = pd.Count;
2108
2109                         if (pd_count == 0)
2110                                 return false;
2111                         
2112                         if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2113                                 return false;
2114                         
2115                         if (pd_count - 1 > arg_count)
2116                                 return false;
2117                         
2118                         if (pd_count == 1 && arg_count == 0)
2119                                 return true;
2120
2121                         Type[] method_args = method.GetGenericArguments ();
2122                         Type[] infered_types = new Type [method_args.Length];
2123
2124                         //
2125                         // If we have come this far, the case which
2126                         // remains is when the number of parameters is
2127                         // less than or equal to the argument count.
2128                         //
2129                         for (int i = 0; i < pd_count - 1; ++i) {
2130                                 Argument a = (Argument) arguments [i];
2131
2132                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2133                                         continue;
2134
2135                                 Type pt = pd.ParameterType (i);
2136                                 Type at = a.Type;
2137
2138                                 if (!InferType (pt, at, infered_types))
2139                                         return false;
2140                         }
2141
2142                         Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2143
2144                         for (int i = pd_count - 1; i < arg_count; i++) {
2145                                 Argument a = (Argument) arguments [i];
2146
2147                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2148                                         continue;
2149
2150                                 if (!InferType (element_type, a.Type, infered_types))
2151                                         return false;
2152                         }
2153
2154                         for (int i = 0; i < infered_types.Length; i++)
2155                                 if (infered_types [i] == null)
2156                                         return false;
2157
2158                         method = method.BindGenericParameters (infered_types);
2159                         return true;
2160                 }
2161
2162                 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
2163                 {
2164                         if (infered_types == null)
2165                                 return false;
2166
2167                         for (int i = 0; i < arg_types.Length; i++) {
2168                                 if (arg_types [i] == null)
2169                                         continue;
2170
2171                                 if (!InferType (param_types [i], arg_types [i], infered_types))
2172                                         return false;
2173                         }
2174
2175                         for (int i = 0; i < infered_types.Length; i++)
2176                                 if (infered_types [i] == null)
2177                                         return false;
2178
2179                         return true;
2180                 }
2181
2182                 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2183                                                        ref MethodBase method)
2184                 {
2185                         if (!TypeManager.IsGenericMethod (method))
2186                                 return true;
2187
2188                         int arg_count;
2189                         if (arguments != null)
2190                                 arg_count = arguments.Count;
2191                         else
2192                                 arg_count = 0;
2193
2194                         ParameterData pd = Invocation.GetParameterData (method);
2195                         if (arg_count != pd.Count)
2196                                 return false;
2197
2198                         Type[] method_args = method.GetGenericArguments ();
2199
2200                         bool is_open = false;
2201                         for (int i = 0; i < method_args.Length; i++) {
2202                                 if (method_args [i].IsGenericParameter) {
2203                                         is_open = true;
2204                                         break;
2205                                 }
2206                         }
2207                         if (!is_open)
2208                                 return true;
2209
2210                         Type[] infered_types = new Type [method_args.Length];
2211
2212                         Type[] param_types = new Type [pd.Count];
2213                         Type[] arg_types = new Type [pd.Count];
2214
2215                         for (int i = 0; i < arg_count; i++) {
2216                                 param_types [i] = pd.ParameterType (i);
2217
2218                                 Argument a = (Argument) arguments [i];
2219                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2220                                         continue;
2221
2222                                 arg_types [i] = a.Type;
2223                         }
2224
2225                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2226                                 return false;
2227
2228                         method = method.BindGenericParameters (infered_types);
2229                         return true;
2230                 }
2231
2232                 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2233                                                        ref MethodBase method)
2234                 {
2235                         if (!TypeManager.IsGenericMethod (method))
2236                                 return true;
2237
2238                         ParameterData pd = Invocation.GetParameterData (method);
2239                         if (apd.Count != pd.Count)
2240                                 return false;
2241
2242                         Type[] method_args = method.GetGenericArguments ();
2243                         Type[] infered_types = new Type [method_args.Length];
2244
2245                         Type[] param_types = new Type [pd.Count];
2246                         Type[] arg_types = new Type [pd.Count];
2247
2248                         for (int i = 0; i < apd.Count; i++) {
2249                                 param_types [i] = pd.ParameterType (i);
2250                                 arg_types [i] = apd.ParameterType (i);
2251                         }
2252
2253                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2254                                 return false;
2255
2256                         method = method.BindGenericParameters (infered_types);
2257                         return true;
2258                 }
2259
2260                 public static bool IsNullableType (Type t)
2261                 {
2262                         if (!t.IsGenericInstance)
2263                                 return false;
2264
2265                         Type gt = t.GetGenericTypeDefinition ();
2266                         return gt == generic_nullable_type;
2267                 }
2268         }
2269
2270         public class NullCoalescingOperator : Expression
2271         {
2272                 Expression left;
2273                 Expression right;
2274
2275                 public NullCoalescingOperator (Expression left, Expression right, Location loc)
2276                 {
2277                         this.left = left;
2278                         this.right = right;
2279                         this.loc = loc;
2280                 }
2281
2282                 public override Expression DoResolve (EmitContext ec)
2283                 {
2284                         Error (-1, "The ?? operator is not yet implemented.");
2285                         return null;
2286                 }
2287
2288                 public override void Emit (EmitContext ec)
2289                 {
2290                 }
2291         }
2292
2293         public abstract class Nullable
2294         {
2295                 protected sealed class NullableInfo
2296                 {
2297                         public readonly Type Type;
2298                         public readonly Type UnderlyingType;
2299                         public readonly MethodInfo HasValue;
2300                         public readonly MethodInfo Value;
2301                         public readonly ConstructorInfo Constructor;
2302
2303                         public NullableInfo (Type type)
2304                         {
2305                                 Type = type;
2306                                 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2307
2308                                 PropertyInfo has_value_pi = type.GetProperty ("HasValue");
2309                                 PropertyInfo value_pi = type.GetProperty ("Value");
2310
2311                                 HasValue = has_value_pi.GetGetMethod (false);
2312                                 Value = value_pi.GetGetMethod (false);
2313                                 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2314                         }
2315                 }
2316
2317                 protected class Unwrap : Expression, IMemoryLocation
2318                 {
2319                         Expression expr;
2320                         NullableInfo info;
2321
2322                         LocalTemporary temp;
2323                         bool has_temp;
2324
2325                         public Unwrap (Expression expr, Location loc)
2326                         {
2327                                 this.expr = expr;
2328                                 this.loc = loc;
2329                         }
2330
2331                         public override Expression DoResolve (EmitContext ec)
2332                         {
2333                                 expr = expr.Resolve (ec);
2334                                 if (expr == null)
2335                                         return null;
2336
2337                                 if (!(expr is IMemoryLocation))
2338                                         temp = new LocalTemporary (ec, expr.Type);
2339
2340                                 info = new NullableInfo (expr.Type);
2341                                 type = info.UnderlyingType;
2342                                 eclass = expr.eclass;
2343                                 return this;
2344                         }
2345
2346                         public override void Emit (EmitContext ec)
2347                         {
2348                                 AddressOf (ec, AddressOp.LoadStore);
2349                                 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2350                         }
2351
2352                         public void EmitCheck (EmitContext ec, Label label)
2353                         {
2354                                 AddressOf (ec, AddressOp.LoadStore);
2355                                 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2356                                 ec.ig.Emit (OpCodes.Brfalse, label);
2357                         }
2358
2359                         public void AddressOf (EmitContext ec, AddressOp mode)
2360                         {
2361                                 if (temp != null) {
2362                                         if (!has_temp) {
2363                                                 temp.Store (ec);
2364                                                 has_temp = true;
2365                                         }
2366                                         temp.AddressOf (ec, AddressOp.LoadStore);
2367                                 } else
2368                                         ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2369                         }
2370                 }
2371
2372                 protected class Wrap : Expression
2373                 {
2374                         Expression expr;
2375                         NullableInfo info;
2376
2377                         public Wrap (Expression expr, Location loc)
2378                         {
2379                                 this.expr = expr;
2380                                 this.loc = loc;
2381                         }
2382
2383                         public override Expression DoResolve (EmitContext ec)
2384                         {
2385                                 expr = expr.Resolve (ec);
2386                                 if (expr == null)
2387                                         return null;
2388
2389                                 TypeExpr target_type = new NullableType (expr.Type, loc);
2390                                 target_type = target_type.ResolveAsTypeTerminal (ec);
2391                                 if (target_type == null)
2392                                         return null;
2393
2394                                 type = target_type.Type;
2395                                 info = new NullableInfo (type);
2396                                 eclass = ExprClass.Value;
2397                                 return this;
2398                         }
2399
2400                         public override void Emit (EmitContext ec)
2401                         {
2402                                 expr.Emit (ec);
2403                                 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2404                         }
2405                 }
2406
2407                 public class NullLiteral : Expression, IMemoryLocation {
2408                         public NullLiteral (Type target_type, Location loc)
2409                         {
2410                                 this.type = target_type;
2411                                 this.loc = loc;
2412
2413                                 eclass = ExprClass.Value;
2414                         }
2415                 
2416                         public override Expression DoResolve (EmitContext ec)
2417                         {
2418                                 return this;
2419                         }
2420
2421                         public override void Emit (EmitContext ec)
2422                         {
2423                                 LocalTemporary value_target = new LocalTemporary (ec, type);
2424
2425                                 value_target.AddressOf (ec, AddressOp.Store);
2426                                 ec.ig.Emit (OpCodes.Initobj, type);
2427                                 value_target.Emit (ec);
2428                         }
2429
2430                         public void AddressOf (EmitContext ec, AddressOp Mode)
2431                         {
2432                                 LocalTemporary value_target = new LocalTemporary (ec, type);
2433                                         
2434                                 value_target.AddressOf (ec, AddressOp.Store);
2435                                 ec.ig.Emit (OpCodes.Initobj, type);
2436                                 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2437                         }
2438                 }
2439
2440                 public abstract class Lifted : Expression, IMemoryLocation
2441                 {
2442                         Expression expr, underlying, wrap, null_value;
2443                         Unwrap unwrap;
2444
2445                         protected Lifted (Expression expr, Location loc)
2446                         {
2447                                 this.expr = expr;
2448                                 this.loc = loc;
2449                         }
2450
2451                         public override Expression DoResolve (EmitContext ec)
2452                         {
2453                                 expr = expr.Resolve (ec);
2454                                 if (expr == null)
2455                                         return null;
2456
2457                                 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2458                                 if (unwrap == null)
2459                                         return null;
2460
2461                                 underlying = ResolveUnderlying (unwrap, ec);
2462                                 if (underlying == null)
2463                                         return null;
2464
2465                                 wrap = new Wrap (underlying, loc).Resolve (ec);
2466                                 if (wrap == null)
2467                                         return null;
2468
2469                                 null_value = new NullLiteral (wrap.Type, loc).Resolve (ec);
2470                                 if (null_value == null)
2471                                         return null;
2472
2473                                 type = wrap.Type;
2474                                 eclass = ExprClass.Value;
2475                                 return this;
2476                         }
2477
2478                         protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2479
2480                         public override void Emit (EmitContext ec)
2481                         {
2482                                 ILGenerator ig = ec.ig;
2483                                 Label is_null_label = ig.DefineLabel ();
2484                                 Label end_label = ig.DefineLabel ();
2485
2486                                 unwrap.EmitCheck (ec, is_null_label);
2487
2488                                 wrap.Emit (ec);
2489                                 ig.Emit (OpCodes.Br, end_label);
2490
2491                                 ig.MarkLabel (is_null_label);
2492                                 null_value.Emit (ec);
2493
2494                                 ig.MarkLabel (end_label);
2495                         }
2496
2497                         public void AddressOf (EmitContext ec, AddressOp mode)
2498                         {
2499                                 unwrap.AddressOf (ec, mode);
2500                         }
2501                 }
2502
2503                 public class LiftedConversion : Lifted
2504                 {
2505                         public readonly bool IsUser;
2506                         public readonly bool IsExplicit;
2507                         public readonly Type TargetType;
2508
2509                         public LiftedConversion (Expression expr, Type target_type, bool is_user,
2510                                                  bool is_explicit, Location loc)
2511                                 : base (expr, loc)
2512                         {
2513                                 this.IsUser = is_user;
2514                                 this.IsExplicit = is_explicit;
2515                                 this.TargetType = target_type;
2516                         }
2517
2518                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2519                         {
2520                                 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2521
2522                                 if (IsUser) {
2523                                         return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2524                                 } else {
2525                                         if (IsExplicit)
2526                                                 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2527                                         else
2528                                                 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2529                                 }
2530                         }
2531                 }
2532
2533                 public class LiftedUnaryOperator : Lifted
2534                 {
2535                         public readonly Unary.Operator Oper;
2536
2537                         public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2538                                 : base (expr, loc)
2539                         {
2540                                 this.Oper = op;
2541                         }
2542
2543                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2544                         {
2545                                 return new Unary (Oper, unwrap, loc);
2546                         }
2547                 }
2548
2549                 public class LiftedConditional : Lifted
2550                 {
2551                         Expression expr, true_expr, false_expr;
2552                         Unwrap unwrap;
2553
2554                         public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2555                                                   Location loc)
2556                                 : base (expr, loc)
2557                         {
2558                                 this.true_expr = true_expr;
2559                                 this.false_expr = false_expr;
2560                         }
2561
2562                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2563                         {
2564                                 return new Conditional (unwrap, true_expr, false_expr, loc);
2565                         }
2566                 }
2567
2568                 public class LiftedBinaryOperator : Expression
2569                 {
2570                         public readonly Binary.Operator Oper;
2571
2572                         Expression left, right, underlying, null_value;
2573                         Unwrap left_unwrap, right_unwrap;
2574
2575                         public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2576                                                      Location loc)
2577                         {
2578                                 this.Oper = op;
2579                                 this.left = left;
2580                                 this.right = right;
2581                                 this.loc = loc;
2582                         }
2583
2584                         public override Expression DoResolve (EmitContext ec)
2585                         {
2586                                 left = left.Resolve (ec);
2587                                 if (left == null)
2588                                         return null;
2589
2590                                 right = right.Resolve (ec);
2591                                 if (right == null)
2592                                         return null;
2593
2594                                 if (TypeManager.IsNullableType (left.Type)) {
2595                                         left_unwrap = new Unwrap (left, loc);
2596                                         left = left_unwrap.Resolve (ec);
2597                                         if (left == null)
2598                                                 return null;
2599                                 }
2600
2601                                 if (TypeManager.IsNullableType (right.Type)) {
2602                                         right_unwrap = new Unwrap (right, loc);
2603                                         right = right_unwrap.Resolve (ec);
2604                                         if (right == null)
2605                                                 return null;
2606                                 }
2607
2608                                 underlying = new Wrap (new Binary (Oper, left, right, loc), loc);
2609                                 underlying = underlying.Resolve (ec);
2610                                 if (underlying == null)
2611                                         return null;
2612
2613                                 null_value = new NullLiteral (underlying.Type, loc).Resolve (ec);
2614                                 if (null_value == null)
2615                                         return null;
2616
2617                                 type = underlying.Type;
2618                                 eclass = ExprClass.Value;
2619                                 return this;
2620                         }
2621
2622                         public override void Emit (EmitContext ec)
2623                         {
2624                                 ILGenerator ig = ec.ig;
2625
2626                                 Label is_null_label = ig.DefineLabel ();
2627                                 Label end_label = ig.DefineLabel ();
2628
2629                                 if (left_unwrap != null)
2630                                         left_unwrap.EmitCheck (ec, is_null_label);
2631
2632                                 if (right_unwrap != null)
2633                                         right_unwrap.EmitCheck (ec, is_null_label);
2634
2635                                 underlying.Emit (ec);
2636                                 ig.Emit (OpCodes.Br, end_label);
2637
2638                                 ig.MarkLabel (is_null_label);
2639                                 null_value.Emit (ec);
2640
2641                                 ig.MarkLabel (end_label);
2642                         }
2643                 }
2644         }
2645 }