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