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