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