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