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;
802 public void UpdateInflatedInstancesBaseType ()
805 // When nested class has a partial part the situation where parent type
806 // is inflated before its base type is defined can occur. In such case
807 // all inflated (should be only 1) instansted need to be updated
809 // partial class A<T> {
810 // partial class B : A<int> { }
813 // partial class A<T> : X {}
815 if (inflated_instances == null)
818 foreach (var inflated in inflated_instances) {
820 // Don't need to inflate possible generic type because for now the method
821 // is always used from within the nested type
823 inflated.Value.BaseType = base_type;
829 // Special version used for types which must exist in corlib or
830 // the compiler cannot work
832 public sealed class BuiltinTypeSpec : TypeSpec
838 // Ordered carefully for fast compares
866 MulticastDelegate = 23,
879 readonly string name;
881 public BuiltinTypeSpec (MemberKind kind, string ns, string name, Type builtinKind)
882 : base (kind, null, null, null, Modifiers.PUBLIC)
884 this.type = builtinKind;
889 public BuiltinTypeSpec (string name, Type builtinKind)
890 : this (MemberKind.InternalCompilerType, "", name, builtinKind)
892 // Make all internal types CLS-compliant, non-obsolete, compact
893 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
898 public override int Arity {
904 public override BuiltinTypeSpec.Type BuiltinType {
910 public string FullName {
912 return ns + '.' + name;
916 public override string Name {
922 public string Namespace {
930 public static bool IsPrimitiveType (TypeSpec type)
932 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.LastPrimitive;
935 public static bool IsPrimitiveTypeOrDecimal (TypeSpec type)
937 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.Decimal;
940 public override string GetSignatureForError ()
943 case "Int32": return "int";
944 case "Int64": return "long";
945 case "String": return "string";
946 case "Boolean": return "bool";
947 case "Void": return "void";
948 case "Object": return "object";
949 case "UInt32": return "uint";
950 case "Int16": return "short";
951 case "UInt16": return "ushort";
952 case "UInt64": return "ulong";
953 case "Single": return "float";
954 case "Double": return "double";
955 case "Decimal": return "decimal";
956 case "Char": return "char";
957 case "Byte": return "byte";
958 case "SByte": return "sbyte";
968 // Returns the size of type if known, otherwise, 0
970 public static int GetSize (TypeSpec type)
972 switch (type.BuiltinType) {
996 public void SetDefinition (ITypeDefinition td, MetaType type, Modifiers mod)
998 this.definition = td;
1000 this.modifiers |= (mod & ~Modifiers.AccessibilityMask);
1003 public void SetDefinition (TypeSpec ts)
1005 this.definition = ts.MemberDefinition;
1006 this.info = ts.GetMetaInfo ();
1007 this.BaseType = ts.BaseType;
1008 this.Interfaces = ts.Interfaces;
1009 this.modifiers = ts.Modifiers;
1014 // Various type comparers used by compiler
1016 static class TypeSpecComparer
1019 // Does strict reference comparion only
1021 public static readonly DefaultImpl Default = new DefaultImpl ();
1023 public class DefaultImpl : IEqualityComparer<TypeSpec[]>
1025 #region IEqualityComparer<TypeSpec[]> Members
1027 bool IEqualityComparer<TypeSpec[]>.Equals (TypeSpec[] x, TypeSpec[] y)
1032 if (x.Length != y.Length)
1035 for (int i = 0; i < x.Length; ++i)
1042 int IEqualityComparer<TypeSpec[]>.GetHashCode (TypeSpec[] obj)
1045 for (int i = 0; i < obj.Length; ++i)
1046 hash = (hash << 5) - hash + obj[i].GetHashCode ();
1055 // When comparing type signature of overrides or overloads
1056 // this version tolerates different MVARs at same position
1058 public static class Override
1060 public static bool IsEqual (TypeSpec a, TypeSpec b)
1066 // Consider the following example:
1068 // public abstract class A
1070 // public abstract T Foo<T>();
1073 // public class B : A
1075 // public override U Foo<T>() { return default (U); }
1078 // Here, `T' and `U' are method type parameters from different methods
1079 // (A.Foo and B.Foo), so both `==' and Equals() will fail.
1081 // However, since we're determining whether B.Foo() overrides A.Foo(),
1082 // we need to do a signature based comparision and consider them equal.
1085 var tp_a = a as TypeParameterSpec;
1087 var tp_b = b as TypeParameterSpec;
1088 return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
1091 var ac_a = a as ArrayContainer;
1093 var ac_b = b as ArrayContainer;
1094 return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
1097 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1098 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1100 if (a.MemberDefinition != b.MemberDefinition)
1104 for (int i = 0; i < a.TypeArguments.Length; ++i) {
1105 if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
1109 a = a.DeclaringType;
1110 b = b.DeclaringType;
1111 } while (a != null);
1116 public static bool IsEqual (TypeSpec[] a, TypeSpec[] b)
1121 if (a.Length != b.Length)
1124 for (int i = 0; i < a.Length; ++i) {
1125 if (!IsEqual (a[i], b[i]))
1134 // Compares unordered arrays
1136 public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
1141 if (a == null || b == null || a.Length != b.Length)
1144 for (int ai = 0; ai < a.Length; ++ai) {
1146 for (int bi = 0; bi < b.Length; ++bi) {
1147 if (IsEqual (a[ai], b[bi])) {
1160 public static bool IsEqual (AParametersCollection a, AParametersCollection b)
1165 if (a.Count != b.Count)
1168 for (int i = 0; i < a.Count; ++i) {
1169 if (!IsEqual (a.Types[i], b.Types[i]))
1172 if ((a.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (b.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask))
1181 // Type variance equality comparison
1183 public static class Variant
1185 public static bool IsEqual (TypeSpec type1, TypeSpec type2)
1187 if (!type1.IsGeneric || !type2.IsGeneric)
1190 var target_type_def = type2.MemberDefinition;
1191 if (type1.MemberDefinition != target_type_def)
1194 var t1_targs = type1.TypeArguments;
1195 var t2_targs = type2.TypeArguments;
1196 var targs_definition = target_type_def.TypeParameters;
1198 if (!type1.IsInterface && !type1.IsDelegate) {
1202 for (int i = 0; i < targs_definition.Length; ++i) {
1203 if (TypeSpecComparer.IsEqual (t1_targs[i], t2_targs[i]))
1206 Variance v = targs_definition[i].Variance;
1207 if (v == Variance.None) {
1211 if (v == Variance.Covariant) {
1212 if (!Convert.ImplicitReferenceConversionExists (t1_targs[i], t2_targs[i]))
1214 } else if (!Convert.ImplicitReferenceConversionExists (t2_targs[i], t1_targs[i])) {
1224 // Checks whether two generic instances may become equal for some
1225 // particular instantiation (26.3.1).
1227 public static class Unify
1230 // Either @a or @b must be generic type
1232 public static bool IsEqual (TypeSpec a, TypeSpec b)
1234 if (a.MemberDefinition != b.MemberDefinition) {
1235 var base_ifaces = a.Interfaces;
1236 if (base_ifaces != null) {
1237 foreach (var base_iface in base_ifaces) {
1238 if (base_iface.Arity > 0 && IsEqual (base_iface, b))
1246 var ta = a.TypeArguments;
1247 var tb = b.TypeArguments;
1248 for (int i = 0; i < ta.Length; i++) {
1249 if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
1256 static bool ContainsTypeParameter (TypeSpec tparam, TypeSpec type)
1258 TypeSpec[] targs = type.TypeArguments;
1259 for (int i = 0; i < targs.Length; i++) {
1260 if (tparam == targs[i])
1263 if (ContainsTypeParameter (tparam, targs[i]))
1271 /// Check whether `a' and `b' may become equal generic types.
1272 /// The algorithm to do that is a little bit complicated.
1274 static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
1276 if (a.IsGenericParameter) {
1278 // If a is an array of a's type, they may never
1285 // If b is a generic parameter or an actual type,
1286 // they may become equal:
1288 // class X<T,U> : I<T>, I<U>
1289 // class X<T> : I<T>, I<float>
1291 if (b.IsGenericParameter)
1292 return a != b && a.DeclaringType == b.DeclaringType;
1295 // We're now comparing a type parameter with a
1296 // generic instance. They may become equal unless
1297 // the type parameter appears anywhere in the
1298 // generic instance:
1300 // class X<T,U> : I<T>, I<X<U>>
1301 // -> error because you could instanciate it as
1304 // class X<T> : I<T>, I<X<T>> -> ok
1307 return !ContainsTypeParameter (a, b);
1310 if (b.IsGenericParameter)
1311 return MayBecomeEqualGenericTypes (b, a);
1314 // At this point, neither a nor b are a type parameter.
1316 // If one of them is a generic instance, compare them (if the
1317 // other one is not a generic instance, they can never
1320 if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
1321 return IsEqual (a, b);
1324 // If both of them are arrays.
1326 var a_ac = a as ArrayContainer;
1328 var b_ac = b as ArrayContainer;
1329 if (b_ac == null || a_ac.Rank != b_ac.Rank)
1332 return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
1336 // Ok, two ordinary types.
1342 public static bool Equals (TypeSpec[] x, TypeSpec[] y)
1347 if (x.Length != y.Length)
1350 for (int i = 0; i < x.Length; ++i)
1351 if (!IsEqual (x[i], y[i]))
1358 // Identity type conversion
1360 // Default reference comparison, it has to be used when comparing
1361 // two possible dynamic/internal types
1363 public static bool IsEqual (TypeSpec a, TypeSpec b)
1366 // This also rejects dynamic == dynamic
1367 return a.Kind != MemberKind.InternalCompilerType || a.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
1370 if (a == null || b == null)
1374 var a_a = (ArrayContainer) a;
1375 var b_a = b as ArrayContainer;
1379 return a_a.Rank == b_a.Rank && IsEqual (a_a.Element, b_a.Element);
1382 if (!a.IsGeneric || !b.IsGeneric) {
1384 // object and dynamic are considered equivalent there is an identity conversion
1385 // between object and dynamic, and between constructed types that are the same
1386 // when replacing all occurences of dynamic with object.
1388 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1389 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1394 if (a.MemberDefinition != b.MemberDefinition)
1398 if (!Equals (a.TypeArguments, b.TypeArguments))
1401 a = a.DeclaringType;
1402 b = b.DeclaringType;
1403 } while (a != null);
1409 public interface ITypeDefinition : IMemberDefinition
1411 IAssemblyDefinition DeclaringAssembly { get; }
1412 string Namespace { get; }
1413 bool IsPartial { get; }
1414 bool IsComImport { get; }
1415 bool IsTypeForwarder { get; }
1416 int TypeParametersCount { get; }
1417 TypeParameterSpec[] TypeParameters { get; }
1419 TypeSpec GetAttributeCoClass ();
1420 string GetAttributeDefaultMember ();
1421 AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
1422 bool IsInternalAsPublic (IAssemblyDefinition assembly);
1423 void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache);
1426 class InternalType : TypeSpec, ITypeDefinition
1428 public static readonly InternalType AnonymousMethod = new InternalType ("anonymous method");
1429 public static readonly InternalType Arglist = new InternalType ("__arglist");
1430 public static readonly InternalType MethodGroup = new InternalType ("method group");
1431 public static readonly InternalType NullLiteral = new InternalType ("null");
1432 public static readonly InternalType FakeInternalType = new InternalType ("<fake$type>");
1433 public static readonly InternalType Namespace = new InternalType ("<namespace>");
1434 public static readonly InternalType ErrorType = new InternalType ("<error>");
1436 readonly string name;
1438 InternalType (string name)
1439 : base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
1442 this.definition = this;
1443 cache = MemberCache.Empty;
1445 // Make all internal types CLS-compliant, non-obsolete
1446 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
1451 public override int Arity {
1457 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1459 throw new NotImplementedException ();
1463 bool ITypeDefinition.IsComImport {
1469 bool IMemberDefinition.IsImported {
1475 bool ITypeDefinition.IsPartial {
1481 bool ITypeDefinition.IsTypeForwarder {
1487 public override string Name {
1493 string ITypeDefinition.Namespace {
1499 int ITypeDefinition.TypeParametersCount {
1505 TypeParameterSpec[] ITypeDefinition.TypeParameters {
1513 public override string GetSignatureForError ()
1518 #region ITypeDefinition Members
1520 TypeSpec ITypeDefinition.GetAttributeCoClass ()
1525 string ITypeDefinition.GetAttributeDefaultMember ()
1530 AttributeUsageAttribute ITypeDefinition.GetAttributeUsage (PredefinedAttribute pa)
1535 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1537 throw new NotImplementedException ();
1540 void ITypeDefinition.LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1542 throw new NotImplementedException ();
1545 string[] IMemberDefinition.ConditionalConditions ()
1550 ObsoleteAttribute IMemberDefinition.GetAttributeObsolete ()
1555 bool? IMemberDefinition.CLSAttributeValue {
1561 void IMemberDefinition.SetIsAssigned ()
1565 void IMemberDefinition.SetIsUsed ()
1573 // Common base class for composite types
1575 public abstract class ElementTypeSpec : TypeSpec, ITypeDefinition
1577 protected ElementTypeSpec (MemberKind kind, TypeSpec element, MetaType info)
1578 : base (kind, element.DeclaringType, null, info, element.Modifiers)
1580 this.Element = element;
1582 state &= ~SharedStateFlags;
1583 state |= (element.state & SharedStateFlags);
1585 if (element.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1586 state |= StateFlags.HasDynamicElement;
1588 // Has to use its own type definition instead of just element definition to
1589 // correctly identify itself for cases like x.MemberDefininition == predefined.MemberDefinition
1590 this.definition = this;
1592 cache = MemberCache.Empty;
1597 public TypeSpec Element { get; private set; }
1599 bool ITypeDefinition.IsComImport {
1605 bool ITypeDefinition.IsPartial {
1611 bool ITypeDefinition.IsTypeForwarder {
1617 public override string Name {
1619 throw new NotSupportedException ();
1625 public override ObsoleteAttribute GetAttributeObsolete ()
1627 return Element.GetAttributeObsolete ();
1630 protected virtual string GetPostfixSignature ()
1635 public override string GetSignatureForDocumentation ()
1637 return Element.GetSignatureForDocumentation () + GetPostfixSignature ();
1640 public override string GetSignatureForError ()
1642 return Element.GetSignatureForError () + GetPostfixSignature ();
1645 public override TypeSpec Mutate (TypeParameterMutator mutator)
1647 var me = Element.Mutate (mutator);
1651 var mutated = (ElementTypeSpec) MemberwiseClone ();
1652 mutated.Element = me;
1653 mutated.info = null;
1657 #region ITypeDefinition Members
1659 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1661 return Element.MemberDefinition.DeclaringAssembly;
1665 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1667 return Element.MemberDefinition.IsInternalAsPublic (assembly);
1670 public string Namespace {
1671 get { throw new NotImplementedException (); }
1674 public int TypeParametersCount {
1680 public TypeParameterSpec[] TypeParameters {
1682 throw new NotSupportedException ();
1686 public TypeSpec GetAttributeCoClass ()
1688 return Element.MemberDefinition.GetAttributeCoClass ();
1691 public string GetAttributeDefaultMember ()
1693 return Element.MemberDefinition.GetAttributeDefaultMember ();
1696 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1698 Element.MemberDefinition.LoadMembers (declaringType, onlyTypes, ref cache);
1701 public bool IsImported {
1703 return Element.MemberDefinition.IsImported;
1707 public string[] ConditionalConditions ()
1709 return Element.MemberDefinition.ConditionalConditions ();
1712 bool? IMemberDefinition.CLSAttributeValue {
1714 return Element.MemberDefinition.CLSAttributeValue;
1718 public void SetIsAssigned ()
1720 Element.MemberDefinition.SetIsAssigned ();
1723 public void SetIsUsed ()
1725 Element.MemberDefinition.SetIsUsed ();
1731 public class ArrayContainer : ElementTypeSpec
1733 public struct TypeRankPair : IEquatable<TypeRankPair>
1738 public TypeRankPair (TypeSpec ts, int rank)
1744 public override int GetHashCode ()
1746 return ts.GetHashCode () ^ rank.GetHashCode ();
1749 #region IEquatable<Tuple<T1,T2>> Members
1751 public bool Equals (TypeRankPair other)
1753 return other.ts == ts && other.rank == rank;
1760 readonly ModuleContainer module;
1762 private ArrayContainer (ModuleContainer module, TypeSpec element, int rank)
1763 : base (MemberKind.ArrayType, element, null)
1765 this.module = module;
1775 public MethodInfo GetConstructor ()
1777 var mb = module.Builder;
1779 var arg_types = new MetaType[rank];
1780 for (int i = 0; i < rank; i++)
1781 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1783 var ctor = mb.GetArrayMethod (
1784 GetMetaInfo (), Constructor.ConstructorName,
1785 CallingConventions.HasThis,
1791 public MethodInfo GetAddressMethod ()
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 address = mb.GetArrayMethod (
1800 GetMetaInfo (), "Address",
1801 CallingConventions.HasThis | CallingConventions.Standard,
1802 ReferenceContainer.MakeType (module, Element).GetMetaInfo (), arg_types);
1807 public MethodInfo GetGetMethod ()
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 get = mb.GetArrayMethod (
1816 GetMetaInfo (), "Get",
1817 CallingConventions.HasThis | CallingConventions.Standard,
1818 Element.GetMetaInfo (), arg_types);
1823 public MethodInfo GetSetMethod ()
1825 var mb = module.Builder;
1827 var arg_types = new MetaType[rank + 1];
1828 for (int i = 0; i < rank; i++)
1829 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1831 arg_types[rank] = Element.GetMetaInfo ();
1833 var set = mb.GetArrayMethod (
1834 GetMetaInfo (), "Set",
1835 CallingConventions.HasThis | CallingConventions.Standard,
1836 module.Compiler.BuiltinTypes.Void.GetMetaInfo (), arg_types);
1841 public override MetaType GetMetaInfo ()
1845 info = Element.GetMetaInfo ().MakeArrayType ();
1847 info = Element.GetMetaInfo ().MakeArrayType (rank);
1853 protected override string GetPostfixSignature()
1855 return GetPostfixSignature (rank);
1858 public static string GetPostfixSignature (int rank)
1860 StringBuilder sb = new StringBuilder ();
1862 for (int i = 1; i < rank; i++) {
1867 return sb.ToString ();
1870 public override string GetSignatureForDocumentation ()
1872 StringBuilder sb = new StringBuilder ();
1873 GetElementSignatureForDocumentation (sb);
1874 return sb.ToString ();
1877 void GetElementSignatureForDocumentation (StringBuilder sb)
1879 var ac = Element as ArrayContainer;
1881 sb.Append (Element.GetSignatureForDocumentation ());
1883 ac.GetElementSignatureForDocumentation (sb);
1886 for (int i = 1; i < rank; i++) {
1895 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element)
1897 return MakeType (module, element, 1);
1900 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element, int rank)
1903 var key = new TypeRankPair (element, rank);
1904 if (!module.ArrayTypesCache.TryGetValue (key, out ac)) {
1905 ac = new ArrayContainer (module, element, rank);
1906 ac.BaseType = module.Compiler.BuiltinTypes.Array;
1907 ac.Interfaces = ac.BaseType.Interfaces;
1909 module.ArrayTypesCache.Add (key, ac);
1916 class ReferenceContainer : ElementTypeSpec
1918 private ReferenceContainer (TypeSpec element)
1919 : base (MemberKind.Class, element, null) // TODO: Kind.Class is most likely wrong
1923 public override MetaType GetMetaInfo ()
1926 info = Element.GetMetaInfo ().MakeByRefType ();
1932 public static ReferenceContainer MakeType (ModuleContainer module, TypeSpec element)
1934 ReferenceContainer pc;
1935 if (!module.ReferenceTypesCache.TryGetValue (element, out pc)) {
1936 pc = new ReferenceContainer (element);
1937 module.ReferenceTypesCache.Add (element, pc);
1944 class PointerContainer : ElementTypeSpec
1946 private PointerContainer (TypeSpec element)
1947 : base (MemberKind.PointerType, element, null)
1949 // It's never CLS-Compliant
1950 state &= ~StateFlags.CLSCompliant_Undetected;
1953 public override MetaType GetMetaInfo ()
1956 info = Element.GetMetaInfo ().MakePointerType ();
1962 protected override string GetPostfixSignature()
1967 public static PointerContainer MakeType (ModuleContainer module, TypeSpec element)
1969 PointerContainer pc;
1970 if (!module.PointerTypesCache.TryGetValue (element, out pc)) {
1971 pc = new PointerContainer (element);
1972 module.PointerTypesCache.Add (element, pc);