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