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 IsGenericIterateInterface {
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 (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
327 return IsValueType (this);
332 // A cache of all type members (including nested types)
334 public MemberCache MemberCache {
336 if (cache == null || (state & StateFlags.PendingMemberCacheMembers) != 0)
337 InitializeMemberCache (false);
343 throw new InternalErrorException ("Membercache reset");
349 public MemberCache MemberCacheTypes {
352 InitializeMemberCache (true);
358 public new ITypeDefinition MemberDefinition {
360 return (ITypeDefinition) definition;
364 // TODO: Wouldn't be better to rely on cast to InflatedTypeSpec and
365 // remove the property, YES IT WOULD !!!
366 public virtual TypeSpec[] TypeArguments {
367 get { return TypeSpec.EmptyTypes; }
372 public virtual bool AddInterface (TypeSpec iface)
374 if ((state & StateFlags.InterfacesExpanded) != 0)
375 throw new InternalErrorException ("Modifying expanded interface list");
377 if (ifaces == null) {
378 ifaces = new List<TypeSpec> () { iface };
382 if (!ifaces.Contains (iface)) {
391 // Special version used during type definition
393 public bool AddInterfaceDefined (TypeSpec iface)
395 if (!AddInterface (iface))
399 // We can get into a situation where a type is inflated before
400 // its interfaces are resoved. Consider this situation
402 // class A<T> : X<A<int>>, IFoo {}
404 // When resolving base class of X`1 we inflate context type A`1
405 // All this happens before we even hit IFoo resolve. Without
406 // additional expansion any inside usage of A<T> would miss IFoo
407 // interface because it comes from early inflated A`1 definition.
409 if (inflated_instances != null) {
411 // Inflate only existing instances not any new instances added
412 // during AddInterface
414 var inflated_existing = inflated_instances.Values.ToArray ();
415 foreach (var inflated in inflated_existing) {
416 inflated.AddInterface (iface);
424 // Returns all type arguments, usefull for nested types
426 public static TypeSpec[] GetAllTypeArguments (TypeSpec type)
428 IList<TypeSpec> targs = TypeSpec.EmptyTypes;
431 if (type.Arity > 0) {
432 if (targs.Count == 0) {
433 targs = type.TypeArguments;
435 var list = targs as List<TypeSpec> ?? new List<TypeSpec> (targs);
436 list.AddRange (type.TypeArguments);
441 type = type.declaringType;
442 } while (type != null);
444 return targs as TypeSpec[] ?? ((List<TypeSpec>) targs).ToArray ();
447 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
449 if (Kind != MemberKind.Class)
450 throw new InternalErrorException ();
453 return Attribute.DefaultUsageAttribute;
455 AttributeUsageAttribute aua = null;
457 while (type != null) {
458 aua = type.MemberDefinition.GetAttributeUsage (pa);
462 type = type.BaseType;
469 // Return metadata information used during emit to describe the type
471 public virtual MetaType GetMetaInfo ()
476 public virtual TypeSpec GetDefinition ()
482 // Text representation of type used by documentation writer
484 public override string GetSignatureForDocumentation ()
486 StringBuilder sb = new StringBuilder ();
488 sb.Append (DeclaringType.GetSignatureForDocumentation ());
490 sb.Append (MemberDefinition.Namespace);
498 if (this is InflatedTypeSpec) {
500 for (int i = 0; i < Arity; ++i) {
504 sb.Append (TypeArguments[i].GetSignatureForDocumentation ());
509 sb.Append (Arity.ToString ());
513 return sb.ToString ();
516 public string GetExplicitNameSignatureForDocumentation ()
518 StringBuilder sb = new StringBuilder ();
520 sb.Append (DeclaringType.GetExplicitNameSignatureForDocumentation ());
521 } else if (MemberDefinition.Namespace != null) {
522 sb.Append (MemberDefinition.Namespace.Replace ('.', '#'));
531 for (int i = 0; i < Arity; ++i) {
535 sb.Append (TypeArguments[i].GetExplicitNameSignatureForDocumentation ());
540 return sb.ToString ();
543 public override string GetSignatureForError ()
548 s = DeclaringType.GetSignatureForError ();
549 } else if (MemberDefinition is AnonymousTypeClass) {
550 return ((AnonymousTypeClass) MemberDefinition).GetSignatureForError ();
552 s = MemberDefinition.Namespace;
555 if (!string.IsNullOrEmpty (s))
558 return s + Name + GetTypeNameSignature ();
561 public string GetSignatureForErrorIncludingAssemblyName ()
563 return string.Format ("{0} [{1}]", GetSignatureForError (), MemberDefinition.DeclaringAssembly.FullName);
566 protected virtual string GetTypeNameSignature ()
571 return "<" + TypeManager.CSharpName (MemberDefinition.TypeParameters) + ">";
574 public bool ImplementsInterface (TypeSpec iface, bool variantly)
576 var ifaces = Interfaces;
577 if (ifaces != null) {
578 for (int i = 0; i < ifaces.Count; ++i) {
579 if (TypeSpecComparer.IsEqual (ifaces[i], iface))
582 if (variantly && TypeSpecComparer.Variant.IsEqual (ifaces[i], iface))
590 protected virtual void InitializeMemberCache (bool onlyTypes)
593 MemberDefinition.LoadMembers (this, onlyTypes, ref cache);
594 } catch (Exception e) {
595 throw new InternalErrorException (e, "Unexpected error when loading type `{0}'", GetSignatureForError ());
599 state |= StateFlags.PendingMemberCacheMembers;
601 state &= ~StateFlags.PendingMemberCacheMembers;
605 // Is @baseClass base implementation of @type. With enabled @dynamicIsEqual the slower
606 // comparison is used to hide differences between `object' and `dynamic' for generic
607 // types. Should not be used for comparisons where G<object> != G<dynamic>
609 public static bool IsBaseClass (TypeSpec type, TypeSpec baseClass, bool dynamicIsObject)
611 if (dynamicIsObject && baseClass.IsGeneric) {
613 // Returns true for a hierarchies like this when passing baseClass of A<dynamic>
615 // class B : A<object> {}
617 type = type.BaseType;
618 while (type != null) {
619 if (TypeSpecComparer.IsEqual (type, baseClass))
622 type = type.BaseType;
628 while (type != null) {
629 type = type.BaseType;
630 if (type == baseClass)
637 public static bool IsReferenceType (TypeSpec t)
640 case MemberKind.TypeParameter:
641 return ((TypeParameterSpec) t).IsReferenceType;
642 case MemberKind.Struct:
643 case MemberKind.Enum:
644 case MemberKind.Void:
646 case MemberKind.InternalCompilerType:
648 // Null is considered to be a reference type
650 return t == InternalType.NullLiteral || t.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
656 public static bool IsNonNullableValueType (TypeSpec t)
659 case MemberKind.TypeParameter:
660 return ((TypeParameterSpec) t).IsValueType;
661 case MemberKind.Struct:
662 return !t.IsNullableType;
663 case MemberKind.Enum:
670 public static bool IsValueType (TypeSpec t)
673 case MemberKind.TypeParameter:
674 return ((TypeParameterSpec) t).IsValueType;
675 case MemberKind.Struct:
676 case MemberKind.Enum:
683 public override MemberSpec InflateMember (TypeParameterInflator inflator)
685 var targs = IsGeneric ? MemberDefinition.TypeParameters : TypeSpec.EmptyTypes;
688 // When inflating nested type from inside the type instance will be same
689 // because type parameters are same for all nested types
691 if (DeclaringType == inflator.TypeInstance) {
692 return MakeGenericType (inflator.Context, targs);
695 return new InflatedTypeSpec (inflator.Context, this, inflator.TypeInstance, targs);
699 // Inflates current type using specific type arguments
701 public InflatedTypeSpec MakeGenericType (IModuleContext context, TypeSpec[] targs)
703 if (targs.Length == 0 && !IsNested)
704 throw new ArgumentException ("Empty type arguments for type " + GetSignatureForError ());
706 InflatedTypeSpec instance;
708 if (inflated_instances == null) {
709 inflated_instances = new Dictionary<TypeSpec[], InflatedTypeSpec> (TypeSpecComparer.Default);
712 instance = this as InflatedTypeSpec;
713 if (instance != null) {
715 // Nested types could be inflated on already inflated instances
716 // Caching this type ensured we are using same instance for
717 // inside/outside inflation using local type parameters
719 inflated_instances.Add (TypeArguments, instance);
724 if (!inflated_instances.TryGetValue (targs, out instance)) {
725 if (GetDefinition () != this && !IsNested)
726 throw new InternalErrorException ("`{0}' must be type definition or nested non-inflated type to MakeGenericType",
727 GetSignatureForError ());
729 instance = new InflatedTypeSpec (context, this, declaringType, targs);
730 inflated_instances.Add (targs, instance);
736 public virtual TypeSpec Mutate (TypeParameterMutator mutator)
741 public override List<TypeSpec> ResolveMissingDependencies ()
743 List<TypeSpec> missing = null;
745 if (Kind == MemberKind.MissingType) {
746 missing = new List<TypeSpec> ();
751 foreach (var targ in TypeArguments) {
752 if (targ.Kind == MemberKind.MissingType) {
754 missing = new List<TypeSpec> ();
760 if (Interfaces != null) {
761 foreach (var iface in Interfaces) {
762 if (iface.Kind == MemberKind.MissingType) {
764 missing = new List<TypeSpec> ();
771 if (MemberDefinition.TypeParametersCount > 0) {
772 foreach (var tp in MemberDefinition.TypeParameters) {
773 var tp_missing = tp.GetMissingDependencies ();
774 if (tp_missing != null) {
776 missing = new List<TypeSpec> ();
778 missing.AddRange (tp_missing);
783 if (missing != null || BaseType == null)
786 return BaseType.ResolveMissingDependencies ();
789 public void SetMetaInfo (MetaType info)
791 if (this.info != null)
792 throw new InternalErrorException ("MetaInfo reset");
797 public void SetExtensionMethodContainer ()
799 modifiers |= Modifiers.METHOD_EXTENSION;
804 // Special version used for types which must exist in corlib or
805 // the compiler cannot work
807 public sealed class BuiltinTypeSpec : TypeSpec
813 // Ordered carefully for fast compares
841 MulticastDelegate = 23,
854 readonly string name;
856 public BuiltinTypeSpec (MemberKind kind, string ns, string name, Type builtinKind)
857 : base (kind, null, null, null, Modifiers.PUBLIC)
859 this.type = builtinKind;
864 public BuiltinTypeSpec (string name, Type builtinKind)
865 : this (MemberKind.InternalCompilerType, "", name, builtinKind)
867 // Make all internal types CLS-compliant, non-obsolete, compact
868 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
873 public override int Arity {
879 public override BuiltinTypeSpec.Type BuiltinType {
885 public string FullName {
887 return ns + '.' + name;
891 public override string Name {
897 public string Namespace {
905 public static bool IsPrimitiveType (TypeSpec type)
907 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.LastPrimitive;
910 public static bool IsPrimitiveTypeOrDecimal (TypeSpec type)
912 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.Decimal;
915 public override string GetSignatureForError ()
918 case "Int32": return "int";
919 case "Int64": return "long";
920 case "String": return "string";
921 case "Boolean": return "bool";
922 case "Void": return "void";
923 case "Object": return "object";
924 case "UInt32": return "uint";
925 case "Int16": return "short";
926 case "UInt16": return "ushort";
927 case "UInt64": return "ulong";
928 case "Single": return "float";
929 case "Double": return "double";
930 case "Decimal": return "decimal";
931 case "Char": return "char";
932 case "Byte": return "byte";
933 case "SByte": return "sbyte";
943 // Returns the size of type if known, otherwise, 0
945 public static int GetSize (TypeSpec type)
947 switch (type.BuiltinType) {
971 public void SetDefinition (ITypeDefinition td, MetaType type, Modifiers mod)
973 this.definition = td;
975 this.modifiers |= (mod & ~Modifiers.AccessibilityMask);
978 public void SetDefinition (TypeSpec ts)
980 this.definition = ts.MemberDefinition;
981 this.info = ts.GetMetaInfo ();
982 this.BaseType = ts.BaseType;
983 this.Interfaces = ts.Interfaces;
984 this.modifiers = ts.Modifiers;
989 // Various type comparers used by compiler
991 static class TypeSpecComparer
994 // Does strict reference comparion only
996 public static readonly DefaultImpl Default = new DefaultImpl ();
998 public class DefaultImpl : IEqualityComparer<TypeSpec[]>
1000 #region IEqualityComparer<TypeSpec[]> Members
1002 bool IEqualityComparer<TypeSpec[]>.Equals (TypeSpec[] x, TypeSpec[] y)
1007 if (x.Length != y.Length)
1010 for (int i = 0; i < x.Length; ++i)
1017 int IEqualityComparer<TypeSpec[]>.GetHashCode (TypeSpec[] obj)
1020 for (int i = 0; i < obj.Length; ++i)
1021 hash = (hash << 5) - hash + obj[i].GetHashCode ();
1030 // When comparing type signature of overrides or overloads
1031 // this version tolerates different MVARs at same position
1033 public static class Override
1035 public static bool IsEqual (TypeSpec a, TypeSpec b)
1041 // Consider the following example:
1043 // public abstract class A
1045 // public abstract T Foo<T>();
1048 // public class B : A
1050 // public override U Foo<T>() { return default (U); }
1053 // Here, `T' and `U' are method type parameters from different methods
1054 // (A.Foo and B.Foo), so both `==' and Equals() will fail.
1056 // However, since we're determining whether B.Foo() overrides A.Foo(),
1057 // we need to do a signature based comparision and consider them equal.
1060 var tp_a = a as TypeParameterSpec;
1062 var tp_b = b as TypeParameterSpec;
1063 return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
1066 var ac_a = a as ArrayContainer;
1068 var ac_b = b as ArrayContainer;
1069 return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
1072 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1073 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1075 if (a.MemberDefinition != b.MemberDefinition)
1079 for (int i = 0; i < a.TypeArguments.Length; ++i) {
1080 if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
1084 a = a.DeclaringType;
1085 b = b.DeclaringType;
1086 } while (a != null);
1091 public static bool IsEqual (TypeSpec[] a, TypeSpec[] b)
1096 if (a.Length != b.Length)
1099 for (int i = 0; i < a.Length; ++i) {
1100 if (!IsEqual (a[i], b[i]))
1109 // Compares unordered arrays
1111 public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
1116 if (a == null || b == null || a.Length != b.Length)
1119 for (int ai = 0; ai < a.Length; ++ai) {
1121 for (int bi = 0; bi < b.Length; ++bi) {
1122 if (IsEqual (a[ai], b[bi])) {
1135 public static bool IsEqual (AParametersCollection a, AParametersCollection b)
1140 if (a.Count != b.Count)
1143 for (int i = 0; i < a.Count; ++i) {
1144 if (!IsEqual (a.Types[i], b.Types[i]))
1147 if ((a.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (b.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask))
1156 // Type variance equality comparison
1158 public static class Variant
1160 public static bool IsEqual (TypeSpec type1, TypeSpec type2)
1162 if (!type1.IsGeneric || !type2.IsGeneric)
1165 var target_type_def = type2.MemberDefinition;
1166 if (type1.MemberDefinition != target_type_def)
1169 var t1_targs = type1.TypeArguments;
1170 var t2_targs = type2.TypeArguments;
1171 var targs_definition = target_type_def.TypeParameters;
1173 if (!type1.IsInterface && !type1.IsDelegate) {
1177 for (int i = 0; i < targs_definition.Length; ++i) {
1178 if (TypeSpecComparer.IsEqual (t1_targs[i], t2_targs[i]))
1181 Variance v = targs_definition[i].Variance;
1182 if (v == Variance.None) {
1186 if (v == Variance.Covariant) {
1187 if (!Convert.ImplicitReferenceConversionExists (t1_targs[i], t2_targs[i]))
1189 } else if (!Convert.ImplicitReferenceConversionExists (t2_targs[i], t1_targs[i])) {
1199 // Checks whether two generic instances may become equal for some
1200 // particular instantiation (26.3.1).
1202 public static class Unify
1205 // Either @a or @b must be generic type
1207 public static bool IsEqual (TypeSpec a, TypeSpec b)
1209 if (a.MemberDefinition != b.MemberDefinition) {
1210 var base_ifaces = a.Interfaces;
1211 if (base_ifaces != null) {
1212 foreach (var base_iface in base_ifaces) {
1213 if (base_iface.Arity > 0 && IsEqual (base_iface, b))
1221 var ta = a.TypeArguments;
1222 var tb = b.TypeArguments;
1223 for (int i = 0; i < ta.Length; i++) {
1224 if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
1231 static bool ContainsTypeParameter (TypeSpec tparam, TypeSpec type)
1233 TypeSpec[] targs = type.TypeArguments;
1234 for (int i = 0; i < targs.Length; i++) {
1235 if (tparam == targs[i])
1238 if (ContainsTypeParameter (tparam, targs[i]))
1246 /// Check whether `a' and `b' may become equal generic types.
1247 /// The algorithm to do that is a little bit complicated.
1249 static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
1251 if (a.IsGenericParameter) {
1253 // If a is an array of a's type, they may never
1260 // If b is a generic parameter or an actual type,
1261 // they may become equal:
1263 // class X<T,U> : I<T>, I<U>
1264 // class X<T> : I<T>, I<float>
1266 if (b.IsGenericParameter)
1267 return a != b && a.DeclaringType == b.DeclaringType;
1270 // We're now comparing a type parameter with a
1271 // generic instance. They may become equal unless
1272 // the type parameter appears anywhere in the
1273 // generic instance:
1275 // class X<T,U> : I<T>, I<X<U>>
1276 // -> error because you could instanciate it as
1279 // class X<T> : I<T>, I<X<T>> -> ok
1282 return !ContainsTypeParameter (a, b);
1285 if (b.IsGenericParameter)
1286 return MayBecomeEqualGenericTypes (b, a);
1289 // At this point, neither a nor b are a type parameter.
1291 // If one of them is a generic instance, compare them (if the
1292 // other one is not a generic instance, they can never
1295 if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
1296 return IsEqual (a, b);
1299 // If both of them are arrays.
1301 var a_ac = a as ArrayContainer;
1303 var b_ac = b as ArrayContainer;
1304 if (b_ac == null || a_ac.Rank != b_ac.Rank)
1307 return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
1311 // Ok, two ordinary types.
1317 public static bool Equals (TypeSpec[] x, TypeSpec[] y)
1322 if (x.Length != y.Length)
1325 for (int i = 0; i < x.Length; ++i)
1326 if (!IsEqual (x[i], y[i]))
1333 // Identity type conversion
1335 // Default reference comparison, it has to be used when comparing
1336 // two possible dynamic/internal types
1338 public static bool IsEqual (TypeSpec a, TypeSpec b)
1341 // This also rejects dynamic == dynamic
1342 return a.Kind != MemberKind.InternalCompilerType || a.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
1345 if (a == null || b == null)
1349 var a_a = (ArrayContainer) a;
1350 var b_a = b as ArrayContainer;
1354 return a_a.Rank == b_a.Rank && IsEqual (a_a.Element, b_a.Element);
1357 if (!a.IsGeneric || !b.IsGeneric) {
1359 // object and dynamic are considered equivalent there is an identity conversion
1360 // between object and dynamic, and between constructed types that are the same
1361 // when replacing all occurences of dynamic with object.
1363 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1364 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1369 if (a.MemberDefinition != b.MemberDefinition)
1373 if (!Equals (a.TypeArguments, b.TypeArguments))
1376 a = a.DeclaringType;
1377 b = b.DeclaringType;
1378 } while (a != null);
1384 public interface ITypeDefinition : IMemberDefinition
1386 IAssemblyDefinition DeclaringAssembly { get; }
1387 string Namespace { get; }
1388 bool IsPartial { get; }
1389 bool IsComImport { get; }
1390 bool IsTypeForwarder { get; }
1391 int TypeParametersCount { get; }
1392 TypeParameterSpec[] TypeParameters { get; }
1394 TypeSpec GetAttributeCoClass ();
1395 string GetAttributeDefaultMember ();
1396 AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
1397 bool IsInternalAsPublic (IAssemblyDefinition assembly);
1398 void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache);
1401 class InternalType : TypeSpec, ITypeDefinition
1403 public static readonly InternalType AnonymousMethod = new InternalType ("anonymous method");
1404 public static readonly InternalType Arglist = new InternalType ("__arglist");
1405 public static readonly InternalType MethodGroup = new InternalType ("method group");
1406 public static readonly InternalType NullLiteral = new InternalType ("null");
1407 public static readonly InternalType FakeInternalType = new InternalType ("<fake$type>");
1408 public static readonly InternalType Namespace = new InternalType ("<namespace>");
1409 public static readonly InternalType ErrorType = new InternalType ("<error>");
1411 readonly string name;
1413 InternalType (string name)
1414 : base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
1417 this.definition = this;
1418 cache = MemberCache.Empty;
1420 // Make all internal types CLS-compliant, non-obsolete
1421 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
1426 public override int Arity {
1432 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1434 throw new NotImplementedException ();
1438 bool ITypeDefinition.IsComImport {
1444 bool IMemberDefinition.IsImported {
1450 bool ITypeDefinition.IsPartial {
1456 bool ITypeDefinition.IsTypeForwarder {
1462 public override string Name {
1468 string ITypeDefinition.Namespace {
1474 int ITypeDefinition.TypeParametersCount {
1480 TypeParameterSpec[] ITypeDefinition.TypeParameters {
1488 public override string GetSignatureForError ()
1493 #region ITypeDefinition Members
1495 TypeSpec ITypeDefinition.GetAttributeCoClass ()
1500 string ITypeDefinition.GetAttributeDefaultMember ()
1505 AttributeUsageAttribute ITypeDefinition.GetAttributeUsage (PredefinedAttribute pa)
1510 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1512 throw new NotImplementedException ();
1515 void ITypeDefinition.LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1517 throw new NotImplementedException ();
1520 string[] IMemberDefinition.ConditionalConditions ()
1525 ObsoleteAttribute IMemberDefinition.GetAttributeObsolete ()
1530 bool? IMemberDefinition.CLSAttributeValue {
1536 void IMemberDefinition.SetIsAssigned ()
1540 void IMemberDefinition.SetIsUsed ()
1548 // Common base class for composite types
1550 public abstract class ElementTypeSpec : TypeSpec, ITypeDefinition
1552 protected ElementTypeSpec (MemberKind kind, TypeSpec element, MetaType info)
1553 : base (kind, element.DeclaringType, null, info, element.Modifiers)
1555 this.Element = element;
1557 state &= ~SharedStateFlags;
1558 state |= (element.state & SharedStateFlags);
1560 if (element.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1561 state |= StateFlags.HasDynamicElement;
1563 // Has to use its own type definition instead of just element definition to
1564 // correctly identify itself for cases like x.MemberDefininition == predefined.MemberDefinition
1565 this.definition = this;
1567 cache = MemberCache.Empty;
1572 public TypeSpec Element { get; private set; }
1574 bool ITypeDefinition.IsComImport {
1580 bool ITypeDefinition.IsPartial {
1586 bool ITypeDefinition.IsTypeForwarder {
1592 public override string Name {
1594 throw new NotSupportedException ();
1600 public override ObsoleteAttribute GetAttributeObsolete ()
1602 return Element.GetAttributeObsolete ();
1605 protected virtual string GetPostfixSignature ()
1610 public override string GetSignatureForDocumentation ()
1612 return Element.GetSignatureForDocumentation () + GetPostfixSignature ();
1615 public override string GetSignatureForError ()
1617 return Element.GetSignatureForError () + GetPostfixSignature ();
1620 public override TypeSpec Mutate (TypeParameterMutator mutator)
1622 var me = Element.Mutate (mutator);
1626 var mutated = (ElementTypeSpec) MemberwiseClone ();
1627 mutated.Element = me;
1628 mutated.info = null;
1632 #region ITypeDefinition Members
1634 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1636 return Element.MemberDefinition.DeclaringAssembly;
1640 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1642 return Element.MemberDefinition.IsInternalAsPublic (assembly);
1645 public string Namespace {
1646 get { throw new NotImplementedException (); }
1649 public int TypeParametersCount {
1655 public TypeParameterSpec[] TypeParameters {
1657 throw new NotSupportedException ();
1661 public TypeSpec GetAttributeCoClass ()
1663 return Element.MemberDefinition.GetAttributeCoClass ();
1666 public string GetAttributeDefaultMember ()
1668 return Element.MemberDefinition.GetAttributeDefaultMember ();
1671 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1673 Element.MemberDefinition.LoadMembers (declaringType, onlyTypes, ref cache);
1676 public bool IsImported {
1678 return Element.MemberDefinition.IsImported;
1682 public string[] ConditionalConditions ()
1684 return Element.MemberDefinition.ConditionalConditions ();
1687 bool? IMemberDefinition.CLSAttributeValue {
1689 return Element.MemberDefinition.CLSAttributeValue;
1693 public void SetIsAssigned ()
1695 Element.MemberDefinition.SetIsAssigned ();
1698 public void SetIsUsed ()
1700 Element.MemberDefinition.SetIsUsed ();
1706 public class ArrayContainer : ElementTypeSpec
1708 public struct TypeRankPair : IEquatable<TypeRankPair>
1713 public TypeRankPair (TypeSpec ts, int rank)
1719 public override int GetHashCode ()
1721 return ts.GetHashCode () ^ rank.GetHashCode ();
1724 #region IEquatable<Tuple<T1,T2>> Members
1726 public bool Equals (TypeRankPair other)
1728 return other.ts == ts && other.rank == rank;
1735 readonly ModuleContainer module;
1737 private ArrayContainer (ModuleContainer module, TypeSpec element, int rank)
1738 : base (MemberKind.ArrayType, element, null)
1740 this.module = module;
1750 public MethodInfo GetConstructor ()
1752 var mb = module.Builder;
1754 var arg_types = new MetaType[rank];
1755 for (int i = 0; i < rank; i++)
1756 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1758 var ctor = mb.GetArrayMethod (
1759 GetMetaInfo (), Constructor.ConstructorName,
1760 CallingConventions.HasThis,
1766 public MethodInfo GetAddressMethod ()
1768 var mb = module.Builder;
1770 var arg_types = new MetaType[rank];
1771 for (int i = 0; i < rank; i++)
1772 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1774 var address = mb.GetArrayMethod (
1775 GetMetaInfo (), "Address",
1776 CallingConventions.HasThis | CallingConventions.Standard,
1777 ReferenceContainer.MakeType (module, Element).GetMetaInfo (), arg_types);
1782 public MethodInfo GetGetMethod ()
1784 var mb = module.Builder;
1786 var arg_types = new MetaType[rank];
1787 for (int i = 0; i < rank; i++)
1788 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1790 var get = mb.GetArrayMethod (
1791 GetMetaInfo (), "Get",
1792 CallingConventions.HasThis | CallingConventions.Standard,
1793 Element.GetMetaInfo (), arg_types);
1798 public MethodInfo GetSetMethod ()
1800 var mb = module.Builder;
1802 var arg_types = new MetaType[rank + 1];
1803 for (int i = 0; i < rank; i++)
1804 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1806 arg_types[rank] = Element.GetMetaInfo ();
1808 var set = mb.GetArrayMethod (
1809 GetMetaInfo (), "Set",
1810 CallingConventions.HasThis | CallingConventions.Standard,
1811 module.Compiler.BuiltinTypes.Void.GetMetaInfo (), arg_types);
1816 public override MetaType GetMetaInfo ()
1820 info = Element.GetMetaInfo ().MakeArrayType ();
1822 info = Element.GetMetaInfo ().MakeArrayType (rank);
1828 protected override string GetPostfixSignature()
1830 return GetPostfixSignature (rank);
1833 public static string GetPostfixSignature (int rank)
1835 StringBuilder sb = new StringBuilder ();
1837 for (int i = 1; i < rank; i++) {
1842 return sb.ToString ();
1845 public override string GetSignatureForDocumentation ()
1847 StringBuilder sb = new StringBuilder ();
1848 GetElementSignatureForDocumentation (sb);
1849 return sb.ToString ();
1852 void GetElementSignatureForDocumentation (StringBuilder sb)
1854 var ac = Element as ArrayContainer;
1856 sb.Append (Element.GetSignatureForDocumentation ());
1858 ac.GetElementSignatureForDocumentation (sb);
1861 for (int i = 1; i < rank; i++) {
1870 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element)
1872 return MakeType (module, element, 1);
1875 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element, int rank)
1878 var key = new TypeRankPair (element, rank);
1879 if (!module.ArrayTypesCache.TryGetValue (key, out ac)) {
1880 ac = new ArrayContainer (module, element, rank);
1881 ac.BaseType = module.Compiler.BuiltinTypes.Array;
1882 ac.Interfaces = ac.BaseType.Interfaces;
1884 module.ArrayTypesCache.Add (key, ac);
1891 class ReferenceContainer : ElementTypeSpec
1893 private ReferenceContainer (TypeSpec element)
1894 : base (MemberKind.Class, element, null) // TODO: Kind.Class is most likely wrong
1898 public override MetaType GetMetaInfo ()
1901 info = Element.GetMetaInfo ().MakeByRefType ();
1907 public static ReferenceContainer MakeType (ModuleContainer module, TypeSpec element)
1909 ReferenceContainer pc;
1910 if (!module.ReferenceTypesCache.TryGetValue (element, out pc)) {
1911 pc = new ReferenceContainer (element);
1912 module.ReferenceTypesCache.Add (element, pc);
1919 class PointerContainer : ElementTypeSpec
1921 private PointerContainer (TypeSpec element)
1922 : base (MemberKind.PointerType, element, null)
1924 // It's never CLS-Compliant
1925 state &= ~StateFlags.CLSCompliant_Undetected;
1928 public override MetaType GetMetaInfo ()
1931 info = Element.GetMetaInfo ().MakePointerType ();
1937 protected override string GetPostfixSignature()
1942 public static PointerContainer MakeType (ModuleContainer module, TypeSpec element)
1944 PointerContainer pc;
1945 if (!module.PointerTypesCache.TryGetValue (element, out pc)) {
1946 pc = new PointerContainer (element);
1947 module.PointerTypesCache.Add (element, pc);