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