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