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