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