2 // typespec.cs: Type specification
4 // Authors: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2010 Novell, Inc
9 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 using System.Collections.Generic;
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
21 using MetaType = System.Type;
22 using System.Reflection;
28 // Inflated or non-inflated representation of any type.
30 public class TypeSpec : MemberSpec
32 protected MetaType info;
33 protected MemberCache cache;
34 protected IList<TypeSpec> ifaces;
37 Dictionary<TypeSpec[], InflatedTypeSpec> inflated_instances;
39 public static readonly TypeSpec[] EmptyTypes = new TypeSpec[0];
42 // Reflection Emit hacking
43 static readonly Type TypeBuilder;
44 static readonly Type GenericTypeBuilder;
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");
56 public TypeSpec (MemberKind kind, TypeSpec declaringType, ITypeDefinition definition, MetaType info, Modifiers modifiers)
57 : base (kind, declaringType, definition, modifiers)
59 this.declaringType = declaringType;
62 if (definition != null && definition.TypeParametersCount > 0)
63 state |= StateFlags.IsGeneric;
68 public override int Arity {
70 return MemberDefinition.TypeParametersCount;
74 public virtual TypeSpec BaseType {
83 public virtual BuiltinTypeSpec.Type BuiltinType {
85 return BuiltinTypeSpec.Type.None;
89 public bool HasDynamicElement {
91 return (state & StateFlags.HasDynamicElement) != 0;
96 // Returns a list of all interfaces including
97 // interfaces from base type or base interfaces
99 public virtual IList<TypeSpec> Interfaces {
101 if ((state & StateFlags.InterfacesImported) == 0) {
102 state |= StateFlags.InterfacesImported;
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
109 var imported = MemberDefinition as ImportedTypeDefinition;
110 if (imported != null && Kind != MemberKind.MissingType)
111 imported.DefineInterfaces (this);
122 public bool IsArray {
124 return Kind == MemberKind.ArrayType;
128 public bool IsAttribute {
135 if (type.BuiltinType == BuiltinTypeSpec.Type.Attribute)
141 type = type.base_type;
142 } while (type != null);
148 public bool IsInterface {
150 return Kind == MemberKind.Interface;
154 public bool IsClass {
156 return Kind == MemberKind.Class;
160 public bool IsConstantCompatible {
162 if ((Kind & (MemberKind.Enum | MemberKind.Class | MemberKind.Interface | MemberKind.Delegate | MemberKind.ArrayType)) != 0)
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:
187 public bool IsDelegate {
189 return Kind == MemberKind.Delegate;
194 // Returns true for instances of Expression<T>
196 public virtual bool IsExpressionTreeType {
201 state = value ? state | StateFlags.InflatedExpressionType : state & ~StateFlags.InflatedExpressionType;
207 return Kind == MemberKind.Enum;
212 // Returns true for instances of IList<T>, IEnumerable<T>, ICollection<T>
214 public virtual bool IsArrayGenericInterface {
219 state = value ? state | StateFlags.GenericIterateInterface : state & ~StateFlags.GenericIterateInterface;
224 // Returns true for instances of System.Threading.Tasks.Task<T>
226 public virtual bool IsGenericTask {
231 state = value ? state | StateFlags.GenericTask : state & ~StateFlags.GenericTask;
235 // TODO: Should probably do
236 // IsGenericType -- recursive
237 // HasTypeParameter -- non-recursive
238 public bool IsGenericOrParentIsGeneric {
244 ts = ts.declaringType;
245 } while (ts != null);
251 public bool IsGenericParameter {
253 return Kind == MemberKind.TypeParameter;
258 // Returns true for instances of Nullable<T>
260 public virtual bool IsNullableType {
265 state = value ? state | StateFlags.InflatedNullableType : state & ~StateFlags.InflatedNullableType;
269 public bool IsNested {
270 get { return declaringType != null && Kind != MemberKind.TypeParameter; }
273 public bool IsPointer {
275 return Kind == MemberKind.PointerType;
279 public bool IsSealed {
280 get { return (Modifiers & Modifiers.SEALED) != 0; }
283 public bool IsSpecialRuntimeType {
285 return (state & StateFlags.SpecialRuntimeType) != 0;
288 state = value ? state | StateFlags.SpecialRuntimeType : state & ~StateFlags.SpecialRuntimeType;
292 public bool IsStruct {
294 return Kind == MemberKind.Struct;
298 public bool IsTypeBuilder {
303 var meta = GetMetaInfo().GetType ();
304 return meta == TypeBuilder || meta == GenericTypeBuilder;
310 // Whether a type is unmanaged. This is used by the unsafe code
312 public bool IsUnmanaged {
315 return ((ElementTypeSpec) this).Element.IsUnmanaged;
317 var ds = MemberDefinition as TypeDefinition;
319 return ds.IsUnmanagedType ();
321 if (Kind == MemberKind.Void)
324 if (Kind == MemberKind.TypeParameter)
327 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
330 return IsValueType (this);
335 // A cache of all type members (including nested types)
337 public MemberCache MemberCache {
339 if (cache == null || (state & StateFlags.PendingMemberCacheMembers) != 0)
340 InitializeMemberCache (false);
346 throw new InternalErrorException ("Membercache reset");
352 public MemberCache MemberCacheTypes {
355 InitializeMemberCache (true);
361 public new ITypeDefinition MemberDefinition {
363 return (ITypeDefinition) definition;
367 // TODO: Wouldn't be better to rely on cast to InflatedTypeSpec and
368 // remove the property, YES IT WOULD !!!
369 public virtual TypeSpec[] TypeArguments {
370 get { return TypeSpec.EmptyTypes; }
375 public virtual bool AddInterface (TypeSpec iface)
377 if ((state & StateFlags.InterfacesExpanded) != 0)
378 throw new InternalErrorException ("Modifying expanded interface list");
380 if (ifaces == null) {
381 ifaces = new List<TypeSpec> { iface };
385 if (!ifaces.Contains (iface)) {
394 // Special version used during type definition
396 public bool AddInterfaceDefined (TypeSpec iface)
398 if (!AddInterface (iface))
402 // We can get into a situation where a type is inflated before
403 // its interfaces are resoved. Consider this situation
405 // class A<T> : X<A<int>>, IFoo {}
407 // When resolving base class of X`1 we inflate context type A`1
408 // All this happens before we even hit IFoo resolve. Without
409 // additional expansion any inside usage of A<T> would miss IFoo
410 // interface because it comes from early inflated A`1 definition.
412 if (inflated_instances != null) {
414 // Inflate only existing instances not any new instances added
415 // during AddInterface
417 var inflated_existing = inflated_instances.Values.ToArray ();
418 foreach (var inflated in inflated_existing) {
419 inflated.AddInterface (iface);
427 // Returns all type arguments, usefull for nested types
429 public static TypeSpec[] GetAllTypeArguments (TypeSpec type)
431 IList<TypeSpec> targs = TypeSpec.EmptyTypes;
434 if (type.Arity > 0) {
435 if (targs.Count == 0) {
436 targs = type.TypeArguments;
438 var list = targs as List<TypeSpec> ?? new List<TypeSpec> (targs);
439 list.AddRange (type.TypeArguments);
444 type = type.declaringType;
445 } while (type != null);
447 return targs as TypeSpec[] ?? ((List<TypeSpec>) targs).ToArray ();
450 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
452 if (Kind != MemberKind.Class)
453 throw new InternalErrorException ();
456 return Attribute.DefaultUsageAttribute;
458 AttributeUsageAttribute aua = null;
460 while (type != null) {
461 aua = type.MemberDefinition.GetAttributeUsage (pa);
465 type = type.BaseType;
472 // Return metadata information used during emit to describe the type
474 public virtual MetaType GetMetaInfo ()
479 public virtual TypeSpec GetDefinition ()
485 // Text representation of type used by documentation writer
487 public override string GetSignatureForDocumentation ()
489 StringBuilder sb = new StringBuilder ();
491 sb.Append (DeclaringType.GetSignatureForDocumentation ());
493 sb.Append (MemberDefinition.Namespace);
501 if (this is InflatedTypeSpec) {
503 for (int i = 0; i < Arity; ++i) {
507 sb.Append (TypeArguments[i].GetSignatureForDocumentation ());
512 sb.Append (Arity.ToString ());
516 return sb.ToString ();
519 public string GetExplicitNameSignatureForDocumentation ()
521 StringBuilder sb = new StringBuilder ();
523 sb.Append (DeclaringType.GetExplicitNameSignatureForDocumentation ());
524 } else if (MemberDefinition.Namespace != null) {
525 sb.Append (MemberDefinition.Namespace.Replace ('.', '#'));
534 for (int i = 0; i < Arity; ++i) {
538 sb.Append (TypeArguments[i].GetExplicitNameSignatureForDocumentation ());
543 return sb.ToString ();
546 public override string GetSignatureForError ()
551 s = DeclaringType.GetSignatureForError ();
552 } else if (MemberDefinition is AnonymousTypeClass) {
553 return ((AnonymousTypeClass) MemberDefinition).GetSignatureForError ();
555 s = MemberDefinition.Namespace;
558 if (!string.IsNullOrEmpty (s))
561 return s + Name + GetTypeNameSignature ();
564 public string GetSignatureForErrorIncludingAssemblyName ()
566 return string.Format ("{0} [{1}]", GetSignatureForError (), MemberDefinition.DeclaringAssembly.FullName);
569 protected virtual string GetTypeNameSignature ()
574 return "<" + TypeManager.CSharpName (MemberDefinition.TypeParameters) + ">";
577 public bool ImplementsInterface (TypeSpec iface, bool variantly)
579 var ifaces = Interfaces;
580 if (ifaces != null) {
581 for (int i = 0; i < ifaces.Count; ++i) {
582 if (TypeSpecComparer.IsEqual (ifaces[i], iface))
585 if (variantly && TypeSpecComparer.Variant.IsEqual (ifaces[i], iface))
593 protected virtual void InitializeMemberCache (bool onlyTypes)
596 MemberDefinition.LoadMembers (this, onlyTypes, ref cache);
597 } catch (Exception e) {
598 throw new InternalErrorException (e, "Unexpected error when loading type `{0}'", GetSignatureForError ());
602 state |= StateFlags.PendingMemberCacheMembers;
604 state &= ~StateFlags.PendingMemberCacheMembers;
608 // Is @baseClass base implementation of @type. With enabled @dynamicIsEqual the slower
609 // comparison is used to hide differences between `object' and `dynamic' for generic
610 // types. Should not be used for comparisons where G<object> != G<dynamic>
612 public static bool IsBaseClass (TypeSpec type, TypeSpec baseClass, bool dynamicIsObject)
614 if (dynamicIsObject && baseClass.IsGeneric) {
616 // Returns true for a hierarchies like this when passing baseClass of A<dynamic>
618 // class B : A<object> {}
620 type = type.BaseType;
621 while (type != null) {
622 if (TypeSpecComparer.IsEqual (type, baseClass))
625 type = type.BaseType;
631 while (type != null) {
632 type = type.BaseType;
633 if (type == baseClass)
640 public static bool IsReferenceType (TypeSpec t)
643 case MemberKind.TypeParameter:
644 return ((TypeParameterSpec) t).IsReferenceType;
645 case MemberKind.Struct:
646 case MemberKind.Enum:
647 case MemberKind.Void:
649 case MemberKind.InternalCompilerType:
651 // Null is considered to be a reference type
653 return t == InternalType.NullLiteral || t.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
659 public static bool IsNonNullableValueType (TypeSpec t)
662 case MemberKind.TypeParameter:
663 return ((TypeParameterSpec) t).IsValueType;
664 case MemberKind.Struct:
665 return !t.IsNullableType;
666 case MemberKind.Enum:
673 public static bool IsValueType (TypeSpec t)
676 case MemberKind.TypeParameter:
677 return ((TypeParameterSpec) t).IsValueType;
678 case MemberKind.Struct:
679 case MemberKind.Enum:
686 public override MemberSpec InflateMember (TypeParameterInflator inflator)
688 var targs = IsGeneric ? MemberDefinition.TypeParameters : TypeSpec.EmptyTypes;
691 // When inflating nested type from inside the type instance will be same
692 // because type parameters are same for all nested types
694 if (DeclaringType == inflator.TypeInstance) {
695 return MakeGenericType (inflator.Context, targs);
698 return new InflatedTypeSpec (inflator.Context, this, inflator.TypeInstance, targs);
702 // Inflates current type using specific type arguments
704 public InflatedTypeSpec MakeGenericType (IModuleContext context, TypeSpec[] targs)
706 if (targs.Length == 0 && !IsNested)
707 throw new ArgumentException ("Empty type arguments for type " + GetSignatureForError ());
709 InflatedTypeSpec instance;
711 if (inflated_instances == null) {
712 inflated_instances = new Dictionary<TypeSpec[], InflatedTypeSpec> (TypeSpecComparer.Default);
715 instance = this as InflatedTypeSpec;
716 if (instance != null) {
718 // Nested types could be inflated on already inflated instances
719 // Caching this type ensured we are using same instance for
720 // inside/outside inflation using local type parameters
722 inflated_instances.Add (TypeArguments, instance);
727 if (!inflated_instances.TryGetValue (targs, out instance)) {
728 if (GetDefinition () != this && !IsNested)
729 throw new InternalErrorException ("`{0}' must be type definition or nested non-inflated type to MakeGenericType",
730 GetSignatureForError ());
732 instance = new InflatedTypeSpec (context, this, declaringType, targs);
733 inflated_instances.Add (targs, instance);
739 public virtual TypeSpec Mutate (TypeParameterMutator mutator)
744 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
746 List<MissingTypeSpecReference> missing = null;
748 if (Kind == MemberKind.MissingType) {
749 missing = new List<MissingTypeSpecReference> ();
750 missing.Add (new MissingTypeSpecReference (this, caller));
754 foreach (var targ in TypeArguments) {
755 if (targ.Kind == MemberKind.MissingType) {
757 missing = new List<MissingTypeSpecReference> ();
759 missing.Add (new MissingTypeSpecReference (targ, caller));
763 if (Interfaces != null) {
764 foreach (var iface in Interfaces) {
765 if (iface.Kind == MemberKind.MissingType) {
767 missing = new List<MissingTypeSpecReference> ();
769 missing.Add (new MissingTypeSpecReference (iface, caller));
774 if (MemberDefinition.TypeParametersCount > 0) {
775 foreach (var tp in MemberDefinition.TypeParameters) {
776 var tp_missing = tp.GetMissingDependencies (this);
777 if (tp_missing != null) {
779 missing = new List<MissingTypeSpecReference> ();
781 missing.AddRange (tp_missing);
786 if (missing != null || BaseType == null)
789 return BaseType.ResolveMissingDependencies (this);
792 public void SetMetaInfo (MetaType info)
794 if (this.info != null)
795 throw new InternalErrorException ("MetaInfo reset");
800 public void SetExtensionMethodContainer ()
802 modifiers |= Modifiers.METHOD_EXTENSION;
805 public void UpdateInflatedInstancesBaseType ()
808 // When nested class has a partial part the situation where parent type
809 // is inflated before its base type is defined can occur. In such case
810 // all inflated (should be only 1) instansted need to be updated
812 // partial class A<T> {
813 // partial class B : A<int> { }
816 // partial class A<T> : X {}
818 if (inflated_instances == null)
821 foreach (var inflated in inflated_instances) {
823 // Don't need to inflate possible generic type because for now the method
824 // is always used from within the nested type
826 inflated.Value.BaseType = base_type;
832 // Special version used for types which must exist in corlib or
833 // the compiler cannot work
835 public sealed class BuiltinTypeSpec : TypeSpec
841 // Ordered carefully for fast compares
869 MulticastDelegate = 23,
882 readonly string name;
884 public BuiltinTypeSpec (MemberKind kind, string ns, string name, Type builtinKind)
885 : base (kind, null, null, null, Modifiers.PUBLIC)
887 this.type = builtinKind;
892 public BuiltinTypeSpec (string name, Type builtinKind)
893 : this (MemberKind.InternalCompilerType, "", name, builtinKind)
895 // Make all internal types CLS-compliant, non-obsolete, compact
896 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
901 public override int Arity {
907 public override BuiltinTypeSpec.Type BuiltinType {
913 public string FullName {
915 return ns + '.' + name;
919 public override string Name {
925 public string Namespace {
933 public static bool IsPrimitiveType (TypeSpec type)
935 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.LastPrimitive;
938 public static bool IsPrimitiveTypeOrDecimal (TypeSpec type)
940 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.Decimal;
943 public override string GetSignatureForError ()
946 case "Int32": return "int";
947 case "Int64": return "long";
948 case "String": return "string";
949 case "Boolean": return "bool";
950 case "Void": return "void";
951 case "Object": return "object";
952 case "UInt32": return "uint";
953 case "Int16": return "short";
954 case "UInt16": return "ushort";
955 case "UInt64": return "ulong";
956 case "Single": return "float";
957 case "Double": return "double";
958 case "Decimal": return "decimal";
959 case "Char": return "char";
960 case "Byte": return "byte";
961 case "SByte": return "sbyte";
971 // Returns the size of type if known, otherwise, 0
973 public static int GetSize (TypeSpec type)
975 switch (type.BuiltinType) {
999 public void SetDefinition (ITypeDefinition td, MetaType type, Modifiers mod)
1001 this.definition = td;
1003 this.modifiers |= (mod & ~Modifiers.AccessibilityMask);
1006 public void SetDefinition (TypeSpec ts)
1008 this.definition = ts.MemberDefinition;
1009 this.info = ts.GetMetaInfo ();
1010 this.BaseType = ts.BaseType;
1011 this.Interfaces = ts.Interfaces;
1012 this.modifiers = ts.Modifiers;
1017 // Various type comparers used by compiler
1019 static class TypeSpecComparer
1022 // Does strict reference comparion only
1024 public static readonly DefaultImpl Default = new DefaultImpl ();
1026 public class DefaultImpl : IEqualityComparer<TypeSpec[]>
1028 #region IEqualityComparer<TypeSpec[]> Members
1030 bool IEqualityComparer<TypeSpec[]>.Equals (TypeSpec[] x, TypeSpec[] y)
1035 if (x.Length != y.Length)
1038 for (int i = 0; i < x.Length; ++i)
1045 int IEqualityComparer<TypeSpec[]>.GetHashCode (TypeSpec[] obj)
1048 for (int i = 0; i < obj.Length; ++i)
1049 hash = (hash << 5) - hash + obj[i].GetHashCode ();
1058 // When comparing type signature of overrides or overloads
1059 // this version tolerates different MVARs at same position
1061 public static class Override
1063 public static bool IsEqual (TypeSpec a, TypeSpec b)
1069 // Consider the following example:
1071 // public abstract class A
1073 // public abstract T Foo<T>();
1076 // public class B : A
1078 // public override U Foo<T>() { return default (U); }
1081 // Here, `T' and `U' are method type parameters from different methods
1082 // (A.Foo and B.Foo), so both `==' and Equals() will fail.
1084 // However, since we're determining whether B.Foo() overrides A.Foo(),
1085 // we need to do a signature based comparision and consider them equal.
1088 var tp_a = a as TypeParameterSpec;
1090 var tp_b = b as TypeParameterSpec;
1091 return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
1094 var ac_a = a as ArrayContainer;
1096 var ac_b = b as ArrayContainer;
1097 return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
1100 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1101 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1103 if (a.MemberDefinition != b.MemberDefinition)
1107 for (int i = 0; i < a.TypeArguments.Length; ++i) {
1108 if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
1112 a = a.DeclaringType;
1113 b = b.DeclaringType;
1114 } while (a != null);
1119 public static bool IsEqual (TypeSpec[] a, TypeSpec[] b)
1124 if (a.Length != b.Length)
1127 for (int i = 0; i < a.Length; ++i) {
1128 if (!IsEqual (a[i], b[i]))
1137 // Compares unordered arrays
1139 public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
1144 if (a == null || b == null || a.Length != b.Length)
1147 for (int ai = 0; ai < a.Length; ++ai) {
1149 for (int bi = 0; bi < b.Length; ++bi) {
1150 if (IsEqual (a[ai], b[bi])) {
1163 public static bool IsEqual (AParametersCollection a, AParametersCollection b)
1168 if (a.Count != b.Count)
1171 for (int i = 0; i < a.Count; ++i) {
1172 if (!IsEqual (a.Types[i], b.Types[i]))
1175 if ((a.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (b.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask))
1184 // Type variance equality comparison
1186 public static class Variant
1188 public static bool IsEqual (TypeSpec type1, TypeSpec type2)
1190 if (!type1.IsGeneric || !type2.IsGeneric)
1193 var target_type_def = type2.MemberDefinition;
1194 if (type1.MemberDefinition != target_type_def)
1197 var t1_targs = type1.TypeArguments;
1198 var t2_targs = type2.TypeArguments;
1199 var targs_definition = target_type_def.TypeParameters;
1201 if (!type1.IsInterface && !type1.IsDelegate) {
1205 for (int i = 0; i < targs_definition.Length; ++i) {
1206 if (TypeSpecComparer.IsEqual (t1_targs[i], t2_targs[i]))
1209 Variance v = targs_definition[i].Variance;
1210 if (v == Variance.None) {
1214 if (v == Variance.Covariant) {
1215 if (!Convert.ImplicitReferenceConversionExists (t1_targs[i], t2_targs[i]))
1217 } else if (!Convert.ImplicitReferenceConversionExists (t2_targs[i], t1_targs[i])) {
1227 // Checks whether two generic instances may become equal for some
1228 // particular instantiation (26.3.1).
1230 public static class Unify
1233 // Either @a or @b must be generic type
1235 public static bool IsEqual (TypeSpec a, TypeSpec b)
1237 if (a.MemberDefinition != b.MemberDefinition) {
1238 var base_ifaces = a.Interfaces;
1239 if (base_ifaces != null) {
1240 foreach (var base_iface in base_ifaces) {
1241 if (base_iface.Arity > 0 && IsEqual (base_iface, b))
1249 var ta = a.TypeArguments;
1250 var tb = b.TypeArguments;
1251 for (int i = 0; i < ta.Length; i++) {
1252 if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
1259 static bool ContainsTypeParameter (TypeSpec tparam, TypeSpec type)
1261 TypeSpec[] targs = type.TypeArguments;
1262 for (int i = 0; i < targs.Length; i++) {
1263 if (tparam == targs[i])
1266 if (ContainsTypeParameter (tparam, targs[i]))
1274 /// Check whether `a' and `b' may become equal generic types.
1275 /// The algorithm to do that is a little bit complicated.
1277 static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
1279 if (a.IsGenericParameter) {
1281 // If a is an array of a's type, they may never
1288 // If b is a generic parameter or an actual type,
1289 // they may become equal:
1291 // class X<T,U> : I<T>, I<U>
1292 // class X<T> : I<T>, I<float>
1294 if (b.IsGenericParameter)
1295 return a != b && a.DeclaringType == b.DeclaringType;
1298 // We're now comparing a type parameter with a
1299 // generic instance. They may become equal unless
1300 // the type parameter appears anywhere in the
1301 // generic instance:
1303 // class X<T,U> : I<T>, I<X<U>>
1304 // -> error because you could instanciate it as
1307 // class X<T> : I<T>, I<X<T>> -> ok
1310 return !ContainsTypeParameter (a, b);
1313 if (b.IsGenericParameter)
1314 return MayBecomeEqualGenericTypes (b, a);
1317 // At this point, neither a nor b are a type parameter.
1319 // If one of them is a generic instance, compare them (if the
1320 // other one is not a generic instance, they can never
1323 if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
1324 return IsEqual (a, b);
1327 // If both of them are arrays.
1329 var a_ac = a as ArrayContainer;
1331 var b_ac = b as ArrayContainer;
1332 if (b_ac == null || a_ac.Rank != b_ac.Rank)
1335 return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
1339 // Ok, two ordinary types.
1345 public static bool Equals (TypeSpec[] x, TypeSpec[] y)
1350 if (x.Length != y.Length)
1353 for (int i = 0; i < x.Length; ++i)
1354 if (!IsEqual (x[i], y[i]))
1361 // Identity type conversion
1363 // Default reference comparison, it has to be used when comparing
1364 // two possible dynamic/internal types
1366 public static bool IsEqual (TypeSpec a, TypeSpec b)
1369 // This also rejects dynamic == dynamic
1370 return a.Kind != MemberKind.InternalCompilerType || a.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
1373 if (a == null || b == null)
1377 var a_a = (ArrayContainer) a;
1378 var b_a = b as ArrayContainer;
1382 return a_a.Rank == b_a.Rank && IsEqual (a_a.Element, b_a.Element);
1385 if (!a.IsGeneric || !b.IsGeneric) {
1387 // object and dynamic are considered equivalent there is an identity conversion
1388 // between object and dynamic, and between constructed types that are the same
1389 // when replacing all occurences of dynamic with object.
1391 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1392 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1397 if (a.MemberDefinition != b.MemberDefinition)
1401 if (!Equals (a.TypeArguments, b.TypeArguments))
1404 a = a.DeclaringType;
1405 b = b.DeclaringType;
1406 } while (a != null);
1412 public interface ITypeDefinition : IMemberDefinition
1414 IAssemblyDefinition DeclaringAssembly { get; }
1415 string Namespace { get; }
1416 bool IsPartial { get; }
1417 bool IsComImport { get; }
1418 bool IsTypeForwarder { get; }
1419 bool IsCyclicTypeForwarder { get; }
1420 int TypeParametersCount { get; }
1421 TypeParameterSpec[] TypeParameters { get; }
1423 TypeSpec GetAttributeCoClass ();
1424 string GetAttributeDefaultMember ();
1425 AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
1426 bool IsInternalAsPublic (IAssemblyDefinition assembly);
1427 void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache);
1430 class InternalType : TypeSpec, ITypeDefinition
1432 public static readonly InternalType AnonymousMethod = new InternalType ("anonymous method");
1433 public static readonly InternalType Arglist = new InternalType ("__arglist");
1434 public static readonly InternalType MethodGroup = new InternalType ("method group");
1435 public static readonly InternalType NullLiteral = new InternalType ("null");
1436 public static readonly InternalType FakeInternalType = new InternalType ("<fake$type>");
1437 public static readonly InternalType Namespace = new InternalType ("<namespace>");
1438 public static readonly InternalType ErrorType = new InternalType ("<error>");
1440 readonly string name;
1442 InternalType (string name)
1443 : base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
1446 this.definition = this;
1447 cache = MemberCache.Empty;
1449 // Make all internal types CLS-compliant, non-obsolete
1450 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
1455 public override int Arity {
1461 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1463 throw new NotImplementedException ();
1467 bool ITypeDefinition.IsComImport {
1473 bool IMemberDefinition.IsImported {
1479 bool ITypeDefinition.IsPartial {
1485 bool ITypeDefinition.IsTypeForwarder {
1491 bool ITypeDefinition.IsCyclicTypeForwarder {
1497 public override string Name {
1503 string ITypeDefinition.Namespace {
1509 int ITypeDefinition.TypeParametersCount {
1515 TypeParameterSpec[] ITypeDefinition.TypeParameters {
1523 public override string GetSignatureForError ()
1528 #region ITypeDefinition Members
1530 TypeSpec ITypeDefinition.GetAttributeCoClass ()
1535 string ITypeDefinition.GetAttributeDefaultMember ()
1540 AttributeUsageAttribute ITypeDefinition.GetAttributeUsage (PredefinedAttribute pa)
1545 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1547 throw new NotImplementedException ();
1550 void ITypeDefinition.LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1552 throw new NotImplementedException ();
1555 string[] IMemberDefinition.ConditionalConditions ()
1560 ObsoleteAttribute IMemberDefinition.GetAttributeObsolete ()
1565 bool? IMemberDefinition.CLSAttributeValue {
1571 void IMemberDefinition.SetIsAssigned ()
1575 void IMemberDefinition.SetIsUsed ()
1583 // Common base class for composite types
1585 public abstract class ElementTypeSpec : TypeSpec, ITypeDefinition
1587 protected ElementTypeSpec (MemberKind kind, TypeSpec element, MetaType info)
1588 : base (kind, element.DeclaringType, null, info, element.Modifiers)
1590 this.Element = element;
1592 state &= ~SharedStateFlags;
1593 state |= (element.state & SharedStateFlags);
1595 if (element.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1596 state |= StateFlags.HasDynamicElement;
1598 // Has to use its own type definition instead of just element definition to
1599 // correctly identify itself for cases like x.MemberDefininition == predefined.MemberDefinition
1600 this.definition = this;
1602 cache = MemberCache.Empty;
1607 public TypeSpec Element { get; private set; }
1609 bool ITypeDefinition.IsComImport {
1615 bool ITypeDefinition.IsPartial {
1621 bool ITypeDefinition.IsTypeForwarder {
1627 bool ITypeDefinition.IsCyclicTypeForwarder {
1633 public override string Name {
1635 throw new NotSupportedException ();
1641 public override ObsoleteAttribute GetAttributeObsolete ()
1643 return Element.GetAttributeObsolete ();
1646 protected virtual string GetPostfixSignature ()
1651 public override string GetSignatureForDocumentation ()
1653 return Element.GetSignatureForDocumentation () + GetPostfixSignature ();
1656 public override string GetSignatureForError ()
1658 return Element.GetSignatureForError () + GetPostfixSignature ();
1661 public override TypeSpec Mutate (TypeParameterMutator mutator)
1663 var me = Element.Mutate (mutator);
1667 var mutated = (ElementTypeSpec) MemberwiseClone ();
1668 mutated.Element = me;
1669 mutated.info = null;
1673 #region ITypeDefinition Members
1675 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1677 return Element.MemberDefinition.DeclaringAssembly;
1681 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1683 return Element.MemberDefinition.IsInternalAsPublic (assembly);
1686 public string Namespace {
1687 get { throw new NotImplementedException (); }
1690 public int TypeParametersCount {
1696 public TypeParameterSpec[] TypeParameters {
1698 throw new NotSupportedException ();
1702 public TypeSpec GetAttributeCoClass ()
1704 return Element.MemberDefinition.GetAttributeCoClass ();
1707 public string GetAttributeDefaultMember ()
1709 return Element.MemberDefinition.GetAttributeDefaultMember ();
1712 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1714 Element.MemberDefinition.LoadMembers (declaringType, onlyTypes, ref cache);
1717 public bool IsImported {
1719 return Element.MemberDefinition.IsImported;
1723 public string[] ConditionalConditions ()
1725 return Element.MemberDefinition.ConditionalConditions ();
1728 bool? IMemberDefinition.CLSAttributeValue {
1730 return Element.MemberDefinition.CLSAttributeValue;
1734 public void SetIsAssigned ()
1736 Element.MemberDefinition.SetIsAssigned ();
1739 public void SetIsUsed ()
1741 Element.MemberDefinition.SetIsUsed ();
1747 public class ArrayContainer : ElementTypeSpec
1749 public struct TypeRankPair : IEquatable<TypeRankPair>
1754 public TypeRankPair (TypeSpec ts, int rank)
1760 public override int GetHashCode ()
1762 return ts.GetHashCode () ^ rank.GetHashCode ();
1765 #region IEquatable<Tuple<T1,T2>> Members
1767 public bool Equals (TypeRankPair other)
1769 return other.ts == ts && other.rank == rank;
1776 readonly ModuleContainer module;
1778 private ArrayContainer (ModuleContainer module, TypeSpec element, int rank)
1779 : base (MemberKind.ArrayType, element, null)
1781 this.module = module;
1791 public MethodInfo GetConstructor ()
1793 var mb = module.Builder;
1795 var arg_types = new MetaType[rank];
1796 for (int i = 0; i < rank; i++)
1797 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1799 var ctor = mb.GetArrayMethod (
1800 GetMetaInfo (), Constructor.ConstructorName,
1801 CallingConventions.HasThis,
1807 public MethodInfo GetAddressMethod ()
1809 var mb = module.Builder;
1811 var arg_types = new MetaType[rank];
1812 for (int i = 0; i < rank; i++)
1813 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1815 var address = mb.GetArrayMethod (
1816 GetMetaInfo (), "Address",
1817 CallingConventions.HasThis | CallingConventions.Standard,
1818 ReferenceContainer.MakeType (module, Element).GetMetaInfo (), arg_types);
1823 public MethodInfo GetGetMethod ()
1825 var mb = module.Builder;
1827 var arg_types = new MetaType[rank];
1828 for (int i = 0; i < rank; i++)
1829 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1831 var get = mb.GetArrayMethod (
1832 GetMetaInfo (), "Get",
1833 CallingConventions.HasThis | CallingConventions.Standard,
1834 Element.GetMetaInfo (), arg_types);
1839 public MethodInfo GetSetMethod ()
1841 var mb = module.Builder;
1843 var arg_types = new MetaType[rank + 1];
1844 for (int i = 0; i < rank; i++)
1845 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1847 arg_types[rank] = Element.GetMetaInfo ();
1849 var set = mb.GetArrayMethod (
1850 GetMetaInfo (), "Set",
1851 CallingConventions.HasThis | CallingConventions.Standard,
1852 module.Compiler.BuiltinTypes.Void.GetMetaInfo (), arg_types);
1857 public override MetaType GetMetaInfo ()
1861 info = Element.GetMetaInfo ().MakeArrayType ();
1863 info = Element.GetMetaInfo ().MakeArrayType (rank);
1869 protected override string GetPostfixSignature()
1871 return GetPostfixSignature (rank);
1874 public static string GetPostfixSignature (int rank)
1876 StringBuilder sb = new StringBuilder ();
1878 for (int i = 1; i < rank; i++) {
1883 return sb.ToString ();
1886 public override string GetSignatureForDocumentation ()
1888 StringBuilder sb = new StringBuilder ();
1889 GetElementSignatureForDocumentation (sb);
1890 return sb.ToString ();
1893 void GetElementSignatureForDocumentation (StringBuilder sb)
1895 var ac = Element as ArrayContainer;
1897 sb.Append (Element.GetSignatureForDocumentation ());
1899 ac.GetElementSignatureForDocumentation (sb);
1902 for (int i = 1; i < rank; i++) {
1911 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element)
1913 return MakeType (module, element, 1);
1916 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element, int rank)
1919 var key = new TypeRankPair (element, rank);
1920 if (!module.ArrayTypesCache.TryGetValue (key, out ac)) {
1921 ac = new ArrayContainer (module, element, rank);
1922 ac.BaseType = module.Compiler.BuiltinTypes.Array;
1923 ac.Interfaces = ac.BaseType.Interfaces;
1925 module.ArrayTypesCache.Add (key, ac);
1932 class ReferenceContainer : ElementTypeSpec
1934 private ReferenceContainer (TypeSpec element)
1935 : base (MemberKind.Class, element, null) // TODO: Kind.Class is most likely wrong
1939 public override MetaType GetMetaInfo ()
1942 info = Element.GetMetaInfo ().MakeByRefType ();
1948 public static ReferenceContainer MakeType (ModuleContainer module, TypeSpec element)
1950 ReferenceContainer pc;
1951 if (!module.ReferenceTypesCache.TryGetValue (element, out pc)) {
1952 pc = new ReferenceContainer (element);
1953 module.ReferenceTypesCache.Add (element, pc);
1960 class PointerContainer : ElementTypeSpec
1962 private PointerContainer (TypeSpec element)
1963 : base (MemberKind.PointerType, element, null)
1965 // It's never CLS-Compliant
1966 state &= ~StateFlags.CLSCompliant_Undetected;
1969 public override MetaType GetMetaInfo ()
1972 info = Element.GetMetaInfo ().MakePointerType ();
1978 protected override string GetPostfixSignature()
1983 public static PointerContainer MakeType (ModuleContainer module, TypeSpec element)
1985 PointerContainer pc;
1986 if (!module.PointerTypesCache.TryGetValue (element, out pc)) {
1987 pc = new PointerContainer (element);
1988 module.PointerTypesCache.Add (element, pc);
1995 public class MissingTypeSpecReference
1997 public MissingTypeSpecReference (TypeSpec type, MemberSpec caller)
2003 public TypeSpec Type { get; private set; }
2004 public MemberSpec Caller { get; private set; }