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