**** Merged r41289 from MCS ****
[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 = TypeManager.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 Equals (object obj)
1417                 {
1418                         ConstructedType cobj = obj as ConstructedType;
1419                         if (cobj == null)
1420                                 return false;
1421
1422                         if ((type == null) || (cobj.type == null))
1423                                 return false;
1424
1425                         return type == cobj.type;
1426                 }
1427
1428                 public override int GetHashCode ()
1429                 {
1430                         return base.GetHashCode ();
1431                 }
1432
1433                 public string Basename {
1434                         get {
1435                                 int pos = name.LastIndexOf ('`');
1436                                 if (pos >= 0)
1437                                         return name.Substring (0, pos);
1438                                 else
1439                                         return name;
1440                         }
1441                 }
1442
1443                 public override string Name {
1444                         get {
1445                                 return full_name;
1446                         }
1447                 }
1448
1449
1450                 public override string FullName {
1451                         get {
1452                                 return full_name;
1453                         }
1454                 }
1455         }
1456
1457         public class GenericMethod : DeclSpace
1458         {
1459                 public GenericMethod (NamespaceEntry ns, TypeContainer parent,
1460                                       MemberName name, Location l)
1461                         : base (ns, parent, name, null, l)
1462                 { }
1463
1464                 public override TypeBuilder DefineType ()
1465                 {
1466                         throw new Exception ();
1467                 }
1468
1469                 public override bool Define ()
1470                 {
1471                         for (int i = 0; i < TypeParameters.Length; i++)
1472                                 if (!TypeParameters [i].Resolve (Parent))
1473                                         return false;
1474
1475                         return true;
1476                 }
1477
1478                 public bool Define (MethodBuilder mb, Type return_type)
1479                 {
1480                         if (!Define ())
1481                                 return false;
1482
1483                         GenericTypeParameterBuilder[] gen_params;
1484                         string[] names = MemberName.TypeArguments.GetDeclarations ();
1485                         gen_params = mb.DefineGenericParameters (names);
1486                         for (int i = 0; i < TypeParameters.Length; i++)
1487                                 TypeParameters [i].Define (gen_params [i]);
1488
1489                         ec = new EmitContext (
1490                                 this, this, Location, null, return_type, ModFlags, false);
1491
1492                         for (int i = 0; i < TypeParameters.Length; i++) {
1493                                 if (!TypeParameters [i].ResolveType (ec))
1494                                         return false;
1495                         }
1496
1497                         return true;
1498                 }
1499
1500                 public bool DefineType (EmitContext ec, MethodBuilder mb,
1501                                         MethodInfo implementing, bool is_override)
1502                 {
1503                         for (int i = 0; i < TypeParameters.Length; i++)
1504                                 if (!TypeParameters [i].DefineType (
1505                                             ec, mb, implementing, is_override))
1506                                         return false;
1507
1508                         return true;
1509                 }
1510
1511                 public override bool DefineMembers (TypeContainer parent)
1512                 {
1513                         return true;
1514                 }
1515
1516                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1517                                                         MemberFilter filter, object criteria)
1518                 {
1519                         throw new Exception ();
1520                 }               
1521
1522                 public override MemberCache MemberCache {
1523                         get {
1524                                 return null;
1525                         }
1526                 }
1527
1528                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1529                 {
1530                         // FIXME
1531                 }
1532
1533                 protected override void VerifyObsoleteAttribute()
1534                 {
1535                         // FIXME
1536                 }
1537
1538                 public override AttributeTargets AttributeTargets {
1539                         get {
1540                                 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1541                         }
1542                 }
1543
1544                 public override string DocCommentHeader {
1545                         get { return "M:"; }
1546                 }
1547         }
1548
1549         public class DefaultValueExpression : Expression
1550         {
1551                 Expression expr;
1552                 LocalTemporary temp_storage;
1553
1554                 public DefaultValueExpression (Expression expr, Location loc)
1555                 {
1556                         this.expr = expr;
1557                         this.loc = loc;
1558                 }
1559
1560                 public override Expression DoResolve (EmitContext ec)
1561                 {
1562                         TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1563                         if (texpr == null)
1564                                 return null;
1565
1566                         type = texpr.Type;
1567                         if (type.IsGenericParameter || TypeManager.IsValueType (type))
1568                                 temp_storage = new LocalTemporary (ec, type);
1569
1570                         eclass = ExprClass.Variable;
1571                         return this;
1572                 }
1573
1574                 public override void Emit (EmitContext ec)
1575                 {
1576                         if (temp_storage != null) {
1577                                 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1578                                 ec.ig.Emit (OpCodes.Initobj, type);
1579                                 temp_storage.Emit (ec);
1580                         } else
1581                                 ec.ig.Emit (OpCodes.Ldnull);
1582                 }
1583         }
1584
1585         public class NullableType : TypeExpr
1586         {
1587                 Expression underlying;
1588
1589                 public NullableType (Expression underlying, Location l)
1590                 {
1591                         this.underlying = underlying;
1592                         loc = l;
1593
1594                         eclass = ExprClass.Type;
1595                 }
1596
1597                 public NullableType (Type type, Location loc)
1598                         : this (new TypeExpression (type, loc), loc)
1599                 { }
1600
1601                 public override string Name {
1602                         get { return underlying.ToString () + "?"; }
1603                 }
1604
1605                 public override string FullName {
1606                         get { return underlying.ToString () + "?"; }
1607                 }
1608
1609                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1610                 {
1611                         TypeArguments args = new TypeArguments (loc);
1612                         args.Add (underlying);
1613
1614                         ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
1615                         return ctype.ResolveAsTypeTerminal (ec);
1616                 }
1617         }
1618
1619         public partial class TypeManager
1620         {
1621                 //
1622                 // A list of core types that the compiler requires or uses
1623                 //
1624                 static public Type new_constraint_attr_type;
1625                 static public Type activator_type;
1626                 static public Type generic_ienumerator_type;
1627                 static public Type generic_ienumerable_type;
1628                 static public Type generic_nullable_type;
1629
1630                 // <remarks>
1631                 //   Tracks the generic parameters.
1632                 // </remarks>
1633                 static PtrHashtable builder_to_type_param;
1634
1635                 //
1636                 // These methods are called by code generated by the compiler
1637                 //
1638                 static public MethodInfo activator_create_instance;
1639
1640                 static void InitGenerics ()
1641                 {
1642                         builder_to_type_param = new PtrHashtable ();
1643                 }
1644
1645                 static void CleanUpGenerics ()
1646                 {
1647                         builder_to_type_param = null;
1648                 }
1649
1650                 static void InitGenericCoreTypes ()
1651                 {
1652                         activator_type = CoreLookupType ("System.Activator");
1653                         new_constraint_attr_type = CoreLookupType (
1654                                 "System.Runtime.CompilerServices.NewConstraintAttribute");
1655
1656                         generic_ienumerator_type = CoreLookupType ("System.Collections.Generic.IEnumerator", 1);
1657                         generic_ienumerable_type = CoreLookupType ("System.Collections.Generic.IEnumerable", 1);
1658                         generic_nullable_type = CoreLookupType ("System.Nullable", 1);
1659                 }
1660
1661                 static void InitGenericCodeHelpers ()
1662                 {
1663                         // Activator
1664                         Type [] type_arg = { type_type };
1665                         activator_create_instance = GetMethod (
1666                                 activator_type, "CreateInstance", type_arg);
1667                 }
1668
1669                 static Type CoreLookupType (string name, int arity)
1670                 {
1671                         return CoreLookupType (MemberName.MakeName (name, arity));
1672                 }
1673
1674                 public static void AddTypeParameter (Type t, TypeParameter tparam)
1675                 {
1676                         if (!builder_to_type_param.Contains (t))
1677                                 builder_to_type_param.Add (t, tparam);
1678                 }
1679
1680                 public static TypeContainer LookupGenericTypeContainer (Type t)
1681                 {
1682                         while (t.IsGenericInstance)
1683                                 t = t.GetGenericTypeDefinition ();
1684
1685                         return LookupTypeContainer (t);
1686                 }
1687
1688                 public static TypeParameter LookupTypeParameter (Type t)
1689                 {
1690                         return (TypeParameter) builder_to_type_param [t];
1691                 }
1692
1693                 public static bool HasConstructorConstraint (Type t)
1694                 {
1695                         GenericConstraints gc = GetTypeParameterConstraints (t);
1696                         if (gc == null)
1697                                 return false;
1698
1699                         return (gc.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
1700                 }
1701
1702                 public static GenericConstraints GetTypeParameterConstraints (Type t)
1703                 {
1704                         if (!t.IsGenericParameter)
1705                                 throw new InvalidOperationException ();
1706
1707                         TypeParameter tparam = LookupTypeParameter (t);
1708                         if (tparam != null)
1709                                 return tparam.GenericConstraints;
1710
1711                         return new ReflectionConstraints (t);
1712                 }
1713
1714                 public static bool IsGeneric (Type t)
1715                 {
1716                         DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1717
1718                         return ds.IsGeneric;
1719                 }
1720
1721                 public static bool HasGenericArguments (Type t)
1722                 {
1723                         return GetNumberOfTypeArguments (t) > 0;
1724                 }
1725
1726                 public static int GetNumberOfTypeArguments (Type t)
1727                 {
1728                         DeclSpace tc = LookupDeclSpace (t);
1729                         if (tc != null)
1730                                 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1731                         else
1732                                 return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
1733                 }
1734
1735                 public static Type[] GetTypeArguments (Type t)
1736                 {
1737                         DeclSpace tc = LookupDeclSpace (t);
1738                         if (tc != null) {
1739                                 if (!tc.IsGeneric)
1740                                         return Type.EmptyTypes;
1741
1742                                 TypeParameter[] tparam = tc.TypeParameters;
1743                                 Type[] ret = new Type [tparam.Length];
1744                                 for (int i = 0; i < tparam.Length; i++) {
1745                                         ret [i] = tparam [i].Type;
1746                                         if (ret [i] == null)
1747                                                 throw new InternalErrorException ();
1748                                 }
1749
1750                                 return ret;
1751                         } else
1752                                 return t.GetGenericArguments ();
1753                 }
1754
1755                 //
1756                 // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
1757                 // For instance "string[]" -> "IEnumerable<string>".
1758                 //
1759                 public static bool IsIEnumerable (Type array, Type enumerator)
1760                 {
1761                         if (!array.IsArray || !enumerator.IsGenericInstance)
1762                                 return false;
1763
1764                         if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
1765                                 return false;
1766
1767                         Type[] args = GetTypeArguments (enumerator);
1768                         return args [0] == GetElementType (array);
1769                 }
1770
1771                 public static bool IsEqual (Type a, Type b)
1772                 {
1773                         if (a.Equals (b))
1774                                 return true;
1775
1776                         if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1777                                 //
1778                                 // `a' is a generic type definition's TypeBuilder and `b' is a
1779                                 // generic instance of the same type.
1780                                 //
1781                                 // Example:
1782                                 //
1783                                 // class Stack<T>
1784                                 // {
1785                                 //     void Test (Stack<T> stack) { }
1786                                 // }
1787                                 //
1788                                 // The first argument of `Test' will be the generic instance
1789                                 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1790                                 //
1791                                 //
1792                                 // We hit this via Closure.Filter() for gen-82.cs.
1793                                 //
1794                                 if (a != b.GetGenericTypeDefinition ())
1795                                         return false;
1796
1797                                 Type[] aparams = a.GetGenericArguments ();
1798                                 Type[] bparams = b.GetGenericArguments ();
1799
1800                                 if (aparams.Length != bparams.Length)
1801                                         return false;
1802
1803                                 for (int i = 0; i < aparams.Length; i++)
1804                                         if (!IsEqual (aparams [i], bparams [i]))
1805                                                 return false;
1806
1807                                 return true;
1808                         }
1809
1810                         if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
1811                                 return IsEqual (b, a);
1812
1813                         if (a.IsGenericParameter && b.IsGenericParameter) {
1814                                 if ((a.DeclaringMethod == null) || (b.DeclaringMethod == null))
1815                                         return false;
1816                                 return a.GenericParameterPosition == b.GenericParameterPosition;
1817                         }
1818
1819                         if (a.IsArray && b.IsArray) {
1820                                 if (a.GetArrayRank () != b.GetArrayRank ())
1821                                         return false;
1822                                 return IsEqual (a.GetElementType (), b.GetElementType ());
1823                         }
1824
1825                         if (a.IsGenericInstance && b.IsGenericInstance) {
1826                                 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1827                                         return false;
1828
1829                                 Type[] aargs = a.GetGenericArguments ();
1830                                 Type[] bargs = b.GetGenericArguments ();
1831
1832                                 if (aargs.Length != bargs.Length)
1833                                         return false;
1834
1835                                 for (int i = 0; i < aargs.Length; i++) {
1836                                         if (!IsEqual (aargs [i], bargs [i]))
1837                                                 return false;
1838                                 }
1839
1840                                 return true;
1841                         }
1842
1843                         return false;
1844                 }
1845
1846                 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered, Type[] method_infered)
1847                 {
1848                         if (a.IsGenericParameter) {
1849                                 //
1850                                 // If a is an array of a's type, they may never
1851                                 // become equal.
1852                                 //
1853                                 while (b.IsArray) {
1854                                         b = b.GetElementType ();
1855                                         if (a.Equals (b))
1856                                                 return false;
1857                                 }
1858
1859                                 //
1860                                 // If b is a generic parameter or an actual type,
1861                                 // they may become equal:
1862                                 //
1863                                 //    class X<T,U> : I<T>, I<U>
1864                                 //    class X<T> : I<T>, I<float>
1865                                 // 
1866                                 if (b.IsGenericParameter || !b.IsGenericInstance) {
1867                                         int pos = a.GenericParameterPosition;
1868                                         Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
1869                                         if (args [pos] == null) {
1870                                                 args [pos] = b;
1871                                                 return true;
1872                                         }
1873
1874                                         return args [pos] == a;
1875                                 }
1876
1877                                 //
1878                                 // We're now comparing a type parameter with a
1879                                 // generic instance.  They may become equal unless
1880                                 // the type parameter appears anywhere in the
1881                                 // generic instance:
1882                                 //
1883                                 //    class X<T,U> : I<T>, I<X<U>>
1884                                 //        -> error because you could instanciate it as
1885                                 //           X<X<int>,int>
1886                                 //
1887                                 //    class X<T> : I<T>, I<X<T>> -> ok
1888                                 //
1889
1890                                 Type[] bargs = GetTypeArguments (b);
1891                                 for (int i = 0; i < bargs.Length; i++) {
1892                                         if (a.Equals (bargs [i]))
1893                                                 return false;
1894                                 }
1895
1896                                 return true;
1897                         }
1898
1899                         if (b.IsGenericParameter)
1900                                 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
1901
1902                         //
1903                         // At this point, neither a nor b are a type parameter.
1904                         //
1905                         // If one of them is a generic instance, let
1906                         // MayBecomeEqualGenericInstances() compare them (if the
1907                         // other one is not a generic instance, they can never
1908                         // become equal).
1909                         //
1910
1911                         if (a.IsGenericInstance || b.IsGenericInstance)
1912                                 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
1913
1914                         //
1915                         // If both of them are arrays.
1916                         //
1917
1918                         if (a.IsArray && b.IsArray) {
1919                                 if (a.GetArrayRank () != b.GetArrayRank ())
1920                                         return false;
1921                         
1922                                 a = a.GetElementType ();
1923                                 b = b.GetElementType ();
1924
1925                                 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
1926                         }
1927
1928                         //
1929                         // Ok, two ordinary types.
1930                         //
1931
1932                         return a.Equals (b);
1933                 }
1934
1935                 //
1936                 // Checks whether two generic instances may become equal for some
1937                 // particular instantiation (26.3.1).
1938                 //
1939                 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1940                                                                    Type[] class_infered, Type[] method_infered)
1941                 {
1942                         if (!a.IsGenericInstance || !b.IsGenericInstance)
1943                                 return false;
1944                         if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1945                                 return false;
1946
1947                         return MayBecomeEqualGenericInstances (
1948                                 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
1949                 }
1950
1951                 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1952                                                                    Type[] class_infered, Type[] method_infered)
1953                 {
1954                         if (aargs.Length != bargs.Length)
1955                                 return false;
1956
1957                         for (int i = 0; i < aargs.Length; i++) {
1958                                 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
1959                                         return false;
1960                         }
1961
1962                         return true;
1963                 }
1964
1965                 public static bool IsEqualGenericInstance (Type type, Type parent)
1966                 {
1967                         int tcount = GetNumberOfTypeArguments (type);
1968                         int pcount = GetNumberOfTypeArguments (parent);
1969
1970                         if (type.IsGenericInstance)
1971                                 type = type.GetGenericTypeDefinition ();
1972                         if (parent.IsGenericInstance)
1973                                 parent = parent.GetGenericTypeDefinition ();
1974
1975                         if (tcount != pcount)
1976                                 return false;
1977
1978                         return type.Equals (parent);
1979                 }
1980
1981                 static public bool IsGenericMethod (MethodBase mb)
1982                 {
1983                         if (mb.DeclaringType is TypeBuilder) {
1984                                 IMethodData method = (IMethodData) builder_to_method [mb];
1985                                 if (method == null)
1986                                         return false;
1987
1988                                 return method.GenericMethod != null;
1989                         }
1990
1991                         return mb.IsGenericMethodDefinition;
1992                 }
1993
1994                 //
1995                 // Type inference.
1996                 //
1997
1998                 static bool InferType (Type pt, Type at, Type[] infered)
1999                 {
2000                         if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
2001                                 int pos = pt.GenericParameterPosition;
2002
2003                                 if (infered [pos] == null) {
2004                                         Type check = at;
2005                                         while (check.IsArray)
2006                                                 check = check.GetElementType ();
2007
2008                                         if (pt == check)
2009                                                 return false;
2010
2011                                         infered [pos] = at;
2012                                         return true;
2013                                 }
2014
2015                                 if (infered [pos] != at)
2016                                         return false;
2017
2018                                 return true;
2019                         }
2020
2021                         if (!pt.ContainsGenericParameters) {
2022                                 if (at.ContainsGenericParameters)
2023                                         return InferType (at, pt, infered);
2024                                 else
2025                                         return true;
2026                         }
2027
2028                         if (at.IsArray) {
2029                                 if (!pt.IsArray ||
2030                                     (at.GetArrayRank () != pt.GetArrayRank ()))
2031                                         return false;
2032
2033                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2034                         }
2035
2036                         if (pt.IsArray) {
2037                                 if (!at.IsArray ||
2038                                     (pt.GetArrayRank () != at.GetArrayRank ()))
2039                                         return false;
2040
2041                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2042                         }
2043
2044                         if (pt.IsByRef && at.IsByRef)
2045                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2046                         ArrayList list = new ArrayList ();
2047                         if (at.IsGenericInstance)
2048                                 list.Add (at);
2049                         else {
2050                                 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2051                                         list.Add (bt);
2052
2053                                 list.AddRange (TypeManager.GetInterfaces (at));
2054                         }
2055
2056                         bool found_one = false;
2057
2058                         foreach (Type type in list) {
2059                                 if (!type.IsGenericInstance)
2060                                         continue;
2061
2062                                 Type[] infered_types = new Type [infered.Length];
2063
2064                                 if (!InferGenericInstance (pt, type, infered_types))
2065                                         continue;
2066
2067                                 for (int i = 0; i < infered_types.Length; i++) {
2068                                         if (infered [i] == null) {
2069                                                 infered [i] = infered_types [i];
2070                                                 continue;
2071                                         }
2072
2073                                         if (infered [i] != infered_types [i])
2074                                                 return false;
2075                                 }
2076
2077                                 found_one = true;
2078                         }
2079
2080                         return found_one;
2081                 }
2082
2083                 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2084                 {
2085                         Type[] at_args = at.GetGenericArguments ();
2086                         Type[] pt_args = pt.GetGenericArguments ();
2087
2088                         if (at_args.Length != pt_args.Length)
2089                                 return false;
2090
2091                         for (int i = 0; i < at_args.Length; i++) {
2092                                 if (!InferType (pt_args [i], at_args [i], infered_types))
2093                                         return false;
2094                         }
2095
2096                         for (int i = 0; i < infered_types.Length; i++) {
2097                                 if (infered_types [i] == null)
2098                                         return false;
2099                         }
2100
2101                         return true;
2102                 }
2103
2104                 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2105                                                              ref MethodBase method)
2106                 {
2107                         if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2108                                 return true;
2109
2110                         int arg_count;
2111                         
2112                         if (arguments == null)
2113                                 arg_count = 0;
2114                         else
2115                                 arg_count = arguments.Count;
2116                         
2117                         ParameterData pd = TypeManager.GetParameterData (method);
2118
2119                         int pd_count = pd.Count;
2120
2121                         if (pd_count == 0)
2122                                 return false;
2123                         
2124                         if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2125                                 return false;
2126                         
2127                         if (pd_count - 1 > arg_count)
2128                                 return false;
2129                         
2130                         if (pd_count == 1 && arg_count == 0)
2131                                 return true;
2132
2133                         Type[] method_args = method.GetGenericArguments ();
2134                         Type[] infered_types = new Type [method_args.Length];
2135
2136                         //
2137                         // If we have come this far, the case which
2138                         // remains is when the number of parameters is
2139                         // less than or equal to the argument count.
2140                         //
2141                         for (int i = 0; i < pd_count - 1; ++i) {
2142                                 Argument a = (Argument) arguments [i];
2143
2144                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2145                                         continue;
2146
2147                                 Type pt = pd.ParameterType (i);
2148                                 Type at = a.Type;
2149
2150                                 if (!InferType (pt, at, infered_types))
2151                                         return false;
2152                         }
2153
2154                         Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2155
2156                         for (int i = pd_count - 1; i < arg_count; i++) {
2157                                 Argument a = (Argument) arguments [i];
2158
2159                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2160                                         continue;
2161
2162                                 if (!InferType (element_type, a.Type, infered_types))
2163                                         return false;
2164                         }
2165
2166                         for (int i = 0; i < infered_types.Length; i++)
2167                                 if (infered_types [i] == null)
2168                                         return false;
2169
2170                         method = method.BindGenericParameters (infered_types);
2171                         return true;
2172                 }
2173
2174                 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
2175                 {
2176                         if (infered_types == null)
2177                                 return false;
2178
2179                         for (int i = 0; i < arg_types.Length; i++) {
2180                                 if (arg_types [i] == null)
2181                                         continue;
2182
2183                                 if (!InferType (param_types [i], arg_types [i], infered_types))
2184                                         return false;
2185                         }
2186
2187                         for (int i = 0; i < infered_types.Length; i++)
2188                                 if (infered_types [i] == null)
2189                                         return false;
2190
2191                         return true;
2192                 }
2193
2194                 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2195                                                        ref MethodBase method)
2196                 {
2197                         if (!TypeManager.IsGenericMethod (method))
2198                                 return true;
2199
2200                         int arg_count;
2201                         if (arguments != null)
2202                                 arg_count = arguments.Count;
2203                         else
2204                                 arg_count = 0;
2205
2206                         ParameterData pd = TypeManager.GetParameterData (method);
2207                         if (arg_count != pd.Count)
2208                                 return false;
2209
2210                         Type[] method_args = method.GetGenericArguments ();
2211
2212                         bool is_open = false;
2213                         for (int i = 0; i < method_args.Length; i++) {
2214                                 if (method_args [i].IsGenericParameter) {
2215                                         is_open = true;
2216                                         break;
2217                                 }
2218                         }
2219                         if (!is_open)
2220                                 return true;
2221
2222                         Type[] infered_types = new Type [method_args.Length];
2223
2224                         Type[] param_types = new Type [pd.Count];
2225                         Type[] arg_types = new Type [pd.Count];
2226
2227                         for (int i = 0; i < arg_count; i++) {
2228                                 param_types [i] = pd.ParameterType (i);
2229
2230                                 Argument a = (Argument) arguments [i];
2231                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2232                                         continue;
2233
2234                                 arg_types [i] = a.Type;
2235                         }
2236
2237                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2238                                 return false;
2239
2240                         method = method.BindGenericParameters (infered_types);
2241                         return true;
2242                 }
2243
2244                 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2245                                                        ref MethodBase method)
2246                 {
2247                         if (!TypeManager.IsGenericMethod (method))
2248                                 return true;
2249
2250                         ParameterData pd = TypeManager.GetParameterData (method);
2251                         if (apd.Count != pd.Count)
2252                                 return false;
2253
2254                         Type[] method_args = method.GetGenericArguments ();
2255                         Type[] infered_types = new Type [method_args.Length];
2256
2257                         Type[] param_types = new Type [pd.Count];
2258                         Type[] arg_types = new Type [pd.Count];
2259
2260                         for (int i = 0; i < apd.Count; i++) {
2261                                 param_types [i] = pd.ParameterType (i);
2262                                 arg_types [i] = apd.ParameterType (i);
2263                         }
2264
2265                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2266                                 return false;
2267
2268                         method = method.BindGenericParameters (infered_types);
2269                         return true;
2270                 }
2271
2272                 public static bool IsNullableType (Type t)
2273                 {
2274                         if (!t.IsGenericInstance)
2275                                 return false;
2276
2277                         Type gt = t.GetGenericTypeDefinition ();
2278                         return gt == generic_nullable_type;
2279                 }
2280         }
2281
2282         public abstract class Nullable
2283         {
2284                 protected sealed class NullableInfo
2285                 {
2286                         public readonly Type Type;
2287                         public readonly Type UnderlyingType;
2288                         public readonly MethodInfo HasValue;
2289                         public readonly MethodInfo Value;
2290                         public readonly ConstructorInfo Constructor;
2291
2292                         public NullableInfo (Type type)
2293                         {
2294                                 Type = type;
2295                                 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2296
2297                                 PropertyInfo has_value_pi = type.GetProperty ("HasValue");
2298                                 PropertyInfo value_pi = type.GetProperty ("Value");
2299
2300                                 HasValue = has_value_pi.GetGetMethod (false);
2301                                 Value = value_pi.GetGetMethod (false);
2302                                 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2303                         }
2304                 }
2305
2306                 protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
2307                 {
2308                         Expression expr;
2309                         NullableInfo info;
2310
2311                         LocalTemporary temp;
2312                         bool has_temp;
2313
2314                         public Unwrap (Expression expr, Location loc)
2315                         {
2316                                 this.expr = expr;
2317                                 this.loc = loc;
2318                         }
2319
2320                         public override Expression DoResolve (EmitContext ec)
2321                         {
2322                                 expr = expr.Resolve (ec);
2323                                 if (expr == null)
2324                                         return null;
2325
2326                                 if (!(expr is IMemoryLocation))
2327                                         temp = new LocalTemporary (ec, expr.Type);
2328
2329                                 info = new NullableInfo (expr.Type);
2330                                 type = info.UnderlyingType;
2331                                 eclass = expr.eclass;
2332                                 return this;
2333                         }
2334
2335                         public override void Emit (EmitContext ec)
2336                         {
2337                                 AddressOf (ec, AddressOp.LoadStore);
2338                                 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2339                         }
2340
2341                         public void EmitCheck (EmitContext ec)
2342                         {
2343                                 AddressOf (ec, AddressOp.LoadStore);
2344                                 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2345                         }
2346
2347                         void create_temp (EmitContext ec)
2348                         {
2349                                 if ((temp != null) && !has_temp) {
2350                                         expr.Emit (ec);
2351                                         temp.Store (ec);
2352                                         has_temp = true;
2353                                 }
2354                         }
2355
2356                         public void AddressOf (EmitContext ec, AddressOp mode)
2357                         {
2358                                 create_temp (ec);
2359                                 if (temp != null)
2360                                         temp.AddressOf (ec, AddressOp.LoadStore);
2361                                 else
2362                                         ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2363                         }
2364
2365                         public void Emit (EmitContext ec, bool leave_copy)
2366                         {
2367                                 create_temp (ec);
2368                                 if (leave_copy) {
2369                                         if (temp != null)
2370                                                 temp.Emit (ec);
2371                                         else
2372                                                 expr.Emit (ec);
2373                                 }
2374
2375                                 Emit (ec);
2376                         }
2377
2378                         public void EmitAssign (EmitContext ec, Expression source,
2379                                                 bool leave_copy, bool prepare_for_load)
2380                         {
2381                                 source.Emit (ec);
2382                                 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2383
2384                                 if (leave_copy)
2385                                         ec.ig.Emit (OpCodes.Dup);
2386
2387                                 Expression empty = new EmptyExpression (expr.Type);
2388                                 ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
2389                         }
2390                 }
2391
2392                 protected class Wrap : Expression
2393                 {
2394                         Expression expr;
2395                         NullableInfo info;
2396
2397                         public Wrap (Expression expr, Location loc)
2398                         {
2399                                 this.expr = expr;
2400                                 this.loc = loc;
2401                         }
2402
2403                         public override Expression DoResolve (EmitContext ec)
2404                         {
2405                                 expr = expr.Resolve (ec);
2406                                 if (expr == null)
2407                                         return null;
2408
2409                                 TypeExpr target_type = new NullableType (expr.Type, loc);
2410                                 target_type = target_type.ResolveAsTypeTerminal (ec);
2411                                 if (target_type == null)
2412                                         return null;
2413
2414                                 type = target_type.Type;
2415                                 info = new NullableInfo (type);
2416                                 eclass = ExprClass.Value;
2417                                 return this;
2418                         }
2419
2420                         public override void Emit (EmitContext ec)
2421                         {
2422                                 expr.Emit (ec);
2423                                 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2424                         }
2425                 }
2426
2427                 public class NullableLiteral : Expression, IMemoryLocation {
2428                         public NullableLiteral (Type target_type, Location loc)
2429                         {
2430                                 this.type = target_type;
2431                                 this.loc = loc;
2432
2433                                 eclass = ExprClass.Value;
2434                         }
2435                 
2436                         public override Expression DoResolve (EmitContext ec)
2437                         {
2438                                 return this;
2439                         }
2440
2441                         public override void Emit (EmitContext ec)
2442                         {
2443                                 LocalTemporary value_target = new LocalTemporary (ec, type);
2444
2445                                 value_target.AddressOf (ec, AddressOp.Store);
2446                                 ec.ig.Emit (OpCodes.Initobj, type);
2447                                 value_target.Emit (ec);
2448                         }
2449
2450                         public void AddressOf (EmitContext ec, AddressOp Mode)
2451                         {
2452                                 LocalTemporary value_target = new LocalTemporary (ec, type);
2453                                         
2454                                 value_target.AddressOf (ec, AddressOp.Store);
2455                                 ec.ig.Emit (OpCodes.Initobj, type);
2456                                 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2457                         }
2458                 }
2459
2460                 public abstract class Lifted : Expression, IMemoryLocation
2461                 {
2462                         Expression expr, underlying, wrap, null_value;
2463                         Unwrap unwrap;
2464
2465                         protected Lifted (Expression expr, Location loc)
2466                         {
2467                                 this.expr = expr;
2468                                 this.loc = loc;
2469                         }
2470
2471                         public override Expression DoResolve (EmitContext ec)
2472                         {
2473                                 expr = expr.Resolve (ec);
2474                                 if (expr == null)
2475                                         return null;
2476
2477                                 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
2478                                 if (unwrap == null)
2479                                         return null;
2480
2481                                 underlying = ResolveUnderlying (unwrap, ec);
2482                                 if (underlying == null)
2483                                         return null;
2484
2485                                 wrap = new Wrap (underlying, loc).Resolve (ec);
2486                                 if (wrap == null)
2487                                         return null;
2488
2489                                 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2490                                 if (null_value == null)
2491                                         return null;
2492
2493                                 type = wrap.Type;
2494                                 eclass = ExprClass.Value;
2495                                 return this;
2496                         }
2497
2498                         protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2499
2500                         public override void Emit (EmitContext ec)
2501                         {
2502                                 ILGenerator ig = ec.ig;
2503                                 Label is_null_label = ig.DefineLabel ();
2504                                 Label end_label = ig.DefineLabel ();
2505
2506                                 unwrap.EmitCheck (ec);
2507                                 ig.Emit (OpCodes.Brfalse, is_null_label);
2508
2509                                 wrap.Emit (ec);
2510                                 ig.Emit (OpCodes.Br, end_label);
2511
2512                                 ig.MarkLabel (is_null_label);
2513                                 null_value.Emit (ec);
2514
2515                                 ig.MarkLabel (end_label);
2516                         }
2517
2518                         public void AddressOf (EmitContext ec, AddressOp mode)
2519                         {
2520                                 unwrap.AddressOf (ec, mode);
2521                         }
2522                 }
2523
2524                 public class LiftedConversion : Lifted
2525                 {
2526                         public readonly bool IsUser;
2527                         public readonly bool IsExplicit;
2528                         public readonly Type TargetType;
2529
2530                         public LiftedConversion (Expression expr, Type target_type, bool is_user,
2531                                                  bool is_explicit, Location loc)
2532                                 : base (expr, loc)
2533                         {
2534                                 this.IsUser = is_user;
2535                                 this.IsExplicit = is_explicit;
2536                                 this.TargetType = target_type;
2537                         }
2538
2539                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2540                         {
2541                                 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2542
2543                                 if (IsUser) {
2544                                         return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2545                                 } else {
2546                                         if (IsExplicit)
2547                                                 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2548                                         else
2549                                                 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2550                                 }
2551                         }
2552                 }
2553
2554                 public class LiftedUnaryOperator : Lifted
2555                 {
2556                         public readonly Unary.Operator Oper;
2557
2558                         public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2559                                 : base (expr, loc)
2560                         {
2561                                 this.Oper = op;
2562                         }
2563
2564                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2565                         {
2566                                 return new Unary (Oper, unwrap, loc);
2567                         }
2568                 }
2569
2570                 public class LiftedConditional : Lifted
2571                 {
2572                         Expression expr, true_expr, false_expr;
2573                         Unwrap unwrap;
2574
2575                         public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2576                                                   Location loc)
2577                                 : base (expr, loc)
2578                         {
2579                                 this.true_expr = true_expr;
2580                                 this.false_expr = false_expr;
2581                         }
2582
2583                         protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2584                         {
2585                                 return new Conditional (unwrap, true_expr, false_expr, loc);
2586                         }
2587                 }
2588
2589                 public class LiftedBinaryOperator : Expression
2590                 {
2591                         public readonly Binary.Operator Oper;
2592
2593                         Expression left, right, underlying, null_value, bool_wrap;
2594                         Unwrap left_unwrap, right_unwrap;
2595                         bool is_equality, is_comparision, is_boolean;
2596
2597                         public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2598                                                      Location loc)
2599                         {
2600                                 this.Oper = op;
2601                                 this.left = left;
2602                                 this.right = right;
2603                                 this.loc = loc;
2604                         }
2605
2606                         public override Expression DoResolve (EmitContext ec)
2607                         {
2608                                 if (TypeManager.IsNullableType (left.Type)) {
2609                                         left_unwrap = new Unwrap (left, loc);
2610                                         left = left_unwrap.Resolve (ec);
2611                                         if (left == null)
2612                                                 return null;
2613                                 }
2614
2615                                 if (TypeManager.IsNullableType (right.Type)) {
2616                                         right_unwrap = new Unwrap (right, loc);
2617                                         right = right_unwrap.Resolve (ec);
2618                                         if (right == null)
2619                                                 return null;
2620                                 }
2621
2622                                 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
2623                                      (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
2624                                     ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2625                                         Expression empty = new EmptyExpression (TypeManager.bool_type);
2626                                         bool_wrap = new Wrap (empty, loc).Resolve (ec);
2627                                         null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2628
2629                                         type = bool_wrap.Type;
2630                                         is_boolean = true;
2631                                 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2632                                         if (!(left is NullLiteral) && !(right is NullLiteral)) {
2633                                                 underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2634                                                 if (underlying == null)
2635                                                         return null;
2636                                         }
2637
2638                                         type = TypeManager.bool_type;
2639                                         is_equality = true;
2640                                 } else if ((Oper == Binary.Operator.LessThan) ||
2641                                            (Oper == Binary.Operator.GreaterThan) ||
2642                                            (Oper == Binary.Operator.LessThanOrEqual) ||
2643                                            (Oper == Binary.Operator.GreaterThanOrEqual)) {
2644                                         underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2645                                         if (underlying == null)
2646                                                 return null;
2647
2648                                         type = TypeManager.bool_type;
2649                                         is_comparision = true;
2650                                 } else {
2651                                         underlying = new Binary (Oper, left, right, loc).Resolve (ec);
2652                                         if (underlying == null)
2653                                                 return null;
2654
2655                                         underlying = new Wrap (underlying, loc).Resolve (ec);
2656                                         if (underlying == null)
2657                                                 return null;
2658
2659                                         type = underlying.Type;
2660                                         null_value = new NullableLiteral (type, loc).Resolve (ec);
2661                                 }
2662
2663                                 eclass = ExprClass.Value;
2664                                 return this;
2665                         }
2666
2667                         void EmitBoolean (EmitContext ec)
2668                         {
2669                                 ILGenerator ig = ec.ig;
2670
2671                                 Label left_is_null_label = ig.DefineLabel ();
2672                                 Label right_is_null_label = ig.DefineLabel ();
2673                                 Label is_null_label = ig.DefineLabel ();
2674                                 Label wrap_label = ig.DefineLabel ();
2675                                 Label end_label = ig.DefineLabel ();
2676
2677                                 if (left_unwrap != null) {
2678                                         left_unwrap.EmitCheck (ec);
2679                                         ig.Emit (OpCodes.Brfalse, left_is_null_label);
2680                                 }
2681
2682                                 left.Emit (ec);
2683                                 ig.Emit (OpCodes.Dup);
2684                                 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2685                                         ig.Emit (OpCodes.Brtrue, wrap_label);
2686                                 else
2687                                         ig.Emit (OpCodes.Brfalse, wrap_label);
2688
2689                                 if (right_unwrap != null) {
2690                                         right_unwrap.EmitCheck (ec);
2691                                         ig.Emit (OpCodes.Brfalse, right_is_null_label);
2692                                 }
2693
2694                                 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2695                                         ig.Emit (OpCodes.Pop);
2696
2697                                 right.Emit (ec);
2698                                 if (Oper == Binary.Operator.BitwiseOr)
2699                                         ig.Emit (OpCodes.Or);
2700                                 else if (Oper == Binary.Operator.BitwiseAnd)
2701                                         ig.Emit (OpCodes.And);
2702                                 ig.Emit (OpCodes.Br, wrap_label);
2703
2704                                 ig.MarkLabel (left_is_null_label);
2705                                 if (right_unwrap != null) {
2706                                         right_unwrap.EmitCheck (ec);
2707                                         ig.Emit (OpCodes.Brfalse, is_null_label);
2708                                 }
2709
2710                                 right.Emit (ec);
2711                                 ig.Emit (OpCodes.Dup);
2712                                 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2713                                         ig.Emit (OpCodes.Brtrue, wrap_label);
2714                                 else
2715                                         ig.Emit (OpCodes.Brfalse, wrap_label);
2716
2717                                 ig.MarkLabel (right_is_null_label);
2718                                 ig.Emit (OpCodes.Pop);
2719                                 ig.MarkLabel (is_null_label);
2720                                 null_value.Emit (ec);
2721                                 ig.Emit (OpCodes.Br, end_label);
2722
2723                                 ig.MarkLabel (wrap_label);
2724                                 ig.Emit (OpCodes.Nop);
2725                                 bool_wrap.Emit (ec);
2726                                 ig.Emit (OpCodes.Nop);
2727
2728                                 ig.MarkLabel (end_label);
2729                         }
2730
2731                         void EmitEquality (EmitContext ec)
2732                         {
2733                                 ILGenerator ig = ec.ig;
2734
2735                                 Label left_not_null_label = ig.DefineLabel ();
2736                                 Label false_label = ig.DefineLabel ();
2737                                 Label true_label = ig.DefineLabel ();
2738                                 Label end_label = ig.DefineLabel ();
2739
2740                                 if (left_unwrap != null) {
2741                                         left_unwrap.EmitCheck (ec);
2742                                         if (right is NullLiteral) {
2743                                                 if (Oper == Binary.Operator.Equality)
2744                                                         ig.Emit (OpCodes.Brfalse, true_label);
2745                                                 else
2746                                                         ig.Emit (OpCodes.Brfalse, false_label);
2747                                         } else if (right_unwrap != null) {
2748                                                 ig.Emit (OpCodes.Dup);
2749                                                 ig.Emit (OpCodes.Brtrue, left_not_null_label);
2750                                                 right_unwrap.EmitCheck (ec);
2751                                                 ig.Emit (OpCodes.Ceq);
2752                                                 if (Oper == Binary.Operator.Inequality) {
2753                                                         ig.Emit (OpCodes.Ldc_I4_0);
2754                                                         ig.Emit (OpCodes.Ceq);
2755                                                 }
2756                                                 ig.Emit (OpCodes.Br, end_label);
2757
2758                                                 ig.MarkLabel (left_not_null_label);
2759                                                 ig.Emit (OpCodes.Pop);
2760                                         } else {
2761                                                 if (Oper == Binary.Operator.Equality)
2762                                                         ig.Emit (OpCodes.Brfalse, false_label);
2763                                                 else
2764                                                         ig.Emit (OpCodes.Brfalse, true_label);
2765                                         }
2766                                 }
2767
2768                                 if (right_unwrap != null) {
2769                                         right_unwrap.EmitCheck (ec);
2770                                         if (left is NullLiteral) {
2771                                                 if (Oper == Binary.Operator.Equality)
2772                                                         ig.Emit (OpCodes.Brfalse, true_label);
2773                                                 else
2774                                                         ig.Emit (OpCodes.Brfalse, false_label);
2775                                         } else {
2776                                                 if (Oper == Binary.Operator.Equality)
2777                                                         ig.Emit (OpCodes.Brfalse, false_label);
2778                                                 else
2779                                                         ig.Emit (OpCodes.Brfalse, true_label);
2780                                         }
2781                                 }
2782
2783                                 bool left_is_null = left is NullLiteral;
2784                                 bool right_is_null = right is NullLiteral;
2785                                 if (left_is_null || right_is_null) {
2786                                         if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
2787                                             ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null)))
2788                                                 ig.Emit (OpCodes.Br, true_label);
2789                                         else
2790                                                 ig.Emit (OpCodes.Br, false_label);
2791                                 } else {
2792                                         underlying.Emit (ec);
2793                                         ig.Emit (OpCodes.Br, end_label);
2794                                 }
2795
2796                                 ig.MarkLabel (false_label);
2797                                 ig.Emit (OpCodes.Ldc_I4_0);
2798                                 ig.Emit (OpCodes.Br, end_label);
2799
2800                                 ig.MarkLabel (true_label);
2801                                 ig.Emit (OpCodes.Ldc_I4_1);
2802
2803                                 ig.MarkLabel (end_label);
2804                         }
2805
2806                         void EmitComparision (EmitContext ec)
2807                         {
2808                                 ILGenerator ig = ec.ig;
2809
2810                                 Label is_null_label = ig.DefineLabel ();
2811                                 Label end_label = ig.DefineLabel ();
2812
2813                                 if (left_unwrap != null) {
2814                                         left_unwrap.EmitCheck (ec);
2815                                         ig.Emit (OpCodes.Brfalse, is_null_label);
2816                                 }
2817
2818                                 if (right_unwrap != null) {
2819                                         right_unwrap.EmitCheck (ec);
2820                                         ig.Emit (OpCodes.Brfalse, is_null_label);
2821                                 }
2822
2823                                 underlying.Emit (ec);
2824                                 ig.Emit (OpCodes.Br, end_label);
2825
2826                                 ig.MarkLabel (is_null_label);
2827                                 ig.Emit (OpCodes.Ldc_I4_0);
2828
2829                                 ig.MarkLabel (end_label);
2830                         }
2831
2832                         public override void Emit (EmitContext ec)
2833                         {
2834                                 if (is_boolean) {
2835                                         EmitBoolean (ec);
2836                                         return;
2837                                 } else if (is_equality) {
2838                                         EmitEquality (ec);
2839                                         return;
2840                                 } else if (is_comparision) {
2841                                         EmitComparision (ec);
2842                                         return;
2843                                 }
2844
2845                                 ILGenerator ig = ec.ig;
2846
2847                                 Label is_null_label = ig.DefineLabel ();
2848                                 Label end_label = ig.DefineLabel ();
2849
2850                                 if (left_unwrap != null) {
2851                                         left_unwrap.EmitCheck (ec);
2852                                         ig.Emit (OpCodes.Brfalse, is_null_label);
2853                                 }
2854
2855                                 if (right_unwrap != null) {
2856                                         right_unwrap.EmitCheck (ec);
2857                                         ig.Emit (OpCodes.Brfalse, is_null_label);
2858                                 }
2859
2860                                 underlying.Emit (ec);
2861                                 ig.Emit (OpCodes.Br, end_label);
2862
2863                                 ig.MarkLabel (is_null_label);
2864                                 null_value.Emit (ec);
2865
2866                                 ig.MarkLabel (end_label);
2867                         }
2868                 }
2869
2870                 public class OperatorTrueOrFalse : Expression
2871                 {
2872                         public readonly bool IsTrue;
2873
2874                         Expression expr;
2875                         Unwrap unwrap;
2876
2877                         public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
2878                         {
2879                                 this.IsTrue = is_true;
2880                                 this.expr = expr;
2881                                 this.loc = loc;
2882                         }
2883
2884                         public override Expression DoResolve (EmitContext ec)
2885                         {
2886                                 unwrap = new Unwrap (expr, loc);
2887                                 expr = unwrap.Resolve (ec);
2888                                 if (expr == null)
2889                                         return null;
2890
2891                                 if (unwrap.Type != TypeManager.bool_type)
2892                                         return null;
2893
2894                                 type = TypeManager.bool_type;
2895                                 eclass = ExprClass.Value;
2896                                 return this;
2897                         }
2898
2899                         public override void Emit (EmitContext ec)
2900                         {
2901                                 ILGenerator ig = ec.ig;
2902
2903                                 Label is_null_label = ig.DefineLabel ();
2904                                 Label end_label = ig.DefineLabel ();
2905
2906                                 unwrap.EmitCheck (ec);
2907                                 ig.Emit (OpCodes.Brfalse, is_null_label);
2908
2909                                 unwrap.Emit (ec);
2910                                 if (!IsTrue) {
2911                                         ig.Emit (OpCodes.Ldc_I4_0);
2912                                         ig.Emit (OpCodes.Ceq);
2913                                 }
2914                                 ig.Emit (OpCodes.Br, end_label);
2915
2916                                 ig.MarkLabel (is_null_label);
2917                                 ig.Emit (OpCodes.Ldc_I4_0);
2918
2919                                 ig.MarkLabel (end_label);
2920                         }
2921                 }
2922
2923                 public class NullCoalescingOperator : Expression
2924                 {
2925                         Expression left, right;
2926                         Expression expr;
2927                         Unwrap unwrap;
2928
2929                         public NullCoalescingOperator (Expression left, Expression right, Location loc)
2930                         {
2931                                 this.left = left;
2932                                 this.right = right;
2933                                 this.loc = loc;
2934
2935                                 eclass = ExprClass.Value;
2936                         }
2937
2938                         public override Expression DoResolve (EmitContext ec)
2939                         {
2940                                 if (type != null)
2941                                         return this;
2942
2943                                 left = left.Resolve (ec);
2944                                 if (left == null)
2945                                         return null;
2946
2947                                 right = right.Resolve (ec);
2948                                 if (right == null)
2949                                         return null;
2950
2951                                 Type ltype = left.Type, rtype = right.Type;
2952
2953                                 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
2954                                         Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
2955                                         return null;
2956                                 }
2957
2958                                 if (TypeManager.IsNullableType (ltype)) {
2959                                         NullableInfo info = new NullableInfo (ltype);
2960
2961                                         unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
2962                                         if (unwrap == null)
2963                                                 return null;
2964
2965                                         expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
2966                                         if (expr != null) {
2967                                                 left = unwrap;
2968                                                 type = expr.Type;
2969                                                 return this;
2970                                         }
2971                                 }
2972
2973                                 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
2974                                 if (expr != null) {
2975                                         type = expr.Type;
2976                                         return this;
2977                                 }
2978
2979                                 if (unwrap != null) {
2980                                         expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
2981                                         if (expr != null) {
2982                                                 left = expr;
2983                                                 expr = right;
2984                                                 type = expr.Type;
2985                                                 return this;
2986                                         }
2987                                 }
2988
2989                                 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
2990                                 return null;
2991                         }
2992
2993                         public override void Emit (EmitContext ec)
2994                         {
2995                                 ILGenerator ig = ec.ig;
2996
2997                                 Label is_null_label = ig.DefineLabel ();
2998                                 Label end_label = ig.DefineLabel ();
2999
3000                                 if (unwrap != null) {
3001                                         unwrap.EmitCheck (ec);
3002                                         ig.Emit (OpCodes.Brfalse, is_null_label);
3003                                 }
3004
3005                                 left.Emit (ec);
3006                                 ig.Emit (OpCodes.Br, end_label);
3007
3008                                 ig.MarkLabel (is_null_label);
3009                                 expr.Emit (ec);
3010
3011                                 ig.MarkLabel (end_label);
3012                         }
3013                 }
3014
3015                 public class LiftedUnaryMutator : ExpressionStatement
3016                 {
3017                         public readonly UnaryMutator.Mode Mode;
3018                         Expression expr, null_value;
3019                         UnaryMutator underlying;
3020                         Unwrap unwrap;
3021
3022                         public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3023                         {
3024                                 this.expr = expr;
3025                                 this.Mode = mode;
3026                                 this.loc = loc;
3027
3028                                 eclass = ExprClass.Value;
3029                         }
3030
3031                         public override Expression DoResolve (EmitContext ec)
3032                         {
3033                                 expr = expr.Resolve (ec);
3034                                 if (expr == null)
3035                                         return null;
3036
3037                                 unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
3038                                 if (unwrap == null)
3039                                         return null;
3040
3041                                 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3042                                 if (underlying == null)
3043                                         return null;
3044
3045                                 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3046                                 if (null_value == null)
3047                                         return null;
3048
3049                                 type = expr.Type;
3050                                 return this;
3051                         }
3052
3053                         void DoEmit (EmitContext ec, bool is_expr)
3054                         {
3055                                 ILGenerator ig = ec.ig;
3056                                 Label is_null_label = ig.DefineLabel ();
3057                                 Label end_label = ig.DefineLabel ();
3058
3059                                 unwrap.EmitCheck (ec);
3060                                 ig.Emit (OpCodes.Brfalse, is_null_label);
3061
3062                                 if (is_expr)
3063                                         underlying.Emit (ec);
3064                                 else
3065                                         underlying.EmitStatement (ec);
3066                                 ig.Emit (OpCodes.Br, end_label);
3067
3068                                 ig.MarkLabel (is_null_label);
3069                                 if (is_expr)
3070                                         null_value.Emit (ec);
3071
3072                                 ig.MarkLabel (end_label);
3073                         }
3074
3075                         public override void Emit (EmitContext ec)
3076                         {
3077                                 DoEmit (ec, true);
3078                         }
3079
3080                         public override void EmitStatement (EmitContext ec)
3081                         {
3082                                 DoEmit (ec, false);
3083                         }
3084                 }
3085         }
3086 }