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