Make static fields readonly
[mono.git] / mcs / mcs / typespec.cs
1 //
2 // typespec.cs: Type specification
3 //
4 // Authors: Marek Safar (marek.safar@gmail.com)
5 //
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
7 //
8 // Copyright 2010 Novell, Inc
9 //
10
11 using System;
12 using System.Collections.Generic;
13 using System.Text;
14 using System.Linq;
15
16 namespace Mono.CSharp
17 {
18         public class TypeSpec : MemberSpec
19         {
20                 protected Type info;
21                 protected MemberCache cache;
22                 protected IList<TypeSpec> ifaces;
23                 TypeSpec base_type;
24
25                 Dictionary<TypeSpec[], InflatedTypeSpec> inflated_instances;
26
27                 public static readonly TypeSpec[] EmptyTypes = new TypeSpec[0];
28
29                 // Reflection Emit hacking
30                 static Type TypeBuilder;
31                 static Type GenericTypeBuilder;
32
33                 static TypeSpec ()
34                 {
35                         var assembly = typeof (object).Assembly;
36                         TypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilder");
37                         GenericTypeBuilder = assembly.GetType ("System.Reflection.MonoGenericClass");
38                         if (GenericTypeBuilder == null)
39                                 GenericTypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilderInstantiation");
40                 }
41
42                 public TypeSpec (MemberKind kind, TypeSpec declaringType, ITypeDefinition definition, Type info, Modifiers modifiers)
43                         : base (kind, declaringType, definition, modifiers)
44                 {
45                         this.declaringType = declaringType;
46                         this.info = info;
47
48                         if (definition != null && definition.TypeParametersCount > 0)
49                                 state |= StateFlags.IsGeneric;
50                 }
51
52                 #region Properties
53
54                 public override int Arity {
55                         get {
56                                 return MemberDefinition.TypeParametersCount;
57                         }
58                 }
59
60                 public virtual TypeSpec BaseType {
61                         get {
62                                 return base_type;
63                         }
64                         set {
65                                 base_type = value;
66                         }
67                 }
68
69                 public bool HasDynamicElement {
70                         get {
71                                 return (state & StateFlags.HasDynamicElement) != 0;
72                         }
73                 }
74
75                 public virtual IList<TypeSpec> Interfaces {
76                         get {
77                                 return ifaces;
78                         }
79                         set {
80                                 ifaces = value;
81                         }
82                 }
83
84                 public bool IsArray {
85                         get {
86                                 return Kind == MemberKind.ArrayType;
87                         }
88                 }
89
90                 public bool IsAttribute {
91                         get {
92                                 if (!IsClass)
93                                         return false;
94
95                                 var type = this;
96                                 do {
97                                         if (type.IsGeneric)
98                                                 return false;
99
100                                         if (type == TypeManager.attribute_type)
101                                                 return true;
102                                         
103                                         type = type.base_type;
104                                 } while (type != null);
105
106                                 return false;
107                         }
108                 }
109
110                 public bool IsInterface {
111                         get {
112                                 return Kind == MemberKind.Interface;
113                         }
114                 }
115
116                 public bool IsClass {
117                         get {
118                                 return Kind == MemberKind.Class;
119                         }
120                 }
121
122                 public bool IsConstantCompatible {
123                         get {
124                                 if ((Kind & (MemberKind.Enum | MemberKind.Class | MemberKind.Interface | MemberKind.Delegate | MemberKind.ArrayType)) != 0)
125                                         return true;
126
127                                 return TypeManager.IsPrimitiveType (this) || this == TypeManager.decimal_type || this == InternalType.Dynamic;
128                         }
129                 }
130
131                 public bool IsDelegate {
132                         get {
133                                 return Kind == MemberKind.Delegate;
134                         }
135                 }
136
137                 public bool IsEnum {
138                         get { return Kind == MemberKind.Enum; }
139                 }
140
141                 // TODO: Should probably do
142                 // IsGenericType -- recursive
143                 // HasTypeParameter -- non-recursive
144                 public bool IsGenericOrParentIsGeneric {
145                         get {
146                                 var ts = this;
147                                 do {
148                                         if (ts.IsGeneric)
149                                                 return true;
150                                         ts = ts.declaringType;
151                                 } while (ts != null);
152
153                                 return false;
154                         }
155                 }
156
157                 public bool IsGenericParameter {
158                         get { return Kind == MemberKind.TypeParameter; }
159                 }
160
161                 public bool IsNested {
162                         get { return declaringType != null && Kind != MemberKind.TypeParameter; }
163                 }
164
165                 public bool IsPointer {
166                         get {
167                                 return Kind == MemberKind.PointerType;
168                         }
169                 }
170
171                 public bool IsSealed {
172                         get { return (Modifiers & Modifiers.SEALED) != 0; }
173                 }
174
175                 public bool IsStruct {
176                         get { 
177                                 return Kind == MemberKind.Struct;
178                         }
179                 }
180
181                 public bool IsTypeBuilder {
182                         get {
183                                 var meta = GetMetaInfo().GetType ();
184                                 return meta == TypeBuilder || meta == GenericTypeBuilder;
185                         }
186                 }
187
188                 public MemberCache MemberCache {
189                         get {
190                                 if (cache == null || (state & StateFlags.PendingMemberCacheMembers) != 0)
191                                         InitializeMemberCache (false);
192
193                                 return cache;
194                         }
195                         set {
196                                 if (cache != null)
197                                         throw new InternalErrorException ("Membercache reset");
198
199                                 cache = value;
200                         }
201                 }
202
203                 public MemberCache MemberCacheTypes {
204                         get {
205                                 if (cache == null)
206                                         InitializeMemberCache (true);
207
208                                 return cache;
209                         }
210                 }       
211
212                 public new ITypeDefinition MemberDefinition {
213                         get {
214                                 return (ITypeDefinition) definition;
215                         }
216                 }
217
218                 // TODO: Wouldn't be better to rely on cast to InflatedTypeSpec and
219                 // remove the property, YES IT WOULD !!!
220                 public virtual TypeSpec[] TypeArguments {
221                         get { return TypeSpec.EmptyTypes; }
222                 }
223
224                 #endregion
225
226                 public bool AddInterface (TypeSpec iface)
227                 {
228                         if ((state & StateFlags.InterfacesExpanded) != 0)
229                                 throw new InternalErrorException ("Modifying expanded interface list");
230
231                         if (ifaces == null) {
232                                 ifaces = new List<TypeSpec> () { iface };
233                                 return true;
234                         }
235
236                         if (!ifaces.Contains (iface)) {
237                                 ifaces.Add (iface);
238                                 return true;
239                         }
240
241                         return false;
242                 }
243
244                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
245                 {
246                         if (Kind != MemberKind.Class)
247                                 throw new InternalErrorException ();
248
249                         if (!pa.IsDefined)
250                                 return Attribute.DefaultUsageAttribute;
251
252                         AttributeUsageAttribute aua = null;
253                         var type = this;
254                         while (type != null) {
255                                 aua = type.MemberDefinition.GetAttributeUsage (pa);
256                                 if (aua != null)
257                                         break;
258
259                                 type = type.BaseType;
260                         }
261
262                         return aua;
263                 }
264
265                 public virtual Type GetMetaInfo ()
266                 {
267                         return info;
268                 }
269
270                 public virtual TypeSpec GetDefinition ()
271                 {
272                         return this;
273                 }
274
275                 public override string GetSignatureForError ()
276                 {
277                         string s;
278
279                         if (IsNested) {
280                                 s = DeclaringType.GetSignatureForError ();
281                         } else if (MemberDefinition is AnonymousTypeClass) {
282                                 return ((AnonymousTypeClass) MemberDefinition).GetSignatureForError ();
283                         } else {
284                                 s = MemberDefinition.Namespace;
285                         }
286
287                         if (!string.IsNullOrEmpty (s))
288                                 s += ".";
289
290                         return s + Name + GetTypeNameSignature ();
291                 }
292
293                 protected virtual string GetTypeNameSignature ()
294                 {
295                         if (!IsGeneric)
296                                 return null;
297
298                         return "<" + TypeManager.CSharpName (MemberDefinition.TypeParameters) + ">";
299                 }
300
301                 public bool ImplementsInterface (TypeSpec iface, bool variantly)
302                 {
303                         var t = this;
304                         do {
305                                 if (t.Interfaces != null) {     // TODO: Try t.iface
306                                         foreach (TypeSpec i in t.Interfaces) {
307                                                 if (i == iface || TypeSpecComparer.IsEqual (i, iface))
308                                                         return true;
309
310                                                 if (variantly && TypeSpecComparer.Variant.IsEqual (i, iface))
311                                                         return true;
312                                         }
313                                 }
314
315                                 t = t.BaseType;
316                         } while (t != null);
317
318                         return false;
319                 }
320
321                 protected virtual void InitializeMemberCache (bool onlyTypes)
322                 {
323                         MemberDefinition.LoadMembers (this, onlyTypes, ref cache);
324
325                         if (onlyTypes)
326                                 state |= StateFlags.PendingMemberCacheMembers;
327                         else
328                                 state &= ~StateFlags.PendingMemberCacheMembers;
329                 }
330
331                 //
332                 // Is @baseClass base implementation of @type. With enabled @dynamicIsEqual the slower
333                 // comparison is used to hide differences between `object' and `dynamic' for generic
334                 // types. Should not be used for comparisons where G<object> != G<dynamic>
335                 //
336                 public static bool IsBaseClass (TypeSpec type, TypeSpec baseClass, bool dynamicIsObject)
337                 {
338                         if (dynamicIsObject && baseClass.IsGeneric) {
339                                 //
340                                 // Returns true for a hierarchies like this when passing baseClass of A<dynamic>
341                                 //
342                                 // class B : A<object> {}
343                                 //
344                                 while (type != null) {
345                                         type = type.BaseType;
346                                         if (TypeSpecComparer.IsEqual (type, baseClass))
347                                                 return true;
348                                 }
349
350                                 return false;
351                         }
352
353                         while (type != null) {
354                                 type = type.BaseType;
355                                 if (type == baseClass)
356                                         return true;
357                         }
358
359                         return false;
360                 }
361
362                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
363                 {
364                         var targs = IsGeneric ? MemberDefinition.TypeParameters : TypeSpec.EmptyTypes;
365
366                         //
367                         // When inflating nested type from inside the type instance will be same
368                         // because type parameters are same for all nested types
369                         //
370                         if (DeclaringType == inflator.TypeInstance)
371                                 return MakeGenericType (targs);
372
373                         return new InflatedTypeSpec (this, inflator.TypeInstance, targs);
374                 }
375
376                 public InflatedTypeSpec MakeGenericType (TypeSpec[] targs)
377                 {
378                         if (targs.Length == 0 && !IsNested)
379                                 throw new ArgumentException ("Empty type arguments for type " + GetSignatureForError ());
380
381                         InflatedTypeSpec instance;
382
383                         if (inflated_instances == null)
384                                 inflated_instances = new Dictionary<TypeSpec[], InflatedTypeSpec> (TypeSpecComparer.Default);
385
386                         if (!inflated_instances.TryGetValue (targs, out instance)) {
387                                 if (GetDefinition () != this && !IsNested)
388                                         throw new InternalErrorException ("`{0}' must be type definition or nested non-inflated type to MakeGenericType",
389                                                 GetSignatureForError ());
390
391                                 instance = new InflatedTypeSpec (this, declaringType, targs);
392                                 inflated_instances.Add (targs, instance);
393                         }
394
395                         return instance;
396                 }
397
398                 public virtual TypeSpec Mutate (TypeParameterMutator mutator)
399                 {
400                         return this;
401                 }
402
403                 public void SetMetaInfo (Type info)
404                 {
405                         if (this.info != null)
406                                 throw new InternalErrorException ("MetaInfo reset");
407
408                         this.info = info;
409                 }
410
411                 public void SetExtensionMethodContainer ()
412                 {
413                         modifiers |= Modifiers.METHOD_EXTENSION;
414                 }
415         }
416
417         public class PredefinedTypeSpec : TypeSpec
418         {
419                 string name;
420                 string ns;
421
422                 public PredefinedTypeSpec (MemberKind kind, string ns, string name)
423                         : base (kind, null, null, null, Modifiers.PUBLIC)
424                 {
425                         if (kind == MemberKind.Struct)
426                                 modifiers |= Modifiers.SEALED;
427
428                         this.name = name;
429                         this.ns = ns;
430                 }
431
432                 #region Properties
433
434                 public override int Arity {
435                         get {
436                                 return 0;
437                         }
438                 }
439
440                 public override string Name {
441                         get {
442                                 return name;
443                         }
444                 }
445
446                 public string Namespace {
447                         get {
448                                 return ns;
449                         }
450                 }
451
452                 #endregion
453
454                 public override string GetSignatureForError ()
455                 {
456                         switch (name) {
457                         case "Int32": return "int";
458                         case "Int64": return "long";
459                         case "String": return "string";
460                         case "Boolean": return "bool";
461                         case "Void": return "void";
462                         case "Object": return "object";
463                         case "UInt32": return "uint";
464                         case "Int16": return "short";
465                         case "UInt16": return "ushort";
466                         case "UInt64": return "ulong";
467                         case "Single": return "float";
468                         case "Double": return "double";
469                         case "Decimal": return "decimal";
470                         case "Char": return "char";
471                         case "Byte": return "byte";
472                         case "SByte": return "sbyte";
473                         }
474
475                         return ns + "." + name;
476                 }
477
478                 public void SetDefinition (ITypeDefinition td, Type type)
479                 {
480                         this.definition = td;
481                         this.info = type;
482                 }
483
484                 public void SetDefinition (TypeSpec ts)
485                 {
486                         this.definition = ts.MemberDefinition;
487                         this.info = ts.GetMetaInfo ();
488                         this.BaseType = ts.BaseType;
489                         this.Interfaces = ts.Interfaces;
490                 }
491         }
492
493         static class TypeSpecComparer
494         {
495                 //
496                 // Does strict reference comparion only
497                 //
498                 public static readonly DefaultImpl Default = new DefaultImpl ();
499
500                 public class DefaultImpl : IEqualityComparer<TypeSpec[]>
501                 {
502                         #region IEqualityComparer<TypeSpec[]> Members
503
504                         bool IEqualityComparer<TypeSpec[]>.Equals (TypeSpec[] x, TypeSpec[] y)
505                         {
506                                 if (x == y)
507                                         return true;
508
509                                 if (x.Length != y.Length)
510                                         return false;
511
512                                 for (int i = 0; i < x.Length; ++i)
513                                         if (x[i] != y[i])
514                                                 return false;
515
516                                 return true;
517                         }
518
519                         int IEqualityComparer<TypeSpec[]>.GetHashCode (TypeSpec[] obj)
520                         {
521                                 int hash = 0;
522                                 for (int i = 0; i < obj.Length; ++i)
523                                         hash = (hash << 5) - hash + obj[i].GetHashCode ();
524
525                                 return hash;
526                         }
527
528                         #endregion
529                 }
530
531                 //
532                 // When comparing type signature of overrides or overloads
533                 // this version tolerates different MVARs at same position
534                 //
535                 public static class Override
536                 {
537                         public static bool IsEqual (TypeSpec a, TypeSpec b)
538                         {
539                                 if (a == b)
540                                         return true;
541
542                                 //
543                                 // Consider the following example:
544                                 //
545                                 //     public abstract class A
546                                 //     {
547                                 //        public abstract T Foo<T>();
548                                 //     }
549                                 //
550                                 //     public class B : A
551                                 //     {
552                                 //        public override U Foo<T>() { return default (U); }
553                                 //     }
554                                 //
555                                 // Here, `T' and `U' are method type parameters from different methods
556                                 // (A.Foo and B.Foo), so both `==' and Equals() will fail.
557                                 //
558                                 // However, since we're determining whether B.Foo() overrides A.Foo(),
559                                 // we need to do a signature based comparision and consider them equal.
560                                 //
561
562                                 var tp_a = a as TypeParameterSpec;
563                                 if (tp_a != null) {
564                                         var tp_b = b as TypeParameterSpec;
565                                         return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
566                                 }
567
568                                 var ac_a = a as ArrayContainer;
569                                 if (ac_a != null) {
570                                         var ac_b = b as ArrayContainer;
571                                         return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
572                                 }
573
574                                 if (a == InternalType.Dynamic || b == InternalType.Dynamic)
575                                         return b == TypeManager.object_type || a == TypeManager.object_type;
576
577                                 if (a.MemberDefinition != b.MemberDefinition)
578                                         return false;
579
580                                 do {
581                                         for (int i = 0; i < a.TypeArguments.Length; ++i) {
582                                                 if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
583                                                         return false;
584                                         }
585
586                                         a = a.DeclaringType;
587                                         b = b.DeclaringType;
588                                 } while (a != null);
589
590                                 return true;
591                         }
592
593                         //
594                         // Compares unordered arrays
595                         //
596                         public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
597                         {
598                                 if (a == b)
599                                         return true;
600
601                                 if (a == null || b == null || a.Length != b.Length)
602                                         return false;
603
604                                 for (int ai = 0; ai < a.Length; ++ai) {
605                                         bool found = false;
606                                         for (int bi = 0; bi < b.Length; ++bi) {
607                                                 if (IsEqual (a[ai], b[bi])) {
608                                                         found = true;
609                                                         break;
610                                                 }
611                                         }
612
613                                         if (!found)
614                                                 return false;
615                                 }
616
617                                 return true;
618                         }
619
620                         public static bool IsEqual (AParametersCollection a, AParametersCollection b)
621                         {
622                                 if (a == b)
623                                         return true;
624
625                                 if (a.Count != b.Count)
626                                         return false;
627
628                                 for (int i = 0; i < a.Count; ++i) {
629                                         if (!IsEqual (a.Types[i], b.Types[i]))
630                                                 return false;
631
632                                         const Parameter.Modifier ref_out = Parameter.Modifier.REF | Parameter.Modifier.OUT;
633                                         if ((a.FixedParameters[i].ModFlags & ref_out) != (b.FixedParameters[i].ModFlags & ref_out))
634                                                 return false;
635                                 }
636
637                                 return true;
638                         }
639                 }
640
641                 //
642                 // Type variance equality comparison
643                 //
644                 public static class Variant
645                 {
646                         public static bool IsEqual (TypeSpec type1, TypeSpec type2)
647                         {
648                                 if (!type1.IsGeneric || !type2.IsGeneric)
649                                         return false;
650
651                                 var target_type_def = type2.MemberDefinition;
652                                 if (type1.MemberDefinition != target_type_def)
653                                         return false;
654
655                                 var t1_targs = type1.TypeArguments;
656                                 var t2_targs = type2.TypeArguments;
657                                 var targs_definition = target_type_def.TypeParameters;
658
659                                 if (!type1.IsInterface && !type1.IsDelegate) {
660                                         return false;
661                                 }
662
663                                 for (int i = 0; i < targs_definition.Length; ++i) {
664                                         Variance v = targs_definition[i].Variance;
665                                         if (v == Variance.None) {
666                                                 if (t1_targs[i] == t2_targs[i])
667                                                         continue;
668                                                 return false;
669                                         }
670
671                                         if (v == Variance.Covariant) {
672                                                 if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t1_targs[i]), t2_targs[i]))
673                                                         return false;
674                                         } else if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t2_targs[i]), t1_targs[i])) {
675                                                 return false;
676                                         }
677                                 }
678
679                                 return true;
680                         }
681                 }
682
683                 //
684                 // Checks whether two generic instances may become equal for some
685                 // particular instantiation (26.3.1).
686                 //
687                 public static class Unify
688                 {
689                         //
690                         // Either @a or @b must be generic type
691                         //
692                         public static bool IsEqual (TypeSpec a, TypeSpec b)
693                         {
694                                 if (a.MemberDefinition != b.MemberDefinition)
695                                         return false;
696
697                                 var ta = a.TypeArguments;
698                                 var tb = b.TypeArguments;
699                                 for (int i = 0; i < ta.Length; i++) {
700                                         if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
701                                                 return false;
702                                 }
703
704                                 return true;
705                         }
706
707                         static bool ContainsTypeParameter (TypeSpec tparam, TypeSpec type)
708                         {
709                                 TypeSpec[] targs = type.TypeArguments;
710                                 for (int i = 0; i < targs.Length; i++) {
711                                         if (tparam == targs[i])
712                                                 return true;
713
714                                         if (ContainsTypeParameter (tparam, targs[i]))
715                                                 return true;
716                                 }
717
718                                 return false;
719                         }
720
721                         /// <summary>
722                         ///   Check whether `a' and `b' may become equal generic types.
723                         ///   The algorithm to do that is a little bit complicated.
724                         /// </summary>
725                         static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
726                         {
727                                 if (a.IsGenericParameter) {
728                                         //
729                                         // If a is an array of a's type, they may never
730                                         // become equal.
731                                         //
732                                         if (b.IsArray)
733                                                 return false;
734
735                                         //
736                                         // If b is a generic parameter or an actual type,
737                                         // they may become equal:
738                                         //
739                                         //    class X<T,U> : I<T>, I<U>
740                                         //    class X<T> : I<T>, I<float>
741                                         // 
742                                         if (b.IsGenericParameter)
743                                                 return a.DeclaringType == b.DeclaringType;
744
745                                         //
746                                         // We're now comparing a type parameter with a
747                                         // generic instance.  They may become equal unless
748                                         // the type parameter appears anywhere in the
749                                         // generic instance:
750                                         //
751                                         //    class X<T,U> : I<T>, I<X<U>>
752                                         //        -> error because you could instanciate it as
753                                         //           X<X<int>,int>
754                                         //
755                                         //    class X<T> : I<T>, I<X<T>> -> ok
756                                         //
757
758                                         return !ContainsTypeParameter (a, b);
759                                 }
760
761                                 if (b.IsGenericParameter)
762                                         return MayBecomeEqualGenericTypes (b, a);
763
764                                 //
765                                 // At this point, neither a nor b are a type parameter.
766                                 //
767                                 // If one of them is a generic instance, compare them (if the
768                                 // other one is not a generic instance, they can never
769                                 // become equal).
770                                 //
771                                 if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
772                                         return IsEqual (a, b);
773
774                                 //
775                                 // If both of them are arrays.
776                                 //
777                                 var a_ac = a as ArrayContainer;
778                                 if (a_ac != null) {
779                                         var b_ac = b as ArrayContainer;
780                                         if (b_ac == null || a_ac.Rank != b_ac.Rank)
781                                                 return false;
782
783                                         return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
784                                 }
785
786                                 //
787                                 // Ok, two ordinary types.
788                                 //
789                                 return false;
790                         }
791                 }
792
793                 public static bool Equals (TypeSpec[] x, TypeSpec[] y)
794                 {
795                         if (x == y)
796                                 return true;
797
798                         if (x.Length != y.Length)
799                                 return false;
800
801                         for (int i = 0; i < x.Length; ++i)
802                                 if (!IsEqual (x[i], y[i]))
803                                         return false;
804
805                         return true;
806                 }
807
808                 //
809                 // Identity type conversion
810                 //
811                 // Default reference comparison, it has to be used when comparing
812                 // two possible dynamic/internal types
813                 //
814                 public static bool IsEqual (TypeSpec a, TypeSpec b)
815                 {
816                         if (a == b) {
817                                 // This also rejects dynamic == dynamic
818                                 return a.Kind != MemberKind.InternalCompilerType || a == InternalType.Dynamic;
819                         }
820
821                         //
822                         // object and dynamic are considered equivalent there is an identity conversion
823                         // between object and dynamic, and between constructed types that are the same
824                         // when replacing all occurences of dynamic with object.
825                         //
826                         if (a == InternalType.Dynamic || b == InternalType.Dynamic)
827                                 return b == TypeManager.object_type || a == TypeManager.object_type;
828
829                         if (a == null)
830                                 return false;
831
832                         if (a.IsArray) {
833                                 var a_a = (ArrayContainer) a;
834                                 var b_a = b as ArrayContainer;
835                                 if (b_a == null)
836                                         return false;
837
838                                 return IsEqual (a_a.Element, b_a.Element) && a_a.Rank == b_a.Rank;
839                         }
840
841                         if (!a.IsGeneric || b == null || !b.IsGeneric)
842                                 return false;
843
844                         if (a.MemberDefinition != b.MemberDefinition)
845                                 return false;
846
847                         do {
848                                 if (!Equals (a.TypeArguments, b.TypeArguments))
849                                         return false;
850
851                                 a = a.DeclaringType;
852                                 b = b.DeclaringType;
853                         } while (a != null);
854
855                         return true;
856                 }
857         }
858
859         public interface ITypeDefinition : IMemberDefinition
860         {
861                 string Namespace { get; }
862                 int TypeParametersCount { get; }
863                 TypeParameterSpec[] TypeParameters { get; }
864
865                 TypeSpec GetAttributeCoClass ();
866                 string GetAttributeDefaultMember ();
867                 AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
868                 void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache);
869         }
870
871         class InternalType : TypeSpec, ITypeDefinition
872         {
873                 public static readonly InternalType AnonymousMethod = new InternalType ("anonymous method");
874                 public static readonly InternalType Arglist = new InternalType ("__arglist");
875                 public static readonly InternalType Dynamic = new InternalType ("dynamic", null);
876                 public static readonly InternalType MethodGroup = new InternalType ("method group");
877                 public static readonly InternalType Null = new InternalType ("null");
878                 public static readonly InternalType FakeInternalType = new InternalType ("<fake$type>");
879
880                 readonly string name;
881
882                 InternalType (string name, MemberCache cache)
883                         : this (name)
884                 {
885                         this.cache = cache;
886                 }
887
888                 InternalType (string name)
889                         : base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
890                 {
891                         this.name = name;
892                         this.definition = this;
893                         cache = MemberCache.Empty;
894
895                         // Make all internal types CLS-compliant, non-obsolete
896                         state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected)) | StateFlags.CLSCompliant;
897                 }
898
899                 #region Properties
900
901                 public override int Arity {
902                         get {
903                                 return 0;
904                         }
905                 }
906
907                 System.Reflection.Assembly IMemberDefinition.Assembly {
908                         get {
909                                 throw new NotImplementedException ();
910                         }
911                 }
912
913                 bool IMemberDefinition.IsImported {
914                         get {
915                                 return false;
916                         }
917                 }
918
919                 public override string Name {
920                         get {
921                                 return name;
922                         }
923                 }
924
925                 string ITypeDefinition.Namespace {
926                         get {
927                                 return null;
928                         }
929                 }
930
931                 int ITypeDefinition.TypeParametersCount {
932                         get {
933                                 return 0;
934                         }
935                 }
936
937                 TypeParameterSpec[] ITypeDefinition.TypeParameters {
938                         get {
939                                 return null;
940                         }
941                 }
942
943                 #endregion
944
945                 public override string GetSignatureForError ()
946                 {
947                         return name;
948                 }
949
950                 #region ITypeDefinition Members
951
952                 TypeSpec ITypeDefinition.GetAttributeCoClass ()
953                 {
954                         return null;
955                 }
956
957                 string ITypeDefinition.GetAttributeDefaultMember ()
958                 {
959                         return null;
960                 }
961
962                 AttributeUsageAttribute ITypeDefinition.GetAttributeUsage (PredefinedAttribute pa)
963                 {
964                         return null;
965                 }
966
967                 void ITypeDefinition.LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
968                 {
969                         throw new NotImplementedException ();
970                 }
971
972                 string[] IMemberDefinition.ConditionalConditions ()
973                 {
974                         return null;
975                 }
976
977                 ObsoleteAttribute IMemberDefinition.GetAttributeObsolete ()
978                 {
979                         return null;
980                 }
981
982                 bool IMemberDefinition.IsNotCLSCompliant ()
983                 {
984                         return false;
985                 }
986
987                 void IMemberDefinition.SetIsAssigned ()
988                 {
989                 }
990
991                 void IMemberDefinition.SetIsUsed ()
992                 {
993                 }
994
995                 #endregion
996         }
997
998         public abstract class ElementTypeSpec : TypeSpec, ITypeDefinition
999         {
1000                 protected ElementTypeSpec (MemberKind kind, TypeSpec element, Type info)
1001                         : base (kind, element.DeclaringType, null, info, element.Modifiers)
1002                 {
1003                         this.Element = element;
1004                         if (element == InternalType.Dynamic || element.HasDynamicElement)
1005                                 state |= StateFlags.HasDynamicElement;
1006
1007                         // Has to use its own type definition instead of just element definition to
1008                         // correctly identify itself for cases like x.MemberDefininition == predefined.MemberDefinition
1009                         this.definition = this;
1010
1011                         cache = MemberCache.Empty;
1012                 }
1013
1014                 #region Properties
1015
1016                 public TypeSpec Element { get; private set; }
1017
1018                 public override string Name {
1019                         get {
1020                                 throw new NotSupportedException ();
1021                         }
1022                 }
1023
1024                 #endregion
1025
1026                 public override ObsoleteAttribute GetAttributeObsolete ()
1027                 {
1028                         return Element.GetAttributeObsolete ();
1029                 }
1030
1031                 protected virtual string GetPostfixSignature ()
1032                 {
1033                         return null;
1034                 }
1035
1036                 public override string GetSignatureForError ()
1037                 {
1038                         return Element.GetSignatureForError () + GetPostfixSignature ();
1039                 }
1040
1041                 public override TypeSpec Mutate (TypeParameterMutator mutator)
1042                 {
1043                         var me = Element.Mutate (mutator);
1044                         if (me == Element)
1045                                 return this;
1046
1047                         var mutated = (ElementTypeSpec) MemberwiseClone ();
1048                         mutated.Element = me;
1049                         mutated.info = null;
1050                         return mutated;
1051                 }
1052
1053                 #region ITypeDefinition Members
1054
1055                 System.Reflection.Assembly IMemberDefinition.Assembly {
1056                         get {
1057                                 return Element.Assembly;
1058                         }
1059                 }
1060
1061                 public string Namespace {
1062                         get { throw new NotImplementedException (); }
1063                 }
1064
1065                 public int TypeParametersCount {
1066                         get {
1067                                 return 0;
1068                         }
1069                 }
1070
1071                 public TypeParameterSpec[] TypeParameters {
1072                         get {
1073                                 throw new NotSupportedException ();
1074                         }
1075                 }
1076
1077                 public TypeSpec GetAttributeCoClass ()
1078                 {
1079                         return Element.MemberDefinition.GetAttributeCoClass ();
1080                 }
1081
1082                 public string GetAttributeDefaultMember ()
1083                 {
1084                         return Element.MemberDefinition.GetAttributeDefaultMember ();
1085                 }
1086
1087                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1088                 {
1089                         Element.MemberDefinition.LoadMembers (declaringType, onlyTypes, ref cache);
1090                 }
1091
1092                 public bool IsImported {
1093                         get {
1094                                 return Element.MemberDefinition.IsImported;
1095                         }
1096                 }
1097
1098                 public string[] ConditionalConditions ()
1099                 {
1100                         return Element.MemberDefinition.ConditionalConditions ();
1101                 }
1102
1103                 bool IMemberDefinition.IsNotCLSCompliant ()
1104                 {
1105                         return Element.MemberDefinition.IsNotCLSCompliant ();
1106                 }
1107
1108                 public void SetIsAssigned ()
1109                 {
1110                         Element.MemberDefinition.SetIsAssigned ();
1111                 }
1112
1113                 public void SetIsUsed ()
1114                 {
1115                         Element.MemberDefinition.SetIsUsed ();
1116                 }
1117
1118                 #endregion
1119         }
1120
1121         public class ArrayContainer : ElementTypeSpec
1122         {
1123                 struct TypeRankPair : IEquatable<TypeRankPair>
1124                 {
1125                         TypeSpec ts;
1126                         int rank;
1127
1128                         public TypeRankPair (TypeSpec ts, int rank)
1129                         {
1130                                 this.ts = ts;
1131                                 this.rank = rank;
1132                         }
1133
1134                         public override int GetHashCode ()
1135                         {
1136                                 return ts.GetHashCode () ^ rank.GetHashCode ();
1137                         }
1138
1139                         #region IEquatable<Tuple<T1,T2>> Members
1140
1141                         public bool Equals (TypeRankPair other)
1142                         {
1143                                 return other.ts == ts && other.rank == rank;
1144                         }
1145
1146                         #endregion
1147                 }
1148
1149                 readonly int rank;
1150                 static Dictionary<TypeRankPair, ArrayContainer> instances = new Dictionary<TypeRankPair, ArrayContainer> ();
1151
1152                 private ArrayContainer (TypeSpec element, int rank)
1153                         : base (MemberKind.ArrayType, element, null)
1154                 {
1155                         this.rank = rank;
1156                 }
1157
1158                 public int Rank {
1159                         get {
1160                                 return rank;
1161                         }
1162                 }
1163
1164                 public System.Reflection.MethodInfo GetConstructor ()
1165                 {
1166                         var mb = RootContext.ToplevelTypes.Builder;
1167
1168                         var arg_types = new Type[rank];
1169                         for (int i = 0; i < rank; i++)
1170                                 arg_types[i] = TypeManager.int32_type.GetMetaInfo ();
1171
1172                         var ctor = mb.GetArrayMethod (
1173                                 GetMetaInfo (), ".ctor",
1174                                 System.Reflection.CallingConventions.HasThis,
1175                                 null, arg_types);
1176
1177                         return ctor;
1178                 }
1179
1180                 public System.Reflection.MethodInfo GetAddressMethod ()
1181                 {
1182                         var mb = RootContext.ToplevelTypes.Builder;
1183
1184                         var arg_types = new Type[rank];
1185                         for (int i = 0; i < rank; i++)
1186                                 arg_types[i] = TypeManager.int32_type.GetMetaInfo ();
1187
1188                         var address = mb.GetArrayMethod (
1189                                 GetMetaInfo (), "Address",
1190                                 System.Reflection.CallingConventions.HasThis | System.Reflection.CallingConventions.Standard,
1191                                 ReferenceContainer.MakeType (Element).GetMetaInfo (), arg_types);
1192
1193                         return address;
1194                 }
1195
1196                 public System.Reflection.MethodInfo GetGetMethod ()
1197                 {
1198                         var mb = RootContext.ToplevelTypes.Builder;
1199
1200                         var arg_types = new Type[rank];
1201                         for (int i = 0; i < rank; i++)
1202                                 arg_types[i] = TypeManager.int32_type.GetMetaInfo ();
1203
1204                         var get = mb.GetArrayMethod (
1205                                 GetMetaInfo (), "Get",
1206                                 System.Reflection.CallingConventions.HasThis | System.Reflection.CallingConventions.Standard,
1207                                 Element.GetMetaInfo (), arg_types);
1208
1209                         return get;
1210                 }
1211
1212                 public System.Reflection.MethodInfo GetSetMethod ()
1213                 {
1214                         var mb = RootContext.ToplevelTypes.Builder;
1215
1216                         var arg_types = new Type[rank + 1];
1217                         for (int i = 0; i < rank; i++)
1218                                 arg_types[i] = TypeManager.int32_type.GetMetaInfo ();
1219
1220                         arg_types[rank] = Element.GetMetaInfo ();
1221
1222                         var set = mb.GetArrayMethod (
1223                                 GetMetaInfo (), "Set",
1224                                 System.Reflection.CallingConventions.HasThis | System.Reflection.CallingConventions.Standard,
1225                                 TypeManager.void_type.GetMetaInfo (), arg_types);
1226
1227                         return set;
1228                 }
1229
1230                 public override Type GetMetaInfo ()
1231                 {
1232                         if (info == null) {
1233                                 if (rank == 1)
1234                                         info = Element.GetMetaInfo ().MakeArrayType ();
1235                                 else
1236                                         info = Element.GetMetaInfo ().MakeArrayType (rank);
1237                         }
1238
1239                         return info;
1240                 }
1241
1242                 protected override string GetPostfixSignature()
1243                 {
1244                         return GetPostfixSignature (rank);
1245                 }
1246
1247                 public static string GetPostfixSignature (int rank)
1248                 {
1249                         StringBuilder sb = new StringBuilder ();
1250                         sb.Append ("[");
1251                         for (int i = 1; i < rank; i++) {
1252                                 sb.Append (",");
1253                         }
1254                         sb.Append ("]");
1255
1256                         return sb.ToString ();
1257                 }
1258
1259                 public static ArrayContainer MakeType (TypeSpec element)
1260                 {
1261                         return MakeType (element, 1);
1262                 }
1263
1264                 public static ArrayContainer MakeType (TypeSpec element, int rank)
1265                 {
1266                         ArrayContainer ac;
1267                         var key = new TypeRankPair (element, rank);
1268                         if (!instances.TryGetValue (key, out ac)) {
1269                                 ac = new ArrayContainer (element, rank) {
1270                                         BaseType = TypeManager.array_type
1271                                 };
1272
1273                                 instances.Add (key, ac);
1274                         }
1275
1276                         return ac;
1277                 }
1278
1279                 public static void Reset ()
1280                 {
1281                         instances = new Dictionary<TypeRankPair, ArrayContainer> ();
1282                 }
1283         }
1284
1285         class ReferenceContainer : ElementTypeSpec
1286         {
1287                 static Dictionary<TypeSpec, ReferenceContainer> instances = new Dictionary<TypeSpec, ReferenceContainer> ();
1288
1289                 private ReferenceContainer (TypeSpec element)
1290                         : base (MemberKind.Class, element, null)        // TODO: Kind.Class is most likely wrong
1291                 {
1292                 }
1293
1294                 public override Type GetMetaInfo ()
1295                 {
1296                         if (info == null) {
1297                                 info = Element.GetMetaInfo ().MakeByRefType ();
1298                         }
1299
1300                         return info;
1301                 }
1302
1303                 public static ReferenceContainer MakeType (TypeSpec element)
1304                 {
1305                         ReferenceContainer pc;
1306                         if (!instances.TryGetValue (element, out pc)) {
1307                                 pc = new ReferenceContainer (element);
1308                                 instances.Add (element, pc);
1309                         }
1310
1311                         return pc;
1312                 }
1313
1314                 public static void Reset ()
1315                 {
1316                         instances = new Dictionary<TypeSpec, ReferenceContainer> ();
1317                 }
1318         }
1319
1320         class PointerContainer : ElementTypeSpec
1321         {
1322                 static Dictionary<TypeSpec, PointerContainer> instances = new Dictionary<TypeSpec, PointerContainer> ();
1323
1324                 private PointerContainer (TypeSpec element)
1325                         : base (MemberKind.PointerType, element, null)
1326                 {
1327                         // It's never CLS-Compliant
1328                         state &= ~StateFlags.CLSCompliant_Undetected;
1329                 }
1330
1331                 public override Type GetMetaInfo ()
1332                 {
1333                         if (info == null) {
1334                                 info = Element.GetMetaInfo ().MakePointerType ();
1335                         }
1336
1337                         return info;
1338                 }
1339
1340                 protected override string GetPostfixSignature()
1341                 {
1342                         return "*";
1343                 }
1344
1345                 public static PointerContainer MakeType (TypeSpec element)
1346                 {
1347                         PointerContainer pc;
1348                         if (!instances.TryGetValue (element, out pc)) {
1349                                 pc = new PointerContainer (element);
1350                                 instances.Add (element, pc);
1351                         }
1352
1353                         return pc;
1354                 }
1355
1356                 public static void Reset ()
1357                 {
1358                         instances = new Dictionary<TypeSpec, PointerContainer> ();
1359                 }
1360         }
1361 }