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