Merge pull request #642 from Ventero/CleanCopyLocal
[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 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
10 //
11
12 using System;
13 using System.Collections.Generic;
14 using System.Text;
15 using System.Linq;
16
17 #if STATIC
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 #else
21 using MetaType = System.Type;
22 using System.Reflection;
23 #endif
24
25 namespace Mono.CSharp
26 {
27         //
28         // Inflated or non-inflated representation of any type. 
29         //
30         public class TypeSpec : MemberSpec
31         {
32                 protected MetaType info;
33                 protected MemberCache cache;
34                 protected IList<TypeSpec> ifaces;
35                 TypeSpec base_type;
36
37                 Dictionary<TypeSpec[], InflatedTypeSpec> inflated_instances;
38
39                 public static readonly TypeSpec[] EmptyTypes = new TypeSpec[0];
40
41 #if !STATIC
42                 // Reflection Emit hacking
43                 static readonly Type TypeBuilder;
44                 static readonly Type GenericTypeBuilder;
45
46                 static TypeSpec ()
47                 {
48                         var assembly = typeof (object).Assembly;
49                         TypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilder");
50                         GenericTypeBuilder = assembly.GetType ("System.Reflection.MonoGenericClass");
51                         if (GenericTypeBuilder == null)
52                                 GenericTypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilderInstantiation");
53                 }
54 #endif
55
56                 public TypeSpec (MemberKind kind, TypeSpec declaringType, ITypeDefinition definition, MetaType info, Modifiers modifiers)
57                         : base (kind, declaringType, definition, modifiers)
58                 {
59                         this.declaringType = declaringType;
60                         this.info = info;
61
62                         if (definition != null && definition.TypeParametersCount > 0)
63                                 state |= StateFlags.IsGeneric;
64                 }
65
66                 #region Properties
67
68                 public override int Arity {
69                         get {
70                                 return MemberDefinition.TypeParametersCount;
71                         }
72                 }
73
74                 public virtual TypeSpec BaseType {
75                         get {
76                                 return base_type;
77                         }
78                         set {
79                                 base_type = value;
80                         }
81                 }
82
83                 public virtual BuiltinTypeSpec.Type BuiltinType {
84                         get {
85                                 return BuiltinTypeSpec.Type.None;
86                         }
87                 }
88
89                 public bool HasDynamicElement {
90                         get {
91                                 return (state & StateFlags.HasDynamicElement) != 0;
92                         }
93                 }
94
95                 //
96                 // Returns a list of all interfaces including
97                 // interfaces from base type or base interfaces
98                 //
99                 public virtual IList<TypeSpec> Interfaces {
100                         get {
101                                 if ((state & StateFlags.InterfacesImported) == 0) {
102                                         state |= StateFlags.InterfacesImported;
103
104                                         //
105                                         // Delay interfaces expansion to save memory and once all
106                                         // base types has been imported to avoid problems where
107                                         // interface references type before its base was imported
108                                         //
109                                         var imported = MemberDefinition as ImportedTypeDefinition;
110                                         if (imported != null && Kind != MemberKind.MissingType)
111                                                 imported.DefineInterfaces (this);
112
113                                 }
114
115                                 return ifaces;
116                         }
117                         set {
118                                 ifaces = value;
119                         }
120                 }
121
122                 public bool IsArray {
123                         get {
124                                 return Kind == MemberKind.ArrayType;
125                         }
126                 }
127
128                 public bool IsAttribute {
129                         get {
130                                 if (!IsClass)
131                                         return false;
132
133                                 var type = this;
134                                 do {
135                                         if (type.BuiltinType == BuiltinTypeSpec.Type.Attribute)
136                                                 return true;
137
138                                         if (type.IsGeneric)
139                                                 return false;
140                                         
141                                         type = type.base_type;
142                                 } while (type != null);
143
144                                 return false;
145                         }
146                 }
147
148                 public bool IsInterface {
149                         get {
150                                 return Kind == MemberKind.Interface;
151                         }
152                 }
153
154                 public bool IsClass {
155                         get {
156                                 return Kind == MemberKind.Class;
157                         }
158                 }
159
160                 public bool IsConstantCompatible {
161                         get {
162                                 if ((Kind & (MemberKind.Enum | MemberKind.Class | MemberKind.Interface | MemberKind.Delegate | MemberKind.ArrayType)) != 0)
163                                         return true;
164
165                                 switch (BuiltinType) {
166                                 case BuiltinTypeSpec.Type.Int:
167                                 case BuiltinTypeSpec.Type.UInt:
168                                 case BuiltinTypeSpec.Type.Long:
169                                 case BuiltinTypeSpec.Type.ULong:
170                                 case BuiltinTypeSpec.Type.Float:
171                                 case BuiltinTypeSpec.Type.Double:
172                                 case BuiltinTypeSpec.Type.Char:
173                                 case BuiltinTypeSpec.Type.Short:
174                                 case BuiltinTypeSpec.Type.Decimal:
175                                 case BuiltinTypeSpec.Type.Bool:
176                                 case BuiltinTypeSpec.Type.SByte:
177                                 case BuiltinTypeSpec.Type.Byte:
178                                 case BuiltinTypeSpec.Type.UShort:
179                                 case BuiltinTypeSpec.Type.Dynamic:
180                                         return true;
181                                 }
182
183                                 return false;
184                         }
185                 }
186
187                 public bool IsDelegate {
188                         get {
189                                 return Kind == MemberKind.Delegate;
190                         }
191                 }
192
193                 //
194                 // Returns true for instances of Expression<T>
195                 //
196                 public virtual bool IsExpressionTreeType {
197                         get {
198                                 return false;
199                         }
200                         set {
201                                 state = value ? state | StateFlags.InflatedExpressionType : state & ~StateFlags.InflatedExpressionType;
202                         }
203                 }
204
205                 public bool IsEnum {
206                         get {
207                                 return Kind == MemberKind.Enum;
208                         }
209                 }
210
211                 //
212                 // Returns true for instances of IList<T>, IEnumerable<T>, ICollection<T>
213                 //
214                 public virtual bool IsGenericIterateInterface {
215                         get {
216                                 return false;
217                         }
218                         set {
219                                 state = value ? state | StateFlags.GenericIterateInterface : state & ~StateFlags.GenericIterateInterface;
220                         }
221                 }
222
223                 //
224                 // Returns true for instances of System.Threading.Tasks.Task<T>
225                 //
226                 public virtual bool IsGenericTask {
227                         get {
228                                 return false;
229                         }
230                         set {
231                                 state = value ? state | StateFlags.GenericTask : state & ~StateFlags.GenericTask;
232                         }
233                 }
234
235                 // TODO: Should probably do
236                 // IsGenericType -- recursive
237                 // HasTypeParameter -- non-recursive
238                 public bool IsGenericOrParentIsGeneric {
239                         get {
240                                 var ts = this;
241                                 do {
242                                         if (ts.IsGeneric)
243                                                 return true;
244                                         ts = ts.declaringType;
245                                 } while (ts != null);
246
247                                 return false;
248                         }
249                 }
250
251                 public bool IsGenericParameter {
252                         get {
253                                 return Kind == MemberKind.TypeParameter;
254                         }
255                 }
256
257                 //
258                 // Returns true for instances of Nullable<T>
259                 //
260                 public virtual bool IsNullableType {
261                         get {
262                                 return false;
263                         }
264                         set {
265                                 state = value ? state | StateFlags.InflatedNullableType : state & ~StateFlags.InflatedNullableType;
266                         }
267                 }
268
269                 public bool IsNested {
270                         get { return declaringType != null && Kind != MemberKind.TypeParameter; }
271                 }
272
273                 public bool IsPointer {
274                         get {
275                                 return Kind == MemberKind.PointerType;
276                         }
277                 }
278
279                 public bool IsSealed {
280                         get { return (Modifiers & Modifiers.SEALED) != 0; }
281                 }
282
283                 public bool IsSpecialRuntimeType {
284                         get {
285                                 return (state & StateFlags.SpecialRuntimeType) != 0;
286                         }
287                         set {
288                                 state = value ? state | StateFlags.SpecialRuntimeType : state & ~StateFlags.SpecialRuntimeType;
289                         }
290                 }
291
292                 public bool IsStruct {
293                         get { 
294                                 return Kind == MemberKind.Struct;
295                         }
296                 }
297
298                 public bool IsTypeBuilder {
299                         get {
300 #if STATIC
301                                 return true;
302 #else
303                                 var meta = GetMetaInfo().GetType ();
304                                 return meta == TypeBuilder || meta == GenericTypeBuilder;
305 #endif
306                         }
307                 }
308
309                 //
310                 // Whether a type is unmanaged. This is used by the unsafe code
311                 //
312                 public bool IsUnmanaged {
313                         get {
314                                 if (IsPointer)
315                                         return ((ElementTypeSpec) this).Element.IsUnmanaged;
316
317                                 var ds = MemberDefinition as TypeDefinition;
318                                 if (ds != null)
319                                         return ds.IsUnmanagedType ();
320
321                                 if (Kind == MemberKind.Void)
322                                         return true;
323
324                                 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
325                                         return false;
326
327                                 return IsValueType (this);
328                         }
329                 }
330
331                 //
332                 // A cache of all type members (including nested types)
333                 //
334                 public MemberCache MemberCache {
335                         get {
336                                 if (cache == null || (state & StateFlags.PendingMemberCacheMembers) != 0)
337                                         InitializeMemberCache (false);
338
339                                 return cache;
340                         }
341                         set {
342                                 if (cache != null)
343                                         throw new InternalErrorException ("Membercache reset");
344
345                                 cache = value;
346                         }
347                 }
348
349                 public MemberCache MemberCacheTypes {
350                         get {
351                                 if (cache == null)
352                                         InitializeMemberCache (true);
353
354                                 return cache;
355                         }
356                 }       
357
358                 public new ITypeDefinition MemberDefinition {
359                         get {
360                                 return (ITypeDefinition) definition;
361                         }
362                 }
363
364                 // TODO: Wouldn't be better to rely on cast to InflatedTypeSpec and
365                 // remove the property, YES IT WOULD !!!
366                 public virtual TypeSpec[] TypeArguments {
367                         get { return TypeSpec.EmptyTypes; }
368                 }
369
370                 #endregion
371
372                 public virtual bool AddInterface (TypeSpec iface)
373                 {
374                         if ((state & StateFlags.InterfacesExpanded) != 0)
375                                 throw new InternalErrorException ("Modifying expanded interface list");
376
377                         if (ifaces == null) {
378                                 ifaces = new List<TypeSpec> () { iface };
379                                 return true;
380                         }
381
382                         if (!ifaces.Contains (iface)) {
383                                 ifaces.Add (iface);
384                                 return true;
385                         }
386
387                         return false;
388                 }
389
390                 //
391                 // Special version used during type definition
392                 //
393                 public bool AddInterfaceDefined (TypeSpec iface)
394                 {
395                         if (!AddInterface (iface))
396                                 return false;
397
398                         //
399                         // We can get into a situation where a type is inflated before
400                         // its interfaces are resoved. Consider this situation
401                         //
402                         // class A<T> : X<A<int>>, IFoo {}
403                         //
404                         // When resolving base class of X`1 we inflate context type A`1
405                         // All this happens before we even hit IFoo resolve. Without
406                         // additional expansion any inside usage of A<T> would miss IFoo
407                         // interface because it comes from early inflated A`1 definition.
408                         //
409                         if (inflated_instances != null) {
410                                 //
411                                 // Inflate only existing instances not any new instances added
412                                 // during AddInterface
413                                 //
414                                 var inflated_existing = inflated_instances.Values.ToArray ();
415                                 foreach (var inflated in inflated_existing) {
416                                         inflated.AddInterface (iface);
417                                 }
418                         }
419
420                         return true;
421                 }
422
423                 //
424                 // Returns all type arguments, usefull for nested types
425                 //
426                 public static TypeSpec[] GetAllTypeArguments (TypeSpec type)
427                 {
428                         IList<TypeSpec> targs = TypeSpec.EmptyTypes;
429
430                         do {
431                                 if (type.Arity > 0) {
432                                         if (targs.Count == 0) {
433                                                 targs = type.TypeArguments;
434                                         } else {
435                                                 var list = targs as List<TypeSpec> ?? new List<TypeSpec> (targs);
436                                                 list.AddRange (type.TypeArguments);
437                                                 targs = list;
438                                         }
439                                 }
440
441                                 type = type.declaringType;
442                         } while (type != null);
443
444                         return targs as TypeSpec[] ?? ((List<TypeSpec>) targs).ToArray ();
445                 }
446
447                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
448                 {
449                         if (Kind != MemberKind.Class)
450                                 throw new InternalErrorException ();
451
452                         if (!pa.IsDefined)
453                                 return Attribute.DefaultUsageAttribute;
454
455                         AttributeUsageAttribute aua = null;
456                         var type = this;
457                         while (type != null) {
458                                 aua = type.MemberDefinition.GetAttributeUsage (pa);
459                                 if (aua != null)
460                                         break;
461
462                                 type = type.BaseType;
463                         }
464
465                         return aua;
466                 }
467
468                 //
469                 // Return metadata information used during emit to describe the type
470                 //
471                 public virtual MetaType GetMetaInfo ()
472                 {
473                         return info;
474                 }
475
476                 public virtual TypeSpec GetDefinition ()
477                 {
478                         return this;
479                 }
480
481                 //
482                 // Text representation of type used by documentation writer
483                 //
484                 public override string GetSignatureForDocumentation ()
485                 {
486                         StringBuilder sb = new StringBuilder ();
487                         if (IsNested) {
488                                 sb.Append (DeclaringType.GetSignatureForDocumentation ());
489                         } else {
490                                 sb.Append (MemberDefinition.Namespace);
491                         }
492
493                         if (sb.Length != 0)
494                                 sb.Append (".");
495
496                         sb.Append (Name);
497                         if (Arity > 0) {
498                                 if (this is InflatedTypeSpec) {
499                                     sb.Append ("{");
500                                     for (int i = 0; i < Arity; ++i) {
501                                         if (i > 0)
502                                             sb.Append (",");
503
504                                         sb.Append (TypeArguments[i].GetSignatureForDocumentation ());
505                                     }
506                                     sb.Append ("}");
507                                 } else {
508                                         sb.Append ("`");
509                                         sb.Append (Arity.ToString ());
510                                 }
511                         }
512
513                         return sb.ToString ();
514                 }
515
516                 public string GetExplicitNameSignatureForDocumentation ()
517                 {
518                         StringBuilder sb = new StringBuilder ();
519                         if (IsNested) {
520                                 sb.Append (DeclaringType.GetExplicitNameSignatureForDocumentation ());
521                         } else if (MemberDefinition.Namespace != null) {
522                                 sb.Append (MemberDefinition.Namespace.Replace ('.', '#'));
523                         }
524
525                         if (sb.Length != 0)
526                                 sb.Append ("#");
527
528                         sb.Append (Name);
529                         if (Arity > 0) {
530                                 sb.Append ("{");
531                                 for (int i = 0; i < Arity; ++i) {
532                                         if (i > 0)
533                                                 sb.Append (",");
534
535                                         sb.Append (TypeArguments[i].GetExplicitNameSignatureForDocumentation ());
536                                 }
537                                 sb.Append ("}");
538                         }
539
540                         return sb.ToString ();
541                 }
542
543                 public override string GetSignatureForError ()
544                 {
545                         string s;
546
547                         if (IsNested) {
548                                 s = DeclaringType.GetSignatureForError ();
549                         } else if (MemberDefinition is AnonymousTypeClass) {
550                                 return ((AnonymousTypeClass) MemberDefinition).GetSignatureForError ();
551                         } else {
552                                 s = MemberDefinition.Namespace;
553                         }
554
555                         if (!string.IsNullOrEmpty (s))
556                                 s += ".";
557
558                         return s + Name + GetTypeNameSignature ();
559                 }
560
561                 public string GetSignatureForErrorIncludingAssemblyName ()
562                 {
563                         return string.Format ("{0} [{1}]", GetSignatureForError (), MemberDefinition.DeclaringAssembly.FullName);
564                 }
565
566                 protected virtual string GetTypeNameSignature ()
567                 {
568                         if (!IsGeneric)
569                                 return null;
570
571                         return "<" + TypeManager.CSharpName (MemberDefinition.TypeParameters) + ">";
572                 }
573
574                 public bool ImplementsInterface (TypeSpec iface, bool variantly)
575                 {
576                         var ifaces = Interfaces;
577                         if (ifaces != null) {
578                                 for (int i = 0; i < ifaces.Count; ++i) {
579                                         if (TypeSpecComparer.IsEqual (ifaces[i], iface))
580                                                 return true;
581
582                                         if (variantly && TypeSpecComparer.Variant.IsEqual (ifaces[i], iface))
583                                                 return true;
584                                 }
585                         }
586
587                         return false;
588                 }
589
590                 protected virtual void InitializeMemberCache (bool onlyTypes)
591                 {
592                         try {
593                                 MemberDefinition.LoadMembers (this, onlyTypes, ref cache);
594                         } catch (Exception e) {
595                                 throw new InternalErrorException (e, "Unexpected error when loading type `{0}'", GetSignatureForError ());
596                         }
597
598                         if (onlyTypes)
599                                 state |= StateFlags.PendingMemberCacheMembers;
600                         else
601                                 state &= ~StateFlags.PendingMemberCacheMembers;
602                 }
603
604                 //
605                 // Is @baseClass base implementation of @type. With enabled @dynamicIsEqual the slower
606                 // comparison is used to hide differences between `object' and `dynamic' for generic
607                 // types. Should not be used for comparisons where G<object> != G<dynamic>
608                 //
609                 public static bool IsBaseClass (TypeSpec type, TypeSpec baseClass, bool dynamicIsObject)
610                 {
611                         if (dynamicIsObject && baseClass.IsGeneric) {
612                                 //
613                                 // Returns true for a hierarchies like this when passing baseClass of A<dynamic>
614                                 //
615                                 // class B : A<object> {}
616                                 //
617                                 type = type.BaseType;
618                                 while (type != null) {
619                                         if (TypeSpecComparer.IsEqual (type, baseClass))
620                                                 return true;
621
622                                         type = type.BaseType;
623                                 }
624
625                                 return false;
626                         }
627
628                         while (type != null) {
629                                 type = type.BaseType;
630                                 if (type == baseClass)
631                                         return true;
632                         }
633
634                         return false;
635                 }
636
637                 public static bool IsReferenceType (TypeSpec t)
638                 {
639                         switch (t.Kind) {
640                         case MemberKind.TypeParameter:
641                                 return ((TypeParameterSpec) t).IsReferenceType;
642                         case MemberKind.Struct:
643                         case MemberKind.Enum:
644                         case MemberKind.Void:
645                                 return false;
646                         case MemberKind.InternalCompilerType:
647                                 //
648                                 // Null is considered to be a reference type
649                                 //                      
650                                 return t == InternalType.NullLiteral || t.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
651                         default:
652                                 return true;
653                         }
654                 }
655
656                 public static bool IsNonNullableValueType (TypeSpec t)
657                 {
658                         switch (t.Kind) {
659                         case MemberKind.TypeParameter:
660                                 return ((TypeParameterSpec) t).IsValueType;
661                         case MemberKind.Struct:
662                                 return !t.IsNullableType;
663                         case MemberKind.Enum:
664                                 return true;
665                         default:
666                                 return false;
667                         }
668                 }
669
670                 public static bool IsValueType (TypeSpec t)
671                 {
672                         switch (t.Kind) {
673                         case MemberKind.TypeParameter:
674                                 return ((TypeParameterSpec) t).IsValueType;
675                         case MemberKind.Struct:
676                         case MemberKind.Enum:
677                                 return true;
678                         default:
679                                 return false;
680                         }
681                 }
682
683                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
684                 {
685                         var targs = IsGeneric ? MemberDefinition.TypeParameters : TypeSpec.EmptyTypes;
686
687                         //
688                         // When inflating nested type from inside the type instance will be same
689                         // because type parameters are same for all nested types
690                         //
691                         if (DeclaringType == inflator.TypeInstance) {
692                                 return MakeGenericType (inflator.Context, targs);
693                         }
694
695                         return new InflatedTypeSpec (inflator.Context, this, inflator.TypeInstance, targs);
696                 }
697
698                 //
699                 // Inflates current type using specific type arguments
700                 //
701                 public InflatedTypeSpec MakeGenericType (IModuleContext context, TypeSpec[] targs)
702                 {
703                         if (targs.Length == 0 && !IsNested)
704                                 throw new ArgumentException ("Empty type arguments for type " + GetSignatureForError ());
705
706                         InflatedTypeSpec instance;
707
708                         if (inflated_instances == null) {
709                                 inflated_instances = new Dictionary<TypeSpec[], InflatedTypeSpec> (TypeSpecComparer.Default);
710
711                                 if (IsNested) {
712                                         instance = this as InflatedTypeSpec;
713                                         if (instance != null) {
714                                                 //
715                                                 // Nested types could be inflated on already inflated instances
716                                                 // Caching this type ensured we are using same instance for
717                                                 // inside/outside inflation using local type parameters
718                                                 //
719                                                 inflated_instances.Add (TypeArguments, instance);
720                                         }
721                                 }
722                         }
723
724                         if (!inflated_instances.TryGetValue (targs, out instance)) {
725                                 if (GetDefinition () != this && !IsNested)
726                                         throw new InternalErrorException ("`{0}' must be type definition or nested non-inflated type to MakeGenericType",
727                                                 GetSignatureForError ());
728
729                                 instance = new InflatedTypeSpec (context, this, declaringType, targs);
730                                 inflated_instances.Add (targs, instance);
731                         }
732
733                         return instance;
734                 }
735
736                 public virtual TypeSpec Mutate (TypeParameterMutator mutator)
737                 {
738                         return this;
739                 }
740
741                 public override List<TypeSpec> ResolveMissingDependencies ()
742                 {
743                         List<TypeSpec> missing = null;
744
745                         if (Kind == MemberKind.MissingType) {
746                                 missing = new List<TypeSpec> ();
747                                 missing.Add (this);
748                                 return missing;
749                         }
750
751                         foreach (var targ in TypeArguments) {
752                                 if (targ.Kind == MemberKind.MissingType) {
753                                         if (missing == null)
754                                                 missing = new List<TypeSpec> ();
755
756                                         missing.Add (targ);
757                                 }
758                         }
759
760                         if (Interfaces != null) {
761                                 foreach (var iface in Interfaces) {
762                                         if (iface.Kind == MemberKind.MissingType) {
763                                                 if (missing == null)
764                                                         missing = new List<TypeSpec> ();
765
766                                                 missing.Add (iface);
767                                         }
768                                 }
769                         }
770
771                         if (MemberDefinition.TypeParametersCount > 0) {
772                                 foreach (var tp in MemberDefinition.TypeParameters) {
773                                         var tp_missing = tp.GetMissingDependencies ();
774                                         if (tp_missing != null) {
775                                                 if (missing == null)
776                                                         missing = new List<TypeSpec> ();
777
778                                                 missing.AddRange (tp_missing);
779                                         }
780                                 }
781                         }
782
783                         if (missing != null || BaseType == null)
784                                 return missing;
785
786                         return BaseType.ResolveMissingDependencies ();
787                 }
788
789                 public void SetMetaInfo (MetaType info)
790                 {
791                         if (this.info != null)
792                                 throw new InternalErrorException ("MetaInfo reset");
793
794                         this.info = info;
795                 }
796
797                 public void SetExtensionMethodContainer ()
798                 {
799                         modifiers |= Modifiers.METHOD_EXTENSION;
800                 }
801         }
802
803         //
804         // Special version used for types which must exist in corlib or
805         // the compiler cannot work
806         //
807         public sealed class BuiltinTypeSpec : TypeSpec
808         {
809                 public enum Type
810                 {
811                         None = 0,
812
813                         // Ordered carefully for fast compares
814                         FirstPrimitive = 1,
815                         Bool = 1,
816                         Byte = 2,
817                         SByte = 3,
818                         Char = 4,
819                         Short = 5,
820                         UShort = 6,
821                         Int = 7,
822                         UInt = 8,
823                         Long = 9,
824                         ULong = 10,
825                         Float = 11,
826                         Double = 12,
827                         LastPrimitive = 12,
828                         Decimal = 13,
829
830                         IntPtr = 14,
831                         UIntPtr = 15,
832
833                         Object = 16,
834                         Dynamic = 17,
835                         String = 18,
836                         Type = 19,
837
838                         ValueType = 20,
839                         Enum = 21,
840                         Delegate = 22,
841                         MulticastDelegate = 23,
842                         Array = 24,
843
844                         IEnumerator,
845                         IEnumerable,
846                         IDisposable,
847                         Exception,
848                         Attribute,
849                         Other,
850                 }
851
852                 readonly Type type;
853                 readonly string ns;
854                 readonly string name;
855
856                 public BuiltinTypeSpec (MemberKind kind, string ns, string name, Type builtinKind)
857                         : base (kind, null, null, null, Modifiers.PUBLIC)
858                 {
859                         this.type = builtinKind;
860                         this.ns = ns;
861                         this.name = name;
862                 }
863
864                 public BuiltinTypeSpec (string name, Type builtinKind)
865                         : this (MemberKind.InternalCompilerType, "", name, builtinKind)
866                 {
867                         // Make all internal types CLS-compliant, non-obsolete, compact
868                         state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
869                 }
870
871                 #region Properties
872
873                 public override int Arity {
874                         get {
875                                 return 0;
876                         }
877                 }
878
879                 public override BuiltinTypeSpec.Type BuiltinType {
880                         get {
881                                 return type;
882                         }
883                 }
884
885                 public string FullName {
886                         get {
887                                 return ns + '.' + name;
888                         }
889                 }
890
891                 public override string Name {
892                         get {
893                                 return name;
894                         }
895                 }
896
897                 public string Namespace {
898                         get {
899                                 return ns;
900                         }
901                 }
902
903                 #endregion
904
905                 public static bool IsPrimitiveType (TypeSpec type)
906                 {
907                         return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.LastPrimitive;
908                 }
909
910                 public static bool IsPrimitiveTypeOrDecimal (TypeSpec type)
911                 {
912                         return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.Decimal;
913                 }
914
915                 public override string GetSignatureForError ()
916                 {
917                         switch (Name) {
918                         case "Int32": return "int";
919                         case "Int64": return "long";
920                         case "String": return "string";
921                         case "Boolean": return "bool";
922                         case "Void": return "void";
923                         case "Object": return "object";
924                         case "UInt32": return "uint";
925                         case "Int16": return "short";
926                         case "UInt16": return "ushort";
927                         case "UInt64": return "ulong";
928                         case "Single": return "float";
929                         case "Double": return "double";
930                         case "Decimal": return "decimal";
931                         case "Char": return "char";
932                         case "Byte": return "byte";
933                         case "SByte": return "sbyte";
934                         }
935
936                         if (ns.Length == 0)
937                                 return name;
938
939                         return FullName;
940                 }
941
942                 //
943                 // Returns the size of type if known, otherwise, 0
944                 //
945                 public static int GetSize (TypeSpec type)
946                 {
947                         switch (type.BuiltinType) {
948                         case Type.Int:
949                         case Type.UInt:
950                         case Type.Float:
951                                 return 4;
952                         case Type.Long:
953                         case Type.ULong:
954                         case Type.Double:
955                                 return 8;
956                         case Type.Byte:
957                         case Type.SByte:
958                         case Type.Bool:
959                                 return 1;
960                         case Type.Short:
961                         case Type.Char:
962                         case Type.UShort:
963                                 return 2;
964                         case Type.Decimal:
965                                 return 16;
966                         default:
967                                 return 0;
968                         }
969                 }
970
971                 public void SetDefinition (ITypeDefinition td, MetaType type, Modifiers mod)
972                 {
973                         this.definition = td;
974                         this.info = type;
975                         this.modifiers |= (mod & ~Modifiers.AccessibilityMask);
976                 }
977
978                 public void SetDefinition (TypeSpec ts)
979                 {
980                         this.definition = ts.MemberDefinition;
981                         this.info = ts.GetMetaInfo ();
982                         this.BaseType = ts.BaseType;
983                         this.Interfaces = ts.Interfaces;
984                         this.modifiers = ts.Modifiers;
985                 }
986         }
987
988         //
989         // Various type comparers used by compiler
990         //
991         static class TypeSpecComparer
992         {
993                 //
994                 // Does strict reference comparion only
995                 //
996                 public static readonly DefaultImpl Default = new DefaultImpl ();
997
998                 public class DefaultImpl : IEqualityComparer<TypeSpec[]>
999                 {
1000                         #region IEqualityComparer<TypeSpec[]> Members
1001
1002                         bool IEqualityComparer<TypeSpec[]>.Equals (TypeSpec[] x, TypeSpec[] y)
1003                         {
1004                                 if (x == y)
1005                                         return true;
1006
1007                                 if (x.Length != y.Length)
1008                                         return false;
1009
1010                                 for (int i = 0; i < x.Length; ++i)
1011                                         if (x[i] != y[i])
1012                                                 return false;
1013
1014                                 return true;
1015                         }
1016
1017                         int IEqualityComparer<TypeSpec[]>.GetHashCode (TypeSpec[] obj)
1018                         {
1019                                 int hash = 0;
1020                                 for (int i = 0; i < obj.Length; ++i)
1021                                         hash = (hash << 5) - hash + obj[i].GetHashCode ();
1022
1023                                 return hash;
1024                         }
1025
1026                         #endregion
1027                 }
1028
1029                 //
1030                 // When comparing type signature of overrides or overloads
1031                 // this version tolerates different MVARs at same position
1032                 //
1033                 public static class Override
1034                 {
1035                         public static bool IsEqual (TypeSpec a, TypeSpec b)
1036                         {
1037                                 if (a == b)
1038                                         return true;
1039
1040                                 //
1041                                 // Consider the following example:
1042                                 //
1043                                 //     public abstract class A
1044                                 //     {
1045                                 //        public abstract T Foo<T>();
1046                                 //     }
1047                                 //
1048                                 //     public class B : A
1049                                 //     {
1050                                 //        public override U Foo<T>() { return default (U); }
1051                                 //     }
1052                                 //
1053                                 // Here, `T' and `U' are method type parameters from different methods
1054                                 // (A.Foo and B.Foo), so both `==' and Equals() will fail.
1055                                 //
1056                                 // However, since we're determining whether B.Foo() overrides A.Foo(),
1057                                 // we need to do a signature based comparision and consider them equal.
1058                                 //
1059
1060                                 var tp_a = a as TypeParameterSpec;
1061                                 if (tp_a != null) {
1062                                         var tp_b = b as TypeParameterSpec;
1063                                         return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
1064                                 }
1065
1066                                 var ac_a = a as ArrayContainer;
1067                                 if (ac_a != null) {
1068                                         var ac_b = b as ArrayContainer;
1069                                         return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
1070                                 }
1071
1072                                 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1073                                         return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1074
1075                                 if (a.MemberDefinition != b.MemberDefinition)
1076                                         return false;
1077
1078                                 do {
1079                                         for (int i = 0; i < a.TypeArguments.Length; ++i) {
1080                                                 if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
1081                                                         return false;
1082                                         }
1083
1084                                         a = a.DeclaringType;
1085                                         b = b.DeclaringType;
1086                                 } while (a != null);
1087
1088                                 return true;
1089                         }
1090
1091                         public static bool IsEqual (TypeSpec[] a, TypeSpec[] b)
1092                         {
1093                                 if (a == b)
1094                                         return true;
1095
1096                                 if (a.Length != b.Length)
1097                                         return false;
1098
1099                                 for (int i = 0; i < a.Length; ++i) {
1100                                         if (!IsEqual (a[i], b[i]))
1101                                                 return false;
1102                                 }
1103
1104                                 return true;
1105                         }
1106
1107
1108                         //
1109                         // Compares unordered arrays
1110                         //
1111                         public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
1112                         {
1113                                 if (a == b)
1114                                         return true;
1115
1116                                 if (a == null || b == null || a.Length != b.Length)
1117                                         return false;
1118
1119                                 for (int ai = 0; ai < a.Length; ++ai) {
1120                                         bool found = false;
1121                                         for (int bi = 0; bi < b.Length; ++bi) {
1122                                                 if (IsEqual (a[ai], b[bi])) {
1123                                                         found = true;
1124                                                         break;
1125                                                 }
1126                                         }
1127
1128                                         if (!found)
1129                                                 return false;
1130                                 }
1131
1132                                 return true;
1133                         }
1134
1135                         public static bool IsEqual (AParametersCollection a, AParametersCollection b)
1136                         {
1137                                 if (a == b)
1138                                         return true;
1139
1140                                 if (a.Count != b.Count)
1141                                         return false;
1142
1143                                 for (int i = 0; i < a.Count; ++i) {
1144                                         if (!IsEqual (a.Types[i], b.Types[i]))
1145                                                 return false;
1146
1147                                         if ((a.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (b.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask))
1148                                                 return false;
1149                                 }
1150
1151                                 return true;
1152                         }
1153                 }
1154
1155                 //
1156                 // Type variance equality comparison
1157                 //
1158                 public static class Variant
1159                 {
1160                         public static bool IsEqual (TypeSpec type1, TypeSpec type2)
1161                         {
1162                                 if (!type1.IsGeneric || !type2.IsGeneric)
1163                                         return false;
1164
1165                                 var target_type_def = type2.MemberDefinition;
1166                                 if (type1.MemberDefinition != target_type_def)
1167                                         return false;
1168
1169                                 var t1_targs = type1.TypeArguments;
1170                                 var t2_targs = type2.TypeArguments;
1171                                 var targs_definition = target_type_def.TypeParameters;
1172
1173                                 if (!type1.IsInterface && !type1.IsDelegate) {
1174                                         return false;
1175                                 }
1176
1177                                 for (int i = 0; i < targs_definition.Length; ++i) {
1178                                         if (TypeSpecComparer.IsEqual (t1_targs[i], t2_targs[i]))
1179                                                 continue;
1180
1181                                         Variance v = targs_definition[i].Variance;
1182                                         if (v == Variance.None) {
1183                                                 return false;
1184                                         }
1185
1186                                         if (v == Variance.Covariant) {
1187                                                 if (!Convert.ImplicitReferenceConversionExists (t1_targs[i], t2_targs[i]))
1188                                                         return false;
1189                                         } else if (!Convert.ImplicitReferenceConversionExists (t2_targs[i], t1_targs[i])) {
1190                                                 return false;
1191                                         }
1192                                 }
1193
1194                                 return true;
1195                         }
1196                 }
1197
1198                 //
1199                 // Checks whether two generic instances may become equal for some
1200                 // particular instantiation (26.3.1).
1201                 //
1202                 public static class Unify
1203                 {
1204                         //
1205                         // Either @a or @b must be generic type
1206                         //
1207                         public static bool IsEqual (TypeSpec a, TypeSpec b)
1208                         {
1209                                 if (a.MemberDefinition != b.MemberDefinition) {
1210                                         var base_ifaces = a.Interfaces;
1211                                         if (base_ifaces != null) {
1212                                                 foreach (var base_iface in base_ifaces) {
1213                                                         if (base_iface.Arity > 0 && IsEqual (base_iface, b))
1214                                                                 return true;
1215                                                 }
1216                                         }
1217
1218                                         return false;
1219                                 }
1220
1221                                 var ta = a.TypeArguments;
1222                                 var tb = b.TypeArguments;
1223                                 for (int i = 0; i < ta.Length; i++) {
1224                                         if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
1225                                                 return false;
1226                                 }
1227
1228                                 return true;
1229                         }
1230
1231                         static bool ContainsTypeParameter (TypeSpec tparam, TypeSpec type)
1232                         {
1233                                 TypeSpec[] targs = type.TypeArguments;
1234                                 for (int i = 0; i < targs.Length; i++) {
1235                                         if (tparam == targs[i])
1236                                                 return true;
1237
1238                                         if (ContainsTypeParameter (tparam, targs[i]))
1239                                                 return true;
1240                                 }
1241
1242                                 return false;
1243                         }
1244
1245                         /// <summary>
1246                         ///   Check whether `a' and `b' may become equal generic types.
1247                         ///   The algorithm to do that is a little bit complicated.
1248                         /// </summary>
1249                         static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
1250                         {
1251                                 if (a.IsGenericParameter) {
1252                                         //
1253                                         // If a is an array of a's type, they may never
1254                                         // become equal.
1255                                         //
1256                                         if (b.IsArray)
1257                                                 return false;
1258
1259                                         //
1260                                         // If b is a generic parameter or an actual type,
1261                                         // they may become equal:
1262                                         //
1263                                         //    class X<T,U> : I<T>, I<U>
1264                                         //    class X<T> : I<T>, I<float>
1265                                         // 
1266                                         if (b.IsGenericParameter)
1267                                                 return a != b && a.DeclaringType == b.DeclaringType;
1268
1269                                         //
1270                                         // We're now comparing a type parameter with a
1271                                         // generic instance.  They may become equal unless
1272                                         // the type parameter appears anywhere in the
1273                                         // generic instance:
1274                                         //
1275                                         //    class X<T,U> : I<T>, I<X<U>>
1276                                         //        -> error because you could instanciate it as
1277                                         //           X<X<int>,int>
1278                                         //
1279                                         //    class X<T> : I<T>, I<X<T>> -> ok
1280                                         //
1281
1282                                         return !ContainsTypeParameter (a, b);
1283                                 }
1284
1285                                 if (b.IsGenericParameter)
1286                                         return MayBecomeEqualGenericTypes (b, a);
1287
1288                                 //
1289                                 // At this point, neither a nor b are a type parameter.
1290                                 //
1291                                 // If one of them is a generic instance, compare them (if the
1292                                 // other one is not a generic instance, they can never
1293                                 // become equal).
1294                                 //
1295                                 if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
1296                                         return IsEqual (a, b);
1297
1298                                 //
1299                                 // If both of them are arrays.
1300                                 //
1301                                 var a_ac = a as ArrayContainer;
1302                                 if (a_ac != null) {
1303                                         var b_ac = b as ArrayContainer;
1304                                         if (b_ac == null || a_ac.Rank != b_ac.Rank)
1305                                                 return false;
1306
1307                                         return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
1308                                 }
1309
1310                                 //
1311                                 // Ok, two ordinary types.
1312                                 //
1313                                 return false;
1314                         }
1315                 }
1316
1317                 public static bool Equals (TypeSpec[] x, TypeSpec[] y)
1318                 {
1319                         if (x == y)
1320                                 return true;
1321
1322                         if (x.Length != y.Length)
1323                                 return false;
1324
1325                         for (int i = 0; i < x.Length; ++i)
1326                                 if (!IsEqual (x[i], y[i]))
1327                                         return false;
1328
1329                         return true;
1330                 }
1331
1332                 //
1333                 // Identity type conversion
1334                 //
1335                 // Default reference comparison, it has to be used when comparing
1336                 // two possible dynamic/internal types
1337                 //
1338                 public static bool IsEqual (TypeSpec a, TypeSpec b)
1339                 {
1340                         if (a == b) {
1341                                 // This also rejects dynamic == dynamic
1342                                 return a.Kind != MemberKind.InternalCompilerType || a.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
1343                         }
1344
1345                         if (a == null || b == null)
1346                                 return false;
1347
1348                         if (a.IsArray) {
1349                                 var a_a = (ArrayContainer) a;
1350                                 var b_a = b as ArrayContainer;
1351                                 if (b_a == null)
1352                                         return false;
1353
1354                                 return a_a.Rank == b_a.Rank && IsEqual (a_a.Element, b_a.Element);
1355                         }
1356
1357                         if (!a.IsGeneric || !b.IsGeneric) {
1358                                 //
1359                                 // object and dynamic are considered equivalent there is an identity conversion
1360                                 // between object and dynamic, and between constructed types that are the same
1361                                 // when replacing all occurences of dynamic with object.
1362                                 //
1363                                 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1364                                         return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1365
1366                                 return false;
1367                         }
1368
1369                         if (a.MemberDefinition != b.MemberDefinition)
1370                                 return false;
1371
1372                         do {
1373                                 if (!Equals (a.TypeArguments, b.TypeArguments))
1374                                         return false;
1375
1376                                 a = a.DeclaringType;
1377                                 b = b.DeclaringType;
1378                         } while (a != null);
1379
1380                         return true;
1381                 }
1382         }
1383
1384         public interface ITypeDefinition : IMemberDefinition
1385         {
1386                 IAssemblyDefinition DeclaringAssembly { get; }
1387                 string Namespace { get; }
1388                 bool IsPartial { get; }
1389                 bool IsComImport { get; }
1390                 bool IsTypeForwarder { get; }
1391                 int TypeParametersCount { get; }
1392                 TypeParameterSpec[] TypeParameters { get; }
1393
1394                 TypeSpec GetAttributeCoClass ();
1395                 string GetAttributeDefaultMember ();
1396                 AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
1397                 bool IsInternalAsPublic (IAssemblyDefinition assembly);
1398                 void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache);
1399         }
1400
1401         class InternalType : TypeSpec, ITypeDefinition
1402         {
1403                 public static readonly InternalType AnonymousMethod = new InternalType ("anonymous method");
1404                 public static readonly InternalType Arglist = new InternalType ("__arglist");
1405                 public static readonly InternalType MethodGroup = new InternalType ("method group");
1406                 public static readonly InternalType NullLiteral = new InternalType ("null");
1407                 public static readonly InternalType FakeInternalType = new InternalType ("<fake$type>");
1408                 public static readonly InternalType Namespace = new InternalType ("<namespace>");
1409                 public static readonly InternalType ErrorType = new InternalType ("<error>");
1410
1411                 readonly string name;
1412
1413                 InternalType (string name)
1414                         : base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
1415                 {
1416                         this.name = name;
1417                         this.definition = this;
1418                         cache = MemberCache.Empty;
1419
1420                         // Make all internal types CLS-compliant, non-obsolete
1421                         state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
1422                 }
1423
1424                 #region Properties
1425
1426                 public override int Arity {
1427                         get {
1428                                 return 0;
1429                         }
1430                 }
1431
1432                 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1433                         get {
1434                                 throw new NotImplementedException ();
1435                         }
1436                 }
1437
1438                 bool ITypeDefinition.IsComImport {
1439                         get {
1440                                 return false;
1441                         }
1442                 }
1443
1444                 bool IMemberDefinition.IsImported {
1445                         get {
1446                                 return false;
1447                         }
1448                 }
1449
1450                 bool ITypeDefinition.IsPartial {
1451                         get {
1452                                 return false;
1453                         }
1454                 }
1455
1456                 bool ITypeDefinition.IsTypeForwarder {
1457                         get {
1458                                 return false;
1459                         }
1460                 }
1461
1462                 public override string Name {
1463                         get {
1464                                 return name;
1465                         }
1466                 }
1467
1468                 string ITypeDefinition.Namespace {
1469                         get {
1470                                 return null;
1471                         }
1472                 }
1473
1474                 int ITypeDefinition.TypeParametersCount {
1475                         get {
1476                                 return 0;
1477                         }
1478                 }
1479
1480                 TypeParameterSpec[] ITypeDefinition.TypeParameters {
1481                         get {
1482                                 return null;
1483                         }
1484                 }
1485
1486                 #endregion
1487
1488                 public override string GetSignatureForError ()
1489                 {
1490                         return name;
1491                 }
1492
1493                 #region ITypeDefinition Members
1494
1495                 TypeSpec ITypeDefinition.GetAttributeCoClass ()
1496                 {
1497                         return null;
1498                 }
1499
1500                 string ITypeDefinition.GetAttributeDefaultMember ()
1501                 {
1502                         return null;
1503                 }
1504
1505                 AttributeUsageAttribute ITypeDefinition.GetAttributeUsage (PredefinedAttribute pa)
1506                 {
1507                         return null;
1508                 }
1509
1510                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1511                 {
1512                         throw new NotImplementedException ();
1513                 }
1514
1515                 void ITypeDefinition.LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1516                 {
1517                         throw new NotImplementedException ();
1518                 }
1519
1520                 string[] IMemberDefinition.ConditionalConditions ()
1521                 {
1522                         return null;
1523                 }
1524
1525                 ObsoleteAttribute IMemberDefinition.GetAttributeObsolete ()
1526                 {
1527                         return null;
1528                 }
1529
1530                 bool? IMemberDefinition.CLSAttributeValue {
1531                         get {
1532                                 return null;
1533                         }
1534                 }
1535
1536                 void IMemberDefinition.SetIsAssigned ()
1537                 {
1538                 }
1539
1540                 void IMemberDefinition.SetIsUsed ()
1541                 {
1542                 }
1543
1544                 #endregion
1545         }
1546
1547         //
1548         // Common base class for composite types
1549         //
1550         public abstract class ElementTypeSpec : TypeSpec, ITypeDefinition
1551         {
1552                 protected ElementTypeSpec (MemberKind kind, TypeSpec element, MetaType info)
1553                         : base (kind, element.DeclaringType, null, info, element.Modifiers)
1554                 {
1555                         this.Element = element;
1556
1557                         state &= ~SharedStateFlags;
1558                         state |= (element.state & SharedStateFlags);
1559
1560                         if (element.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1561                                 state |= StateFlags.HasDynamicElement;
1562
1563                         // Has to use its own type definition instead of just element definition to
1564                         // correctly identify itself for cases like x.MemberDefininition == predefined.MemberDefinition
1565                         this.definition = this;
1566
1567                         cache = MemberCache.Empty;
1568                 }
1569
1570                 #region Properties
1571
1572                 public TypeSpec Element { get; private set; }
1573
1574                 bool ITypeDefinition.IsComImport {
1575                         get {
1576                                 return false;
1577                         }
1578                 }
1579
1580                 bool ITypeDefinition.IsPartial {
1581                         get {
1582                                 return false;
1583                         }
1584                 }
1585
1586                 bool ITypeDefinition.IsTypeForwarder {
1587                         get {
1588                                 return false;
1589                         }
1590                 }
1591
1592                 public override string Name {
1593                         get {
1594                                 throw new NotSupportedException ();
1595                         }
1596                 }
1597
1598                 #endregion
1599
1600                 public override ObsoleteAttribute GetAttributeObsolete ()
1601                 {
1602                         return Element.GetAttributeObsolete ();
1603                 }
1604
1605                 protected virtual string GetPostfixSignature ()
1606                 {
1607                         return null;
1608                 }
1609
1610                 public override string GetSignatureForDocumentation ()
1611                 {
1612                         return Element.GetSignatureForDocumentation () + GetPostfixSignature ();
1613                 }
1614
1615                 public override string GetSignatureForError ()
1616                 {
1617                         return Element.GetSignatureForError () + GetPostfixSignature ();
1618                 }
1619
1620                 public override TypeSpec Mutate (TypeParameterMutator mutator)
1621                 {
1622                         var me = Element.Mutate (mutator);
1623                         if (me == Element)
1624                                 return this;
1625
1626                         var mutated = (ElementTypeSpec) MemberwiseClone ();
1627                         mutated.Element = me;
1628                         mutated.info = null;
1629                         return mutated;
1630                 }
1631
1632                 #region ITypeDefinition Members
1633
1634                 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1635                         get {
1636                                 return Element.MemberDefinition.DeclaringAssembly;
1637                         }
1638                 }
1639
1640                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1641                 {
1642                         return Element.MemberDefinition.IsInternalAsPublic (assembly);
1643                 }
1644
1645                 public string Namespace {
1646                         get { throw new NotImplementedException (); }
1647                 }
1648
1649                 public int TypeParametersCount {
1650                         get {
1651                                 return 0;
1652                         }
1653                 }
1654
1655                 public TypeParameterSpec[] TypeParameters {
1656                         get {
1657                                 throw new NotSupportedException ();
1658                         }
1659                 }
1660
1661                 public TypeSpec GetAttributeCoClass ()
1662                 {
1663                         return Element.MemberDefinition.GetAttributeCoClass ();
1664                 }
1665
1666                 public string GetAttributeDefaultMember ()
1667                 {
1668                         return Element.MemberDefinition.GetAttributeDefaultMember ();
1669                 }
1670
1671                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1672                 {
1673                         Element.MemberDefinition.LoadMembers (declaringType, onlyTypes, ref cache);
1674                 }
1675
1676                 public bool IsImported {
1677                         get {
1678                                 return Element.MemberDefinition.IsImported;
1679                         }
1680                 }
1681
1682                 public string[] ConditionalConditions ()
1683                 {
1684                         return Element.MemberDefinition.ConditionalConditions ();
1685                 }
1686
1687                 bool? IMemberDefinition.CLSAttributeValue {
1688                         get {
1689                                 return Element.MemberDefinition.CLSAttributeValue;
1690                         }
1691                 }
1692
1693                 public void SetIsAssigned ()
1694                 {
1695                         Element.MemberDefinition.SetIsAssigned ();
1696                 }
1697
1698                 public void SetIsUsed ()
1699                 {
1700                         Element.MemberDefinition.SetIsUsed ();
1701                 }
1702
1703                 #endregion
1704         }
1705
1706         public class ArrayContainer : ElementTypeSpec
1707         {
1708                 public struct TypeRankPair : IEquatable<TypeRankPair>
1709                 {
1710                         TypeSpec ts;
1711                         int rank;
1712
1713                         public TypeRankPair (TypeSpec ts, int rank)
1714                         {
1715                                 this.ts = ts;
1716                                 this.rank = rank;
1717                         }
1718
1719                         public override int GetHashCode ()
1720                         {
1721                                 return ts.GetHashCode () ^ rank.GetHashCode ();
1722                         }
1723
1724                         #region IEquatable<Tuple<T1,T2>> Members
1725
1726                         public bool Equals (TypeRankPair other)
1727                         {
1728                                 return other.ts == ts && other.rank == rank;
1729                         }
1730
1731                         #endregion
1732                 }
1733
1734                 readonly int rank;
1735                 readonly ModuleContainer module;
1736
1737                 private ArrayContainer (ModuleContainer module, TypeSpec element, int rank)
1738                         : base (MemberKind.ArrayType, element, null)
1739                 {
1740                         this.module = module;
1741                         this.rank = rank;
1742                 }
1743
1744                 public int Rank {
1745                         get {
1746                                 return rank;
1747                         }
1748                 }
1749
1750                 public MethodInfo GetConstructor ()
1751                 {
1752                         var mb = module.Builder;
1753
1754                         var arg_types = new MetaType[rank];
1755                         for (int i = 0; i < rank; i++)
1756                                 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1757
1758                         var ctor = mb.GetArrayMethod (
1759                                 GetMetaInfo (), Constructor.ConstructorName,
1760                                 CallingConventions.HasThis,
1761                                 null, arg_types);
1762
1763                         return ctor;
1764                 }
1765
1766                 public MethodInfo GetAddressMethod ()
1767                 {
1768                         var mb = module.Builder;
1769
1770                         var arg_types = new MetaType[rank];
1771                         for (int i = 0; i < rank; i++)
1772                                 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1773
1774                         var address = mb.GetArrayMethod (
1775                                 GetMetaInfo (), "Address",
1776                                 CallingConventions.HasThis | CallingConventions.Standard,
1777                                 ReferenceContainer.MakeType (module, Element).GetMetaInfo (), arg_types);
1778
1779                         return address;
1780                 }
1781
1782                 public MethodInfo GetGetMethod ()
1783                 {
1784                         var mb = module.Builder;
1785
1786                         var arg_types = new MetaType[rank];
1787                         for (int i = 0; i < rank; i++)
1788                                 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1789
1790                         var get = mb.GetArrayMethod (
1791                                 GetMetaInfo (), "Get",
1792                                 CallingConventions.HasThis | CallingConventions.Standard,
1793                                 Element.GetMetaInfo (), arg_types);
1794
1795                         return get;
1796                 }
1797
1798                 public MethodInfo GetSetMethod ()
1799                 {
1800                         var mb = module.Builder;
1801
1802                         var arg_types = new MetaType[rank + 1];
1803                         for (int i = 0; i < rank; i++)
1804                                 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1805
1806                         arg_types[rank] = Element.GetMetaInfo ();
1807
1808                         var set = mb.GetArrayMethod (
1809                                 GetMetaInfo (), "Set",
1810                                 CallingConventions.HasThis | CallingConventions.Standard,
1811                                 module.Compiler.BuiltinTypes.Void.GetMetaInfo (), arg_types);
1812
1813                         return set;
1814                 }
1815
1816                 public override MetaType GetMetaInfo ()
1817                 {
1818                         if (info == null) {
1819                                 if (rank == 1)
1820                                         info = Element.GetMetaInfo ().MakeArrayType ();
1821                                 else
1822                                         info = Element.GetMetaInfo ().MakeArrayType (rank);
1823                         }
1824
1825                         return info;
1826                 }
1827
1828                 protected override string GetPostfixSignature()
1829                 {
1830                         return GetPostfixSignature (rank);
1831                 }
1832
1833                 public static string GetPostfixSignature (int rank)
1834                 {
1835                         StringBuilder sb = new StringBuilder ();
1836                         sb.Append ("[");
1837                         for (int i = 1; i < rank; i++) {
1838                                 sb.Append (",");
1839                         }
1840                         sb.Append ("]");
1841
1842                         return sb.ToString ();
1843                 }
1844
1845                 public override string GetSignatureForDocumentation ()
1846                 {
1847                         StringBuilder sb = new StringBuilder ();
1848                         GetElementSignatureForDocumentation (sb);
1849                         return sb.ToString ();
1850                 }
1851
1852                 void GetElementSignatureForDocumentation (StringBuilder sb)
1853                 {
1854                         var ac = Element as ArrayContainer;
1855                         if (ac == null)
1856                                 sb.Append (Element.GetSignatureForDocumentation ());
1857                         else
1858                                 ac.GetElementSignatureForDocumentation (sb);
1859
1860                         sb.Append ("[");
1861                         for (int i = 1; i < rank; i++) {
1862                                 if (i == 1)
1863                                         sb.Append ("0:");
1864
1865                                 sb.Append (",0:");
1866                         }
1867                         sb.Append ("]");
1868                 }
1869
1870                 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element)
1871                 {
1872                         return MakeType (module, element, 1);
1873                 }
1874
1875                 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element, int rank)
1876                 {
1877                         ArrayContainer ac;
1878                         var key = new TypeRankPair (element, rank);
1879                         if (!module.ArrayTypesCache.TryGetValue (key, out ac)) {
1880                                 ac = new ArrayContainer (module, element, rank);
1881                                 ac.BaseType = module.Compiler.BuiltinTypes.Array;
1882                                 ac.Interfaces = ac.BaseType.Interfaces;
1883
1884                                 module.ArrayTypesCache.Add (key, ac);
1885                         }
1886
1887                         return ac;
1888                 }
1889         }
1890
1891         class ReferenceContainer : ElementTypeSpec
1892         {
1893                 private ReferenceContainer (TypeSpec element)
1894                         : base (MemberKind.Class, element, null)        // TODO: Kind.Class is most likely wrong
1895                 {
1896                 }
1897
1898                 public override MetaType GetMetaInfo ()
1899                 {
1900                         if (info == null) {
1901                                 info = Element.GetMetaInfo ().MakeByRefType ();
1902                         }
1903
1904                         return info;
1905                 }
1906
1907                 public static ReferenceContainer MakeType (ModuleContainer module, TypeSpec element)
1908                 {
1909                         ReferenceContainer pc;
1910                         if (!module.ReferenceTypesCache.TryGetValue (element, out pc)) {
1911                                 pc = new ReferenceContainer (element);
1912                                 module.ReferenceTypesCache.Add (element, pc);
1913                         }
1914
1915                         return pc;
1916                 }
1917         }
1918
1919         class PointerContainer : ElementTypeSpec
1920         {
1921                 private PointerContainer (TypeSpec element)
1922                         : base (MemberKind.PointerType, element, null)
1923                 {
1924                         // It's never CLS-Compliant
1925                         state &= ~StateFlags.CLSCompliant_Undetected;
1926                 }
1927
1928                 public override MetaType GetMetaInfo ()
1929                 {
1930                         if (info == null) {
1931                                 info = Element.GetMetaInfo ().MakePointerType ();
1932                         }
1933
1934                         return info;
1935                 }
1936
1937                 protected override string GetPostfixSignature()
1938                 {
1939                         return "*";
1940                 }
1941
1942                 public static PointerContainer MakeType (ModuleContainer module, TypeSpec element)
1943                 {
1944                         PointerContainer pc;
1945                         if (!module.PointerTypesCache.TryGetValue (element, out pc)) {
1946                                 pc = new PointerContainer (element);
1947                                 module.PointerTypesCache.Add (element, pc);
1948                         }
1949
1950                         return pc;
1951                 }
1952         }
1953 }