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