2005-02-22 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / gmcs / generic.cs
1 //
2 // generic.cs: Generics support
3 //
4 // Authors: Martin Baulig (martin@ximian.com)
5 //          Miguel de Icaza (miguel@ximian.com)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
11 //
12 using System;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
17 using System.Text;
18 using System.Text.RegularExpressions;
19         
20 namespace Mono.CSharp {
21
22         public abstract class GenericConstraints {
23                 public abstract GenericParameterAttributes Attributes {
24                         get;
25                 }
26
27                 public bool HasConstructorConstraint {
28                         get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
29                 }
30
31                 public bool HasReferenceTypeConstraint {
32                         get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
33                 }
34
35                 public bool HasValueTypeConstraint {
36                         get { return (Attributes & GenericParameterAttributes.ValueTypeConstraint) != 0; }
37                 }
38
39                 public virtual bool HasClassConstraint {
40                         get { return ClassConstraint != null; }
41                 }
42
43                 public abstract Type ClassConstraint {
44                         get;
45                 }
46
47                 public abstract Type[] InterfaceConstraints {
48                         get;
49                 }
50
51                 public abstract Type EffectiveBaseClass {
52                         get;
53                 }
54
55                 // <summary>
56                 //   Returns whether the type parameter is "known to be a reference type".
57                 // </summary>
58                 public virtual bool IsReferenceType {
59                         get {
60                                 if (HasReferenceTypeConstraint)
61                                         return true;
62                                 if (HasValueTypeConstraint)
63                                         return false;
64
65                                 if (ClassConstraint != null) {
66                                         if (ClassConstraint.IsValueType)
67                                                 return false;
68
69                                         if (ClassConstraint != TypeManager.object_type)
70                                                 return true;
71                                 }
72
73                                 foreach (Type t in InterfaceConstraints) {
74                                         if (!t.IsGenericParameter)
75                                                 continue;
76
77                                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
78                                         if ((gc != null) && gc.IsReferenceType)
79                                                 return true;
80                                 }
81
82                                 return false;
83                         }
84                 }
85
86                 // <summary>
87                 //   Returns whether the type parameter is "known to be a value type".
88                 // </summary>
89                 public virtual bool IsValueType {
90                         get {
91                                 if (HasValueTypeConstraint)
92                                         return true;
93                                 if (HasReferenceTypeConstraint)
94                                         return false;
95
96                                 if (ClassConstraint != null) {
97                                         if (!ClassConstraint.IsValueType)
98                                                 return false;
99
100                                         if (ClassConstraint != TypeManager.value_type)
101                                                 return true;
102                                 }
103
104                                 foreach (Type t in InterfaceConstraints) {
105                                         if (!t.IsGenericParameter)
106                                                 continue;
107
108                                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
109                                         if ((gc != null) && gc.IsValueType)
110                                                 return true;
111                                 }
112
113                                 return false;
114                         }
115                 }
116         }
117
118         public enum SpecialConstraint
119         {
120                 Constructor,
121                 ReferenceType,
122                 ValueType
123         }
124
125         //
126         // Tracks the constraints for a type parameter
127         //
128         public class Constraints : GenericConstraints {
129                 string name;
130                 ArrayList constraints;
131                 Location loc;
132                 
133                 //
134                 // name is the identifier, constraints is an arraylist of
135                 // Expressions (with types) or `true' for the constructor constraint.
136                 // 
137                 public Constraints (string name, ArrayList constraints,
138                                     Location loc)
139                 {
140                         this.name = name;
141                         this.constraints = constraints;
142                         this.loc = loc;
143                 }
144
145                 public string TypeParameter {
146                         get {
147                                 return name;
148                         }
149                 }
150
151                 GenericParameterAttributes attrs;
152                 TypeExpr class_constraint;
153                 ArrayList iface_constraints;
154                 ArrayList type_param_constraints;
155                 int num_constraints, first_constraint;
156                 Type class_constraint_type;
157                 Type[] iface_constraint_types;
158                 Type effective_base_type;
159
160                 public bool Resolve (EmitContext ec)
161                 {
162                         iface_constraints = new ArrayList ();
163                         type_param_constraints = new ArrayList ();
164
165                         foreach (object obj in constraints) {
166                                 if (HasConstructorConstraint) {
167                                         Report.Error (401, loc,
168                                                       "The new() constraint must be last.");
169                                         return false;
170                                 }
171
172                                 if (obj is SpecialConstraint) {
173                                         SpecialConstraint sc = (SpecialConstraint) obj;
174
175                                         if (sc == SpecialConstraint.Constructor) {
176                                                 if (!HasValueTypeConstraint) {
177                                                         attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
178                                                         continue;
179                                                 }
180
181                                                 Report.Error (
182                                                         451, loc, "The new () constraint " +
183                                                         "cannot be used with the `struct' " +
184                                                         "constraint.");
185                                                 return false;
186                                         }
187
188                                         if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
189                                                 Report.Error (449, loc,
190                                                               "The `class' or `struct' " +
191                                                               "constraint must be first");
192                                                 return false;
193                                         }
194
195                                         if (sc == SpecialConstraint.ReferenceType)
196                                                 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
197                                         else
198                                                 attrs |= GenericParameterAttributes.ValueTypeConstraint;
199                                         continue;
200                                 }
201
202                                 TypeExpr expr;
203                                 if (obj is ConstructedType) {
204                                         ConstructedType cexpr = (ConstructedType) obj;
205                                         if (!cexpr.ResolveConstructedType (ec))
206                                                 return false;
207                                         expr = cexpr;
208                                 } else
209                                         expr = ((Expression) obj).ResolveAsTypeTerminal (ec);
210
211                                 if (expr == null)
212                                         return false;
213
214                                 TypeParameterExpr texpr = expr as TypeParameterExpr;
215                                 if (texpr != null)
216                                         type_param_constraints.Add (expr);
217                                 else if (expr.IsInterface)
218                                         iface_constraints.Add (expr);
219                                 else if (class_constraint != null) {
220                                         Report.Error (406, loc,
221                                                       "`{0}': the class constraint for `{1}' " +
222                                                       "must come before any other constraints.",
223                                                       expr.Name, name);
224                                         return false;
225                                 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
226                                         Report.Error (450, loc, "`{0}': cannot specify both " +
227                                                       "a constraint class and the `class' " +
228                                                       "or `struct' constraint.", expr.Name);
229                                         return false;
230                                 } else
231                                         class_constraint = expr;
232
233                                 num_constraints++;
234                         }
235
236                         return true;
237                 }
238
239                 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
240                 {
241                         seen.Add (tparam, true);
242
243                         Constraints constraints = tparam.Constraints;
244                         if (constraints == null)
245                                 return true;
246
247                         if (constraints.HasValueTypeConstraint) {
248                                 Report.Error (456, loc, "Type parameter `{0}' has " +
249                                               "the `struct' constraint, so it cannot " +
250                                               "be used as a constraint for `{1}'",
251                                               tparam.Name, name);
252                                 return false;
253                         }
254
255                         if (constraints.type_param_constraints == null)
256                                 return true;
257
258                         foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
259                                 if (seen.Contains (expr.TypeParameter)) {
260                                         Report.Error (454, loc, "Circular constraint " +
261                                                       "dependency involving `{0}' and `{1}'",
262                                                       tparam.Name, expr.Name);
263                                         return false;
264                                 }
265
266                                 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
267                                         return false;
268                         }
269
270                         return true;
271                 }
272
273                 public bool ResolveTypes (EmitContext ec)
274                 {
275                         if (effective_base_type != null)
276                                 return true;
277
278                         foreach (object obj in constraints) {
279                                 ConstructedType cexpr = obj as ConstructedType;
280                                 if (cexpr == null)
281                                         continue;
282
283                                 if (!cexpr.CheckConstraints (ec))
284                                         return false;
285                         }
286
287                         foreach (TypeParameterExpr expr in type_param_constraints) {
288                                 Hashtable seen = new Hashtable ();
289                                 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
290                                         return false;
291                         }
292
293                         ArrayList list = new ArrayList ();
294
295                         foreach (TypeExpr iface_constraint in iface_constraints) {
296                                 foreach (Type type in list) {
297                                         if (!type.Equals (iface_constraint.Type))
298                                                 continue;
299
300                                         Report.Error (405, loc,
301                                                       "Duplicate constraint `{0}' for type " +
302                                                       "parameter `{1}'.", iface_constraint.Type,
303                                                       name);
304                                         return false;
305                                 }
306
307                                 list.Add (iface_constraint.Type);
308                         }
309
310                         foreach (TypeParameterExpr expr in type_param_constraints) {
311                                 foreach (Type type in list) {
312                                         if (!type.Equals (expr.Type))
313                                                 continue;
314
315                                         Report.Error (405, loc,
316                                                       "Duplicate constraint `{0}' for type " +
317                                                       "parameter `{1}'.", expr.Type, name);
318                                         return false;
319                                 }
320
321                                 list.Add (expr.Type);
322                         }
323
324                         iface_constraint_types = new Type [list.Count];
325                         list.CopyTo (iface_constraint_types, 0);
326
327                         if (class_constraint != null) {
328                                 class_constraint_type = class_constraint.Type;
329                                 if (class_constraint_type == null)
330                                         return false;
331
332                                 if (class_constraint_type.IsSealed) {
333                                         Report.Error (701, loc,
334                                                       "`{0}' is not a valid bound.  Bounds " +
335                                                       "must be interfaces or non sealed " +
336                                                       "classes", class_constraint_type);
337                                         return false;
338                                 }
339
340                                 if ((class_constraint_type == TypeManager.array_type) ||
341                                     (class_constraint_type == TypeManager.delegate_type) ||
342                                     (class_constraint_type == TypeManager.enum_type) ||
343                                     (class_constraint_type == TypeManager.value_type) ||
344                                     (class_constraint_type == TypeManager.object_type)) {
345                                         Report.Error (702, loc,
346                                                       "Bound cannot be special class `{0}'",
347                                                       class_constraint_type);
348                                         return false;
349                                 }
350                         }
351
352                         if (class_constraint_type != null)
353                                 effective_base_type = class_constraint_type;
354                         else if (HasValueTypeConstraint)
355                                 effective_base_type = TypeManager.value_type;
356                         else
357                                 effective_base_type = TypeManager.object_type;
358
359                         return true;
360                 }
361
362                 public bool CheckDependencies (EmitContext ec)
363                 {
364                         foreach (TypeParameterExpr expr in type_param_constraints) {
365                                 if (!CheckDependencies (expr.TypeParameter, ec))
366                                         return false;
367                         }
368
369                         return true;
370                 }
371
372                 bool CheckDependencies (TypeParameter tparam, EmitContext ec)
373                 {
374                         Constraints constraints = tparam.Constraints;
375                         if (constraints == null)
376                                 return true;
377
378                         if (HasValueTypeConstraint && constraints.HasClassConstraint) {
379                                 Report.Error (455, loc, "Type parameter `{0}' inherits " +
380                                               "conflicting constraints `{1}' and `{2}'",
381                                               name, constraints.ClassConstraint,
382                                               "System.ValueType");
383                                 return false;
384                         }
385
386                         if (HasClassConstraint && constraints.HasClassConstraint) {
387                                 Type t1 = ClassConstraint;
388                                 TypeExpr e1 = class_constraint;
389                                 Type t2 = constraints.ClassConstraint;
390                                 TypeExpr e2 = constraints.class_constraint;
391
392                                 if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
393                                     !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
394                                         Report.Error (455, loc,
395                                                       "Type parameter `{0}' inherits " +
396                                                       "conflicting constraints `{1}' and `{2}'",
397                                                       name, t1, t2);
398                                         return false;
399                                 }
400                         }
401
402                         if (constraints.type_param_constraints == null)
403                                 return true;
404
405                         foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
406                                 if (!CheckDependencies (expr.TypeParameter, ec))
407                                         return false;
408                         }
409
410                         return true;
411                 }
412
413                 public void Define (GenericTypeParameterBuilder type)
414                 {
415                         type.SetGenericParameterAttributes (attrs);
416                 }
417
418                 public override GenericParameterAttributes Attributes {
419                         get { return attrs; }
420                 }
421
422                 public override bool HasClassConstraint {
423                         get { return class_constraint != null; }
424                 }
425
426                 public override Type ClassConstraint {
427                         get { return class_constraint_type; }
428                 }
429
430                 public override Type[] InterfaceConstraints {
431                         get { return iface_constraint_types; }
432                 }
433
434                 public override Type EffectiveBaseClass {
435                         get { return effective_base_type; }
436                 }
437
438                 internal bool IsSubclassOf (Type t)
439                 {
440                         if ((class_constraint_type != null) &&
441                             class_constraint_type.IsSubclassOf (t))
442                                 return true;
443
444                         if (iface_constraint_types == null)
445                                 return false;
446
447                         foreach (Type iface in iface_constraint_types) {
448                                 if (TypeManager.IsSubclassOf (iface, t))
449                                         return true;
450                         }
451
452                         return false;
453                 }
454
455                 public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
456                 {
457                         if (gc.Attributes != attrs)
458                                 return false;
459
460                         if (HasClassConstraint != gc.HasClassConstraint)
461                                 return false;
462                         if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
463                                 return false;
464
465                         int gc_icount = gc.InterfaceConstraints != null ?
466                                 gc.InterfaceConstraints.Length : 0;
467                         int icount = InterfaceConstraints != null ?
468                                 InterfaceConstraints.Length : 0;
469
470                         if (gc_icount != icount)
471                                 return false;
472
473                         foreach (Type iface in gc.InterfaceConstraints) {
474                                 bool ok = false;
475                                 foreach (Type check in InterfaceConstraints) {
476                                         if (TypeManager.IsEqual (iface, check)) {
477                                                 ok = true;
478                                                 break;
479                                         }
480                                 }
481
482                                 if (!ok)
483                                         return false;
484                         }
485
486                         return true;
487                 }
488         }
489
490         //
491         // This type represents a generic type parameter
492         //
493         public class TypeParameter : MemberCore, IMemberContainer {
494                 string name;
495                 GenericConstraints gc;
496                 Constraints constraints;
497                 Location loc;
498                 GenericTypeParameterBuilder type;
499
500                 public TypeParameter (TypeContainer parent, string name,
501                                       Constraints constraints, Location loc)
502                         : base (parent, new MemberName (name), null, loc)
503                 {
504                         this.name = name;
505                         this.constraints = constraints;
506                         this.loc = loc;
507                 }
508
509                 public GenericConstraints GenericConstraints {
510                         get {
511                                 return gc != null ? gc : constraints;
512                         }
513                 }
514
515                 public Constraints Constraints {
516                         get {
517                                 return constraints;
518                         }
519                 }
520
521                 public bool HasConstructorConstraint {
522                         get {
523                                 if (constraints != null)
524                                         return constraints.HasConstructorConstraint;
525
526                                 return false;
527                         }
528                 }
529
530                 public Type Type {
531                         get {
532                                 return type;
533                         }
534                 }
535
536                 public bool Resolve (DeclSpace ds)
537                 {
538                         if (constraints != null) {
539                                 if (!constraints.Resolve (ds.EmitContext)) {
540                                         constraints = null;
541                                         return false;
542                                 }
543                         }
544
545                         return true;
546                 }
547
548                 public void Define (GenericTypeParameterBuilder type)
549                 {
550                         if (this.type != null)
551                                 throw new InvalidOperationException ();
552
553                         this.type = type;
554                         TypeManager.AddTypeParameter (type, this);
555                 }
556
557                 public void DefineConstraints ()
558                 {
559                         if (constraints != null)
560                                 constraints.Define (type);
561                 }
562
563                 public bool ResolveType (EmitContext ec)
564                 {
565                         if (constraints != null) {
566                                 if (!constraints.ResolveTypes (ec)) {
567                                         constraints = null;
568                                         return false;
569                                 }
570                         }
571
572                         return true;
573                 }
574
575                 public bool DefineType (EmitContext ec)
576                 {
577                         return DefineType (ec, null, null, false);
578                 }
579
580                 public bool DefineType (EmitContext ec, MethodBuilder builder,
581                                         MethodInfo implementing, bool is_override)
582                 {
583                         if (!ResolveType (ec))
584                                 return false;
585
586                         if (implementing != null) {
587                                 if (is_override && (constraints != null)) {
588                                         Report.Error (
589                                                 460, loc, "Constraints for override and " +
590                                                 "explicit interface implementation methods " +
591                                                 "are inherited from the base method so they " +
592                                                 "cannot be specified directly");
593                                         return false;
594                                 }
595
596                                 MethodBase mb = implementing;
597                                 if (mb.Mono_IsInflatedMethod)
598                                         mb = mb.GetGenericMethodDefinition ();
599
600                                 int pos = type.GenericParameterPosition;
601                                 ParameterData pd = Invocation.GetParameterData (mb);
602                                 GenericConstraints temp_gc = pd.GenericConstraints (pos);
603                                 Type mparam = mb.GetGenericArguments () [pos];
604
605                                 if (temp_gc != null)
606                                         gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
607                                 else if (constraints != null)
608                                         gc = new InflatedConstraints (constraints, implementing.DeclaringType);
609
610                                 bool ok = true;
611                                 if (constraints != null) {
612                                         if (temp_gc == null)
613                                                 ok = false;
614                                         else if (!constraints.CheckInterfaceMethod (ec, gc))
615                                                 ok = false;
616                                 } else {
617                                         if (!is_override && (temp_gc != null))
618                                                 ok = false;
619                                 }
620
621                                 if (!ok) {
622                                         Report.SymbolRelatedToPreviousError (implementing);
623
624                                         Report.Error (
625                                                 425, loc, "The constraints for type " +
626                                                 "parameter `{0}' of method `{1}' must match " +
627                                                 "the constraints for type parameter `{2}' " +
628                                                 "of interface method `{3}'.  Consider using " +
629                                                 "an explicit interface implementation instead",
630                                                 Name, TypeManager.CSharpSignature (builder),
631                                                 mparam, TypeManager.CSharpSignature (mb));
632                                         return false;
633                                 }
634                         } else {
635                                 gc = (GenericConstraints) constraints;
636                         }
637
638                         if (gc == null)
639                                 return true;
640
641                         if (gc.HasClassConstraint)
642                                 type.SetBaseTypeConstraint (gc.ClassConstraint);
643
644                         type.SetInterfaceConstraints (gc.InterfaceConstraints);
645                         TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
646
647                         return true;
648                 }
649
650                 public bool CheckDependencies (EmitContext ec)
651                 {
652                         if (constraints != null)
653                                 return constraints.CheckDependencies (ec);
654
655                         return true;
656                 }
657
658                 public override string DocCommentHeader {
659                         get {
660                                 throw new InvalidOperationException (
661                                         "Unexpected attempt to get doc comment from " + this.GetType () + ".");
662                         }
663                 }
664
665                 //
666                 // MemberContainer
667                 //
668
669                 public override bool Define ()
670                 {
671                         return true;
672                 }
673
674                 protected override void VerifyObsoleteAttribute ()
675                 { }
676
677                 public override void ApplyAttributeBuilder (Attribute a,
678                                                             CustomAttributeBuilder cb)
679                 { }
680
681                 public override AttributeTargets AttributeTargets {
682                         get {
683                                 return (AttributeTargets) 0;
684                         }
685                 }
686
687                 public override string[] ValidAttributeTargets {
688                         get {
689                                 return new string [0];
690                         }
691                 }
692
693                 //
694                 // IMemberContainer
695                 //
696
697                 string IMemberContainer.Name {
698                         get { return Name; }
699                 }
700
701                 MemberCache IMemberContainer.BaseCache {
702                         get { return null; }
703                 }
704
705                 bool IMemberContainer.IsInterface {
706                         get { return true; }
707                 }
708
709                 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
710                 {
711                         return FindMembers (mt, bf, null, null);
712                 }
713
714                 MemberCache IMemberContainer.MemberCache {
715                         get { return null; }
716                 }
717
718                 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
719                                                MemberFilter filter, object criteria)
720                 {
721                         if (constraints == null)
722                                 return MemberList.Empty;
723
724                         ArrayList members = new ArrayList ();
725
726                         GenericConstraints gc = (GenericConstraints) constraints;
727
728                         if (gc.HasClassConstraint) {
729                                 MemberList list = TypeManager.FindMembers (
730                                         gc.ClassConstraint, mt, bf, filter, criteria);
731
732                                 members.AddRange (list);
733                         }
734
735                         foreach (Type t in gc.InterfaceConstraints) {
736                                 MemberList list = TypeManager.FindMembers (
737                                         t, mt, bf, filter, criteria);
738
739                                 members.AddRange (list);
740                         }
741
742                         return new MemberList (members);
743                 }
744
745                 public bool IsSubclassOf (Type t)
746                 {
747                         if (type.Equals (t))
748                                 return true;
749
750                         if (constraints != null)
751                                 return constraints.IsSubclassOf (t);
752
753                         return false;
754                 }
755
756                 public override string ToString ()
757                 {
758                         return "TypeParameter[" + name + "]";
759                 }
760
761                 protected class InflatedConstraints : GenericConstraints
762                 {
763                         GenericConstraints gc;
764                         Type base_type;
765                         Type class_constraint;
766                         Type[] iface_constraints;
767                         Type[] dargs;
768                         Type declaring;
769
770                         public InflatedConstraints (GenericConstraints gc, Type declaring)
771                         {
772                                 this.gc = gc;
773                                 this.declaring = declaring;
774
775                                 dargs = TypeManager.GetTypeArguments (declaring);
776
777                                 ArrayList list = new ArrayList ();
778                                 if (gc.HasClassConstraint)
779                                         list.Add (inflate (gc.ClassConstraint));
780                                 foreach (Type iface in gc.InterfaceConstraints)
781                                         list.Add (inflate (iface));
782
783                                 bool has_class_constr = false;
784                                 if (list.Count > 0) {
785                                         Type first = (Type) list [0];
786                                         has_class_constr = !first.IsInterface && !first.IsGenericParameter;
787                                 }
788
789                                 if ((list.Count > 0) && has_class_constr) {
790                                         class_constraint = (Type) list [0];
791                                         iface_constraints = new Type [list.Count - 1];
792                                         list.CopyTo (1, iface_constraints, 0, list.Count - 1);
793                                 } else {
794                                         iface_constraints = new Type [list.Count];
795                                         list.CopyTo (iface_constraints, 0);
796                                 }
797
798                                 if (HasValueTypeConstraint)
799                                         base_type = TypeManager.value_type;
800                                 else if (class_constraint != null)
801                                         base_type = class_constraint;
802                                 else
803                                         base_type = TypeManager.object_type;
804                         }
805
806                         Type inflate (Type t)
807                         {
808                                 if (t == null)
809                                         return null;
810                                 if (t.IsGenericParameter)
811                                         return dargs [t.GenericParameterPosition];
812                                 if (t.IsGenericInstance) {
813                                         t = t.GetGenericTypeDefinition ();
814                                         t = t.BindGenericParameters (dargs);
815                                 }
816
817                                 return t;
818                         }
819
820                         public override GenericParameterAttributes Attributes {
821                                 get { return gc.Attributes; }
822                         }
823
824                         public override Type ClassConstraint {
825                                 get { return class_constraint; }
826                         }
827
828                         public override Type EffectiveBaseClass {
829                                 get { return base_type; }
830                         }
831
832                         public override Type[] InterfaceConstraints {
833                                 get { return iface_constraints; }
834                         }
835                 }
836         }
837
838         //
839         // This type represents a generic type parameter reference.
840         //
841         // These expressions are born in a fully resolved state.
842         //
843         public class TypeParameterExpr : TypeExpr {
844                 TypeParameter type_parameter;
845
846                 public override string Name {
847                         get {
848                                 return type_parameter.Name;
849                         }
850                 }
851
852                 public override string FullName {
853                         get {
854                                 return type_parameter.Name;
855                         }
856                 }
857
858                 public TypeParameter TypeParameter {
859                         get {
860                                 return type_parameter;
861                         }
862                 }
863                 
864                 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
865                 {
866                         this.type_parameter = type_parameter;
867                         this.loc = loc;
868                 }
869
870                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
871                 {
872                         type = type_parameter.Type;
873
874                         return this;
875                 }
876
877                 public override bool IsInterface {
878                         get { return false; }
879                 }
880
881                 public override bool CheckAccessLevel (DeclSpace ds)
882                 {
883                         return true;
884                 }
885
886                 public void Error_CannotUseAsUnmanagedType (Location loc)
887                 {
888                         Report.Error (-203, loc, "Can not use type parameter as unamanged type");
889                 }
890         }
891
892         public class TypeArguments {
893                 public readonly Location Location;
894                 ArrayList args;
895                 Type[] atypes;
896                 int dimension;
897                 bool has_type_args;
898                 bool created;
899                 
900                 public TypeArguments (Location loc)
901                 {
902                         args = new ArrayList ();
903                         this.Location = loc;
904                 }
905
906                 public TypeArguments (int dimension, Location loc)
907                 {
908                         this.dimension = dimension;
909                         this.Location = loc;
910                 }
911
912                 public void Add (Expression type)
913                 {
914                         if (created)
915                                 throw new InvalidOperationException ();
916
917                         args.Add (type);
918                 }
919
920                 public void Add (TypeArguments new_args)
921                 {
922                         if (created)
923                                 throw new InvalidOperationException ();
924
925                         args.AddRange (new_args.args);
926                 }
927
928                 public string[] GetDeclarations ()
929                 {
930                         string[] ret = new string [args.Count];
931                         for (int i = 0; i < args.Count; i++) {
932                                 SimpleName sn = args [i] as SimpleName;
933                                 if (sn != null) {
934                                         ret [i] = sn.Name;
935                                         continue;
936                                 }
937
938                                 Report.Error (81, Location, "Type parameter declaration " +
939                                               "must be an identifier not a type");
940                                 return null;
941                         }
942                         return ret;
943                 }
944
945                 public Type[] Arguments {
946                         get {
947                                 return atypes;
948                         }
949                 }
950
951                 public bool HasTypeArguments {
952                         get {
953                                 return has_type_args;
954                         }
955                 }
956
957                 public int Count {
958                         get {
959                                 if (dimension > 0)
960                                         return dimension;
961                                 else
962                                         return args.Count;
963                         }
964                 }
965
966                 public bool IsUnbound {
967                         get {
968                                 return dimension > 0;
969                         }
970                 }
971
972                 public override string ToString ()
973                 {
974                         StringBuilder s = new StringBuilder ();
975
976                         int count = Count;
977                         for (int i = 0; i < count; i++){
978                                 //
979                                 // FIXME: Use TypeManager.CSharpname once we have the type
980                                 //
981                                 if (args != null)
982                                         s.Append (args [i].ToString ());
983                                 if (i+1 < count)
984                                         s.Append (",");
985                         }
986                         return s.ToString ();
987                 }
988
989                 public bool Resolve (EmitContext ec)
990                 {
991                         int count = args.Count;
992                         bool ok = true;
993
994                         atypes = new Type [count];
995
996                         for (int i = 0; i < count; i++){
997                                 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
998                                 if (te == null) {
999                                         ok = false;
1000                                         continue;
1001                                 }
1002                                 if (te is TypeParameterExpr)
1003                                         has_type_args = true;
1004
1005                                 atypes [i] = te.Type;
1006                         }
1007                         return ok;
1008                 }
1009         }
1010         
1011         public class ConstructedType : TypeExpr {
1012                 string name, full_name;
1013                 TypeArguments args;
1014                 Type[] gen_params, atypes;
1015                 Type gt;
1016                 
1017                 public ConstructedType (string name, TypeArguments args, Location l)
1018                 {
1019                         loc = l;
1020                         this.name = MemberName.MakeName (name, args.Count);
1021                         this.args = args;
1022
1023                         eclass = ExprClass.Type;
1024                         full_name = name + "<" + args.ToString () + ">";
1025                 }
1026
1027                 public ConstructedType (string name, TypeParameter[] type_params, Location l)
1028                         : this (type_params, l)
1029                 {
1030                         loc = l;
1031
1032                         this.name = name;
1033                         full_name = name + "<" + args.ToString () + ">";
1034                 }
1035
1036                 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1037                 {
1038                         loc = l;
1039                         this.name = fname.FullName;
1040                         this.args = args;
1041
1042                         eclass = ExprClass.Type;
1043                         full_name = name + "<" + args.ToString () + ">";
1044                 }
1045
1046                 protected ConstructedType (TypeArguments args, Location l)
1047                 {
1048                         loc = l;
1049                         this.args = args;
1050
1051                         eclass = ExprClass.Type;
1052                 }
1053
1054                 protected ConstructedType (TypeParameter[] type_params, Location l)
1055                 {
1056                         loc = l;
1057
1058                         args = new TypeArguments (l);
1059                         foreach (TypeParameter type_param in type_params)
1060                                 args.Add (new TypeParameterExpr (type_param, l));
1061
1062                         eclass = ExprClass.Type;
1063                 }
1064
1065                 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1066                         : this (type_params, l)
1067                 {
1068                         gt = t.GetGenericTypeDefinition ();
1069
1070                         this.name = gt.FullName;
1071                         full_name = gt.FullName + "<" + args.ToString () + ">";
1072                 }
1073
1074                 public ConstructedType (Type t, TypeArguments args, Location l)
1075                         : this (args, l)
1076                 {
1077                         gt = t.GetGenericTypeDefinition ();
1078
1079                         this.name = gt.FullName;
1080                         full_name = gt.FullName + "<" + args.ToString () + ">";
1081                 }
1082
1083                 public TypeArguments TypeArguments {
1084                         get { return args; }
1085                 }
1086
1087                 protected string DeclarationName {
1088                         get {
1089                                 StringBuilder sb = new StringBuilder ();
1090                                 sb.Append (gt.FullName);
1091                                 sb.Append ("<");
1092                                 for (int i = 0; i < gen_params.Length; i++) {
1093                                         if (i > 0)
1094                                                 sb.Append (",");
1095                                         sb.Append (gen_params [i]);
1096                                 }
1097                                 sb.Append (">");
1098                                 return sb.ToString ();
1099                         }
1100                 }
1101
1102                 protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
1103                                                 Type ctype)
1104                 {
1105                         if (TypeManager.HasGenericArguments (ctype)) {
1106                                 Type[] types = TypeManager.GetTypeArguments (ctype);
1107
1108                                 TypeArguments new_args = new TypeArguments (loc);
1109
1110                                 for (int i = 0; i < types.Length; i++) {
1111                                         Type t = types [i];
1112
1113                                         if (t.IsGenericParameter) {
1114                                                 int pos = t.GenericParameterPosition;
1115                                                 t = args.Arguments [pos];
1116                                         }
1117                                         new_args.Add (new TypeExpression (t, loc));
1118                                 }
1119
1120                                 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1121                                 if (ct.ResolveAsTypeTerminal (ec) == null)
1122                                         return false;
1123                                 ctype = ct.Type;
1124                         }
1125
1126                         return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
1127                 }
1128
1129                 protected bool CheckConstraints (EmitContext ec, int index)
1130                 {
1131                         Type atype = atypes [index];
1132                         Type ptype = gen_params [index];
1133
1134                         if (atype == ptype)
1135                                 return true;
1136
1137                         Expression aexpr = new EmptyExpression (atype);
1138
1139                         GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1140                         if (gc == null)
1141                                 return true;
1142
1143                         bool is_class, is_struct;
1144                         if (atype.IsGenericParameter) {
1145                                 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1146                                 if (agc != null) {
1147                                         is_class = agc.HasReferenceTypeConstraint;
1148                                         is_struct = agc.HasValueTypeConstraint;
1149                                 } else {
1150                                         is_class = is_struct = false;
1151                                 }
1152                         } else {
1153                                 is_class = atype.IsClass;
1154                                 is_struct = atype.IsValueType;
1155                         }
1156
1157                         //
1158                         // First, check the `class' and `struct' constraints.
1159                         //
1160                         if (gc.HasReferenceTypeConstraint && !is_class) {
1161                                 Report.Error (452, loc, "The type `{0}' must be " +
1162                                               "a reference type in order to use it " +
1163                                               "as type parameter `{1}' in the " +
1164                                               "generic type or method `{2}'.",
1165                                               atype, ptype, DeclarationName);
1166                                 return false;
1167                         } else if (gc.HasValueTypeConstraint && !is_struct) {
1168                                 Report.Error (453, loc, "The type `{0}' must be " +
1169                                               "a value type in order to use it " +
1170                                               "as type parameter `{1}' in the " +
1171                                               "generic type or method `{2}'.",
1172                                               atype, ptype, DeclarationName);
1173                                 return false;
1174                         }
1175
1176                         //
1177                         // The class constraint comes next.
1178                         //
1179                         if (gc.HasClassConstraint) {
1180                                 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
1181                                         Report.Error (309, loc, "The type `{0}' must be " +
1182                                                       "convertible to `{1}' in order to " +
1183                                                       "use it as parameter `{2}' in the " +
1184                                                       "generic type or method `{3}'",
1185                                                       atype, gc.ClassConstraint, ptype, DeclarationName);
1186                                         return false;
1187                                 }
1188                         }
1189
1190                         //
1191                         // Now, check the interface constraints.
1192                         //
1193                         foreach (Type it in gc.InterfaceConstraints) {
1194                                 Type itype;
1195                                 if (it.IsGenericParameter)
1196                                         itype = atypes [it.GenericParameterPosition];
1197                                 else
1198                                         itype = it;
1199
1200                                 if (!CheckConstraint (ec, ptype, aexpr, itype)) {
1201                                         Report.Error (309, loc, "The type `{0}' must be " +
1202                                                       "convertible to `{1}' in order to " +
1203                                                       "use it as parameter `{2}' in the " +
1204                                                       "generic type or method `{3}'",
1205                                                       atype, itype, ptype, DeclarationName);
1206                                         return false;
1207                                 }
1208                         }
1209
1210                         //
1211                         // Finally, check the constructor constraint.
1212                         //
1213
1214                         if (!gc.HasConstructorConstraint)
1215                                 return true;
1216
1217                         if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1218                                 return true;
1219
1220                         MethodGroupExpr mg = Expression.MemberLookup (
1221                                 ec, atype, ".ctor", MemberTypes.Constructor,
1222                                 BindingFlags.Public | BindingFlags.Instance |
1223                                 BindingFlags.DeclaredOnly, loc)
1224                                 as MethodGroupExpr;
1225
1226                         if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
1227                                 Report.Error (310, loc, "The type `{0}' must have a public " +
1228                                               "parameterless constructor in order to use it " +
1229                                               "as parameter `{1}' in the generic type or " +
1230                                               "method `{2}'", atype, ptype, DeclarationName);
1231                                 return false;
1232                         }
1233
1234                         return true;
1235                 }
1236
1237                 protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
1238                 {
1239                         if (!ResolveConstructedType (ec))
1240                                 return null;
1241
1242                         return this;
1243                 }
1244
1245                 public bool CheckConstraints (EmitContext ec)
1246                 {
1247                         for (int i = 0; i < gen_params.Length; i++) {
1248                                 if (!CheckConstraints (ec, i))
1249                                         return false;
1250                         }
1251
1252                         return true;
1253                 }
1254
1255                 public override TypeExpr ResolveAsTypeTerminal (EmitContext ec)
1256                 {
1257                         if (base.ResolveAsTypeTerminal (ec) == null)
1258                                 return null;
1259
1260                         if (!CheckConstraints (ec))
1261                                 return null;
1262
1263                         return this;
1264                 }
1265
1266                 public bool ResolveConstructedType (EmitContext ec)
1267                 {
1268                         if (type != null)
1269                                 return true;
1270                         if (gt != null)
1271                                 return DoResolveType (ec);
1272
1273                         //
1274                         // First, resolve the generic type.
1275                         //
1276                         DeclSpace ds;
1277                         Type nested = ec.DeclSpace.FindNestedType (loc, name, out ds);
1278                         if (nested != null) {
1279                                 gt = nested.GetGenericTypeDefinition ();
1280
1281                                 TypeArguments new_args = new TypeArguments (loc);
1282                                 if (ds.IsGeneric) {
1283                                         foreach (TypeParameter param in ds.TypeParameters)
1284                                                 new_args.Add (new TypeParameterExpr (param, loc));
1285                                 }
1286                                 new_args.Add (args);
1287
1288                                 args = new_args;
1289                                 return DoResolveType (ec);
1290                         }
1291
1292                         Type t;
1293                         int num_args;
1294
1295                         SimpleName sn = new SimpleName (name, loc);
1296                         TypeExpr resolved = sn.ResolveAsTypeTerminal (ec);
1297                         if (resolved == null)
1298                                 return false;
1299
1300                         t = resolved.Type;
1301                         if (t == null) {
1302                                 Report.Error (246, loc, "Cannot find type `{0}'<...>",
1303                                               Basename);
1304                                 return false;
1305                         }
1306
1307                         num_args = TypeManager.GetNumberOfTypeArguments (t);
1308                         if (num_args == 0) {
1309                                 Report.Error (308, loc,
1310                                               "The non-generic type `{0}' cannot " +
1311                                               "be used with type arguments.",
1312                                               TypeManager.CSharpName (t));
1313                                 return false;
1314                         }
1315
1316                         gt = t.GetGenericTypeDefinition ();
1317                         return DoResolveType (ec);
1318                 }
1319
1320                 bool DoResolveType (EmitContext ec)
1321                 {
1322                         //
1323                         // Resolve the arguments.
1324                         //
1325                         if (args.Resolve (ec) == false)
1326                                 return false;
1327
1328                         gen_params = gt.GetGenericArguments ();
1329                         atypes = args.Arguments;
1330
1331                         if (atypes.Length != gen_params.Length) {
1332                                 Report.Error (305, loc,
1333                                               "Using the generic type `{0}' " +
1334                                               "requires {1} type arguments",
1335                                               TypeManager.GetFullName (gt),
1336                                               gen_params.Length);
1337                                 return false;
1338                         }
1339
1340                         //
1341                         // Now bind the parameters.
1342                         //
1343                         type = gt.BindGenericParameters (atypes);
1344                         return true;
1345                 }
1346
1347                 public Expression GetSimpleName (EmitContext ec)
1348                 {
1349                         return new SimpleName (Basename, args, loc);
1350                 }
1351
1352                 public override bool CheckAccessLevel (DeclSpace ds)
1353                 {
1354                         return ds.CheckAccessLevel (gt);
1355                 }
1356
1357                 public override bool AsAccessible (DeclSpace ds, int flags)
1358                 {
1359                         return ds.AsAccessible (gt, flags);
1360                 }
1361
1362                 public override bool IsClass {
1363                         get { return gt.IsClass; }
1364                 }
1365
1366                 public override bool IsValueType {
1367                         get { return gt.IsValueType; }
1368                 }
1369
1370                 public override bool IsInterface {
1371                         get { return gt.IsInterface; }
1372                 }
1373
1374                 public override bool IsSealed {
1375                         get { return gt.IsSealed; }
1376                 }
1377
1378                 public override bool IsAttribute {
1379                         get { return false; }
1380                 }
1381
1382                 public override bool Equals (object obj)
1383                 {
1384                         ConstructedType cobj = obj as ConstructedType;
1385                         if (cobj == null)
1386                                 return false;
1387
1388                         if ((type == null) || (cobj.type == null))
1389                                 return false;
1390
1391                         return type == cobj.type;
1392                 }
1393
1394                 public override int GetHashCode ()
1395                 {
1396                         return base.GetHashCode ();
1397                 }
1398
1399                 public string Basename {
1400                         get {
1401                                 int pos = name.LastIndexOf ('`');
1402                                 if (pos >= 0)
1403                                         return name.Substring (0, pos);
1404                                 else
1405                                         return name;
1406                         }
1407                 }
1408
1409                 public override string Name {
1410                         get {
1411                                 return full_name;
1412                         }
1413                 }
1414
1415
1416                 public override string FullName {
1417                         get {
1418                                 return full_name;
1419                         }
1420                 }
1421         }
1422
1423         public class GenericMethod : DeclSpace
1424         {
1425                 public GenericMethod (NamespaceEntry ns, TypeContainer parent,
1426                                       MemberName name, Location l)
1427                         : base (ns, parent, name, null, l)
1428                 { }
1429
1430                 public override TypeBuilder DefineType ()
1431                 {
1432                         throw new Exception ();
1433                 }
1434
1435                 public override bool Define ()
1436                 {
1437                         for (int i = 0; i < TypeParameters.Length; i++)
1438                                 if (!TypeParameters [i].Resolve (Parent))
1439                                         return false;
1440
1441                         return true;
1442                 }
1443
1444                 public bool Define (MethodBuilder mb, Type return_type)
1445                 {
1446                         if (!Define ())
1447                                 return false;
1448
1449                         GenericTypeParameterBuilder[] gen_params;
1450                         string[] names = MemberName.TypeArguments.GetDeclarations ();
1451                         gen_params = mb.DefineGenericParameters (names);
1452                         for (int i = 0; i < TypeParameters.Length; i++)
1453                                 TypeParameters [i].Define (gen_params [i]);
1454
1455                         ec = new EmitContext (
1456                                 this, this, Location, null, return_type, ModFlags, false);
1457
1458                         for (int i = 0; i < TypeParameters.Length; i++) {
1459                                 if (!TypeParameters [i].ResolveType (ec))
1460                                         return false;
1461                         }
1462
1463                         return true;
1464                 }
1465
1466                 public bool DefineType (EmitContext ec, MethodBuilder mb,
1467                                         MethodInfo implementing, bool is_override)
1468                 {
1469                         for (int i = 0; i < TypeParameters.Length; i++)
1470                                 if (!TypeParameters [i].DefineType (
1471                                             ec, mb, implementing, is_override))
1472                                         return false;
1473
1474                         return true;
1475                 }
1476
1477                 public override bool DefineMembers (TypeContainer parent)
1478                 {
1479                         return true;
1480                 }
1481
1482                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1483                                                         MemberFilter filter, object criteria)
1484                 {
1485                         throw new Exception ();
1486                 }               
1487
1488                 public override MemberCache MemberCache {
1489                         get {
1490                                 return null;
1491                         }
1492                 }
1493
1494                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1495                 {
1496                         // FIXME
1497                 }
1498
1499                 protected override void VerifyObsoleteAttribute()
1500                 {
1501                         // FIXME
1502                 }
1503
1504                 public override AttributeTargets AttributeTargets {
1505                         get {
1506                                 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1507                         }
1508                 }
1509
1510                 public override string DocCommentHeader {
1511                         get { return "M:"; }
1512                 }
1513         }
1514
1515         public class DefaultValueExpression : Expression
1516         {
1517                 Expression expr;
1518                 LocalTemporary temp_storage;
1519
1520                 public DefaultValueExpression (Expression expr, Location loc)
1521                 {
1522                         this.expr = expr;
1523                         this.loc = loc;
1524                 }
1525
1526                 public override Expression DoResolve (EmitContext ec)
1527                 {
1528                         TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
1529                         if (texpr == null)
1530                                 return null;
1531
1532                         type = texpr.Type;
1533                         if (type.IsGenericParameter || TypeManager.IsValueType (type))
1534                                 temp_storage = new LocalTemporary (ec, type);
1535
1536                         eclass = ExprClass.Variable;
1537                         return this;
1538                 }
1539
1540                 public override void Emit (EmitContext ec)
1541                 {
1542                         if (temp_storage != null) {
1543                                 temp_storage.AddressOf (ec, AddressOp.LoadStore);
1544                                 ec.ig.Emit (OpCodes.Initobj, type);
1545                                 temp_storage.Emit (ec);
1546                         } else
1547                                 ec.ig.Emit (OpCodes.Ldnull);
1548                 }
1549         }
1550
1551         public partial class TypeManager
1552         {
1553                 //
1554                 // A list of core types that the compiler requires or uses
1555                 //
1556                 static public Type new_constraint_attr_type;
1557                 static public Type activator_type;
1558                 static public Type generic_ienumerator_type;
1559                 static public Type generic_ienumerable_type;
1560                 static public Type generic_nullable_type;
1561
1562                 // <remarks>
1563                 //   Tracks the generic parameters.
1564                 // </remarks>
1565                 static PtrHashtable builder_to_type_param;
1566
1567                 //
1568                 // These methods are called by code generated by the compiler
1569                 //
1570                 static public MethodInfo activator_create_instance;
1571
1572                 static void InitGenerics ()
1573                 {
1574                         builder_to_type_param = new PtrHashtable ();
1575                 }
1576
1577                 static void CleanUpGenerics ()
1578                 {
1579                         builder_to_type_param = null;
1580                 }
1581
1582                 static void InitGenericCoreTypes ()
1583                 {
1584                         activator_type = CoreLookupType ("System.Activator");
1585                         new_constraint_attr_type = CoreLookupType (
1586                                 "System.Runtime.CompilerServices.NewConstraintAttribute");
1587
1588                         generic_ienumerator_type = CoreLookupType ("System.Collections.Generic.IEnumerator", 1);
1589                         generic_ienumerable_type = CoreLookupType ("System.Collections.Generic.IEnumerable", 1);
1590                         generic_nullable_type = CoreLookupType ("System.Nullable", 1);
1591                 }
1592
1593                 static void InitGenericCodeHelpers ()
1594                 {
1595                         // Activator
1596                         Type [] type_arg = { type_type };
1597                         activator_create_instance = GetMethod (
1598                                 activator_type, "CreateInstance", type_arg);
1599                 }
1600
1601                 static Type CoreLookupType (string name, int arity)
1602                 {
1603                         return CoreLookupType (MemberName.MakeName (name, arity));
1604                 }
1605
1606                 public static void AddTypeParameter (Type t, TypeParameter tparam)
1607                 {
1608                         if (!builder_to_type_param.Contains (t))
1609                                 builder_to_type_param.Add (t, tparam);
1610                 }
1611
1612                 public static TypeContainer LookupGenericTypeContainer (Type t)
1613                 {
1614                         while (t.IsGenericInstance)
1615                                 t = t.GetGenericTypeDefinition ();
1616
1617                         return LookupTypeContainer (t);
1618                 }
1619
1620                 public static TypeParameter LookupTypeParameter (Type t)
1621                 {
1622                         return (TypeParameter) builder_to_type_param [t];
1623                 }
1624
1625                 public static bool HasConstructorConstraint (Type t)
1626                 {
1627                         GenericConstraints gc = GetTypeParameterConstraints (t);
1628                         if (gc == null)
1629                                 return false;
1630
1631                         return (gc.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
1632                 }
1633
1634                 public static GenericConstraints GetTypeParameterConstraints (Type t)
1635                 {
1636                         if (!t.IsGenericParameter)
1637                                 throw new InvalidOperationException ();
1638
1639                         TypeParameter tparam = LookupTypeParameter (t);
1640                         if (tparam != null)
1641                                 return tparam.GenericConstraints;
1642
1643                         return new ReflectionConstraints (t);
1644                 }
1645
1646                 public static bool IsGeneric (Type t)
1647                 {
1648                         DeclSpace ds = (DeclSpace) builder_to_declspace [t];
1649
1650                         return ds.IsGeneric;
1651                 }
1652
1653                 public static bool HasGenericArguments (Type t)
1654                 {
1655                         return GetNumberOfTypeArguments (t) > 0;
1656                 }
1657
1658                 public static int GetNumberOfTypeArguments (Type t)
1659                 {
1660                         DeclSpace tc = LookupDeclSpace (t);
1661                         if (tc != null)
1662                                 return tc.IsGeneric ? tc.CountTypeParameters : 0;
1663                         else
1664                                 return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
1665                 }
1666
1667                 public static Type[] GetTypeArguments (Type t)
1668                 {
1669                         DeclSpace tc = LookupDeclSpace (t);
1670                         if (tc != null) {
1671                                 if (!tc.IsGeneric)
1672                                         return Type.EmptyTypes;
1673
1674                                 TypeParameter[] tparam = tc.TypeParameters;
1675                                 Type[] ret = new Type [tparam.Length];
1676                                 for (int i = 0; i < tparam.Length; i++) {
1677                                         ret [i] = tparam [i].Type;
1678                                         if (ret [i] == null)
1679                                                 throw new InternalErrorException ();
1680                                 }
1681
1682                                 return ret;
1683                         } else
1684                                 return t.GetGenericArguments ();
1685                 }
1686
1687                 public static bool IsEqual (Type a, Type b)
1688                 {
1689                         if (a.Equals (b))
1690                                 return true;
1691
1692                         if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
1693                                 //
1694                                 // `a' is a generic type definition's TypeBuilder and `b' is a
1695                                 // generic instance of the same type.
1696                                 //
1697                                 // Example:
1698                                 //
1699                                 // class Stack<T>
1700                                 // {
1701                                 //     void Test (Stack<T> stack) { }
1702                                 // }
1703                                 //
1704                                 // The first argument of `Test' will be the generic instance
1705                                 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1706                                 //
1707                                 //
1708                                 // We hit this via Closure.Filter() for gen-82.cs.
1709                                 //
1710                                 if (a != b.GetGenericTypeDefinition ())
1711                                         return false;
1712
1713                                 Type[] aparams = a.GetGenericArguments ();
1714                                 Type[] bparams = b.GetGenericArguments ();
1715
1716                                 if (aparams.Length != bparams.Length)
1717                                         return false;
1718
1719                                 for (int i = 0; i < aparams.Length; i++)
1720                                         if (!IsEqual (aparams [i], bparams [i]))
1721                                                 return false;
1722
1723                                 return true;
1724                         }
1725
1726                         if (a.IsGenericParameter && b.IsGenericParameter) {
1727                                 if ((a.DeclaringMethod == null) || (b.DeclaringMethod == null))
1728                                         return false;
1729                                 return a.GenericParameterPosition == b.GenericParameterPosition;
1730                         }
1731
1732                         if (a.IsArray && b.IsArray) {
1733                                 if (a.GetArrayRank () != b.GetArrayRank ())
1734                                         return false;
1735                                 return IsEqual (a.GetElementType (), b.GetElementType ());
1736                         }
1737
1738                         if (a.IsGenericInstance && b.IsGenericInstance) {
1739                                 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1740                                         return false;
1741
1742                                 Type[] aargs = a.GetGenericArguments ();
1743                                 Type[] bargs = b.GetGenericArguments ();
1744
1745                                 if (aargs.Length != bargs.Length)
1746                                         return false;
1747
1748                                 for (int i = 0; i < aargs.Length; i++) {
1749                                         if (!IsEqual (aargs [i], bargs [i]))
1750                                                 return false;
1751                                 }
1752
1753                                 return true;
1754                         }
1755
1756                         return false;
1757                 }
1758
1759                 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered, Type[] method_infered)
1760                 {
1761                         if (a.IsGenericParameter) {
1762                                 //
1763                                 // If a is an array of a's type, they may never
1764                                 // become equal.
1765                                 //
1766                                 while (b.IsArray) {
1767                                         b = b.GetElementType ();
1768                                         if (a.Equals (b))
1769                                                 return false;
1770                                 }
1771
1772                                 //
1773                                 // If b is a generic parameter or an actual type,
1774                                 // they may become equal:
1775                                 //
1776                                 //    class X<T,U> : I<T>, I<U>
1777                                 //    class X<T> : I<T>, I<float>
1778                                 // 
1779                                 if (b.IsGenericParameter || !b.IsGenericInstance) {
1780                                         int pos = a.GenericParameterPosition;
1781                                         Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
1782                                         if (args [pos] == null) {
1783                                                 args [pos] = b;
1784                                                 return true;
1785                                         }
1786
1787                                         return args [pos] == a;
1788                                 }
1789
1790                                 //
1791                                 // We're now comparing a type parameter with a
1792                                 // generic instance.  They may become equal unless
1793                                 // the type parameter appears anywhere in the
1794                                 // generic instance:
1795                                 //
1796                                 //    class X<T,U> : I<T>, I<X<U>>
1797                                 //        -> error because you could instanciate it as
1798                                 //           X<X<int>,int>
1799                                 //
1800                                 //    class X<T> : I<T>, I<X<T>> -> ok
1801                                 //
1802
1803                                 Type[] bargs = GetTypeArguments (b);
1804                                 for (int i = 0; i < bargs.Length; i++) {
1805                                         if (a.Equals (bargs [i]))
1806                                                 return false;
1807                                 }
1808
1809                                 return true;
1810                         }
1811
1812                         if (b.IsGenericParameter)
1813                                 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
1814
1815                         //
1816                         // At this point, neither a nor b are a type parameter.
1817                         //
1818                         // If one of them is a generic instance, let
1819                         // MayBecomeEqualGenericInstances() compare them (if the
1820                         // other one is not a generic instance, they can never
1821                         // become equal).
1822                         //
1823
1824                         if (a.IsGenericInstance || b.IsGenericInstance)
1825                                 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
1826
1827                         //
1828                         // If both of them are arrays.
1829                         //
1830
1831                         if (a.IsArray && b.IsArray) {
1832                                 if (a.GetArrayRank () != b.GetArrayRank ())
1833                                         return false;
1834                         
1835                                 a = a.GetElementType ();
1836                                 b = b.GetElementType ();
1837
1838                                 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
1839                         }
1840
1841                         //
1842                         // Ok, two ordinary types.
1843                         //
1844
1845                         return a.Equals (b);
1846                 }
1847
1848                 //
1849                 // Checks whether two generic instances may become equal for some
1850                 // particular instantiation (26.3.1).
1851                 //
1852                 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
1853                                                                    Type[] class_infered, Type[] method_infered)
1854                 {
1855                         if (!a.IsGenericInstance || !b.IsGenericInstance)
1856                                 return false;
1857                         if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
1858                                 return false;
1859
1860                         return MayBecomeEqualGenericInstances (
1861                                 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
1862                 }
1863
1864                 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
1865                                                                    Type[] class_infered, Type[] method_infered)
1866                 {
1867                         if (aargs.Length != bargs.Length)
1868                                 return false;
1869
1870                         for (int i = 0; i < aargs.Length; i++) {
1871                                 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
1872                                         return false;
1873                         }
1874
1875                         return true;
1876                 }
1877
1878                 public static bool IsEqualGenericInstance (Type type, Type parent)
1879                 {
1880                         int tcount = GetNumberOfTypeArguments (type);
1881                         int pcount = GetNumberOfTypeArguments (parent);
1882
1883                         if (type.IsGenericInstance)
1884                                 type = type.GetGenericTypeDefinition ();
1885                         if (parent.IsGenericInstance)
1886                                 parent = parent.GetGenericTypeDefinition ();
1887
1888                         if (tcount != pcount)
1889                                 return false;
1890
1891                         return type.Equals (parent);
1892                 }
1893
1894                 static public bool IsGenericMethod (MethodBase mb)
1895                 {
1896                         if (mb.DeclaringType is TypeBuilder) {
1897                                 IMethodData method = (IMethodData) builder_to_method [mb];
1898                                 if (method == null)
1899                                         return false;
1900
1901                                 return method.GenericMethod != null;
1902                         }
1903
1904                         return mb.IsGenericMethodDefinition;
1905                 }
1906
1907                 //
1908                 // Type inference.
1909                 //
1910
1911                 static bool InferType (Type pt, Type at, Type[] infered)
1912                 {
1913                         if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
1914                                 int pos = pt.GenericParameterPosition;
1915
1916                                 if (infered [pos] == null) {
1917                                         Type check = at;
1918                                         while (check.IsArray)
1919                                                 check = check.GetElementType ();
1920
1921                                         if (pt == check)
1922                                                 return false;
1923
1924                                         infered [pos] = at;
1925                                         return true;
1926                                 }
1927
1928                                 if (infered [pos] != at)
1929                                         return false;
1930
1931                                 return true;
1932                         }
1933
1934                         if (!pt.ContainsGenericParameters) {
1935                                 if (at.ContainsGenericParameters)
1936                                         return InferType (at, pt, infered);
1937                                 else
1938                                         return true;
1939                         }
1940
1941                         if (at.IsArray) {
1942                                 if (!pt.IsArray ||
1943                                     (at.GetArrayRank () != pt.GetArrayRank ()))
1944                                         return false;
1945
1946                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1947                         }
1948
1949                         if (pt.IsArray) {
1950                                 if (!at.IsArray ||
1951                                     (pt.GetArrayRank () != at.GetArrayRank ()))
1952                                         return false;
1953
1954                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1955                         }
1956
1957                         if (pt.IsByRef && at.IsByRef)
1958                                 return InferType (pt.GetElementType (), at.GetElementType (), infered);
1959                         ArrayList list = new ArrayList ();
1960                         if (at.IsGenericInstance)
1961                                 list.Add (at);
1962                         else {
1963                                 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
1964                                         list.Add (bt);
1965
1966                                 list.AddRange (TypeManager.GetInterfaces (at));
1967                         }
1968
1969                         bool found_one = false;
1970
1971                         foreach (Type type in list) {
1972                                 if (!type.IsGenericInstance)
1973                                         continue;
1974
1975                                 Type[] infered_types = new Type [infered.Length];
1976
1977                                 if (!InferGenericInstance (pt, type, infered_types))
1978                                         continue;
1979
1980                                 for (int i = 0; i < infered_types.Length; i++) {
1981                                         if (infered [i] == null) {
1982                                                 infered [i] = infered_types [i];
1983                                                 continue;
1984                                         }
1985
1986                                         if (infered [i] != infered_types [i])
1987                                                 return false;
1988                                 }
1989
1990                                 found_one = true;
1991                         }
1992
1993                         return found_one;
1994                 }
1995
1996                 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
1997                 {
1998                         Type[] at_args = at.GetGenericArguments ();
1999                         Type[] pt_args = pt.GetGenericArguments ();
2000
2001                         if (at_args.Length != pt_args.Length)
2002                                 return false;
2003
2004                         for (int i = 0; i < at_args.Length; i++) {
2005                                 if (!InferType (pt_args [i], at_args [i], infered_types))
2006                                         return false;
2007                         }
2008
2009                         for (int i = 0; i < infered_types.Length; i++) {
2010                                 if (infered_types [i] == null)
2011                                         return false;
2012                         }
2013
2014                         return true;
2015                 }
2016
2017                 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2018                                                              ref MethodBase method)
2019                 {
2020                         if ((arguments == null) || !TypeManager.IsGenericMethod (method))
2021                                 return true;
2022
2023                         int arg_count;
2024                         
2025                         if (arguments == null)
2026                                 arg_count = 0;
2027                         else
2028                                 arg_count = arguments.Count;
2029                         
2030                         ParameterData pd = Invocation.GetParameterData (method);
2031
2032                         int pd_count = pd.Count;
2033
2034                         if (pd_count == 0)
2035                                 return false;
2036                         
2037                         if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2038                                 return false;
2039                         
2040                         if (pd_count - 1 > arg_count)
2041                                 return false;
2042                         
2043                         if (pd_count == 1 && arg_count == 0)
2044                                 return true;
2045
2046                         Type[] method_args = method.GetGenericArguments ();
2047                         Type[] infered_types = new Type [method_args.Length];
2048
2049                         //
2050                         // If we have come this far, the case which
2051                         // remains is when the number of parameters is
2052                         // less than or equal to the argument count.
2053                         //
2054                         for (int i = 0; i < pd_count - 1; ++i) {
2055                                 Argument a = (Argument) arguments [i];
2056
2057                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2058                                         continue;
2059
2060                                 Type pt = pd.ParameterType (i);
2061                                 Type at = a.Type;
2062
2063                                 if (!InferType (pt, at, infered_types))
2064                                         return false;
2065                         }
2066
2067                         Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2068
2069                         for (int i = pd_count - 1; i < arg_count; i++) {
2070                                 Argument a = (Argument) arguments [i];
2071
2072                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2073                                         continue;
2074
2075                                 if (!InferType (element_type, a.Type, infered_types))
2076                                         return false;
2077                         }
2078
2079                         for (int i = 0; i < infered_types.Length; i++)
2080                                 if (infered_types [i] == null)
2081                                         return false;
2082
2083                         method = method.BindGenericParameters (infered_types);
2084                         return true;
2085                 }
2086
2087                 public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
2088                 {
2089                         if (infered_types == null)
2090                                 return false;
2091
2092                         for (int i = 0; i < arg_types.Length; i++) {
2093                                 if (arg_types [i] == null)
2094                                         continue;
2095
2096                                 if (!InferType (param_types [i], arg_types [i], infered_types))
2097                                         return false;
2098                         }
2099
2100                         for (int i = 0; i < infered_types.Length; i++)
2101                                 if (infered_types [i] == null)
2102                                         return false;
2103
2104                         return true;
2105                 }
2106
2107                 public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
2108                                                        ref MethodBase method)
2109                 {
2110                         if (!TypeManager.IsGenericMethod (method))
2111                                 return true;
2112
2113                         int arg_count;
2114                         if (arguments != null)
2115                                 arg_count = arguments.Count;
2116                         else
2117                                 arg_count = 0;
2118
2119                         ParameterData pd = Invocation.GetParameterData (method);
2120                         if (arg_count != pd.Count)
2121                                 return false;
2122
2123                         Type[] method_args = method.GetGenericArguments ();
2124
2125                         bool is_open = false;
2126                         for (int i = 0; i < method_args.Length; i++) {
2127                                 if (method_args [i].IsGenericParameter) {
2128                                         is_open = true;
2129                                         break;
2130                                 }
2131                         }
2132                         if (!is_open)
2133                                 return true;
2134
2135                         Type[] infered_types = new Type [method_args.Length];
2136
2137                         Type[] param_types = new Type [pd.Count];
2138                         Type[] arg_types = new Type [pd.Count];
2139
2140                         for (int i = 0; i < arg_count; i++) {
2141                                 param_types [i] = pd.ParameterType (i);
2142
2143                                 Argument a = (Argument) arguments [i];
2144                                 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2145                                         continue;
2146
2147                                 arg_types [i] = a.Type;
2148                         }
2149
2150                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2151                                 return false;
2152
2153                         method = method.BindGenericParameters (infered_types);
2154                         return true;
2155                 }
2156
2157                 public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
2158                                                        ref MethodBase method)
2159                 {
2160                         if (!TypeManager.IsGenericMethod (method))
2161                                 return true;
2162
2163                         ParameterData pd = Invocation.GetParameterData (method);
2164                         if (apd.Count != pd.Count)
2165                                 return false;
2166
2167                         Type[] method_args = method.GetGenericArguments ();
2168                         Type[] infered_types = new Type [method_args.Length];
2169
2170                         Type[] param_types = new Type [pd.Count];
2171                         Type[] arg_types = new Type [pd.Count];
2172
2173                         for (int i = 0; i < apd.Count; i++) {
2174                                 param_types [i] = pd.ParameterType (i);
2175                                 arg_types [i] = apd.ParameterType (i);
2176                         }
2177
2178                         if (!InferTypeArguments (param_types, arg_types, infered_types))
2179                                 return false;
2180
2181                         method = method.BindGenericParameters (infered_types);
2182                         return true;
2183                 }
2184         }
2185 }