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