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