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 IsStructOrEnum {
300 return (Kind & (MemberKind.Struct | MemberKind.Enum)) != 0;
304 public bool IsTypeBuilder {
309 var meta = GetMetaInfo().GetType ();
310 return meta == TypeBuilder || meta == GenericTypeBuilder;
316 // Whether a type is unmanaged. This is used by the unsafe code
318 public bool IsUnmanaged {
321 return ((ElementTypeSpec) this).Element.IsUnmanaged;
323 var ds = MemberDefinition as TypeDefinition;
325 return ds.IsUnmanagedType ();
327 if (Kind == MemberKind.Void)
330 if (Kind == MemberKind.TypeParameter)
333 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
336 return IsValueType (this);
341 // A cache of all type members (including nested types)
343 public MemberCache MemberCache {
345 if (cache == null || (state & StateFlags.PendingMemberCacheMembers) != 0)
346 InitializeMemberCache (false);
352 throw new InternalErrorException ("Membercache reset");
358 public MemberCache MemberCacheTypes {
361 InitializeMemberCache (true);
367 public new ITypeDefinition MemberDefinition {
369 return (ITypeDefinition) definition;
373 // TODO: Wouldn't be better to rely on cast to InflatedTypeSpec and
374 // remove the property, YES IT WOULD !!!
375 public virtual TypeSpec[] TypeArguments {
376 get { return TypeSpec.EmptyTypes; }
381 public virtual bool AddInterface (TypeSpec iface)
383 if ((state & StateFlags.InterfacesExpanded) != 0)
384 throw new InternalErrorException ("Modifying expanded interface list");
386 if (ifaces == null) {
387 ifaces = new List<TypeSpec> { iface };
391 if (!ifaces.Contains (iface)) {
400 // Special version used during type definition
402 public bool AddInterfaceDefined (TypeSpec iface)
404 if (!AddInterface (iface))
408 // We can get into a situation where a type is inflated before
409 // its interfaces are resoved. Consider this situation
411 // class A<T> : X<A<int>>, IFoo {}
413 // When resolving base class of X`1 we inflate context type A`1
414 // All this happens before we even hit IFoo resolve. Without
415 // additional expansion any inside usage of A<T> would miss IFoo
416 // interface because it comes from early inflated A`1 definition.
418 if (inflated_instances != null) {
420 // Inflate only existing instances not any new instances added
421 // during AddInterface
423 var inflated_existing = inflated_instances.Values.ToArray ();
424 foreach (var inflated in inflated_existing) {
425 inflated.AddInterface (iface);
433 // Returns all type arguments, usefull for nested types
435 public static TypeSpec[] GetAllTypeArguments (TypeSpec type)
437 IList<TypeSpec> targs = TypeSpec.EmptyTypes;
440 if (type.Arity > 0) {
441 if (targs.Count == 0) {
442 targs = type.TypeArguments;
444 var list = targs as List<TypeSpec> ?? new List<TypeSpec> (targs);
445 list.AddRange (type.TypeArguments);
450 type = type.declaringType;
451 } while (type != null);
453 return targs as TypeSpec[] ?? ((List<TypeSpec>) targs).ToArray ();
456 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
458 if (Kind != MemberKind.Class)
459 throw new InternalErrorException ();
462 return Attribute.DefaultUsageAttribute;
464 AttributeUsageAttribute aua = null;
466 while (type != null) {
467 aua = type.MemberDefinition.GetAttributeUsage (pa);
471 type = type.BaseType;
478 // Return metadata information used during emit to describe the type
480 public virtual MetaType GetMetaInfo ()
485 public virtual TypeSpec GetDefinition ()
491 // Text representation of type used by documentation writer
493 public override string GetSignatureForDocumentation ()
495 StringBuilder sb = new StringBuilder ();
497 sb.Append (DeclaringType.GetSignatureForDocumentation ());
499 sb.Append (MemberDefinition.Namespace);
507 if (this is InflatedTypeSpec) {
509 for (int i = 0; i < Arity; ++i) {
513 sb.Append (TypeArguments[i].GetSignatureForDocumentation ());
518 sb.Append (Arity.ToString ());
522 return sb.ToString ();
525 public string GetExplicitNameSignatureForDocumentation ()
527 StringBuilder sb = new StringBuilder ();
529 sb.Append (DeclaringType.GetExplicitNameSignatureForDocumentation ());
530 } else if (MemberDefinition.Namespace != null) {
531 sb.Append (MemberDefinition.Namespace.Replace ('.', '#'));
540 for (int i = 0; i < Arity; ++i) {
544 sb.Append (TypeArguments[i].GetExplicitNameSignatureForDocumentation ());
549 return sb.ToString ();
552 public override string GetSignatureForError ()
557 s = DeclaringType.GetSignatureForError ();
558 } else if (MemberDefinition is AnonymousTypeClass) {
559 return ((AnonymousTypeClass) MemberDefinition).GetSignatureForError ();
561 s = MemberDefinition.Namespace;
564 if (!string.IsNullOrEmpty (s))
567 return s + Name + GetTypeNameSignature ();
570 public string GetSignatureForErrorIncludingAssemblyName ()
572 return string.Format ("{0} [{1}]", GetSignatureForError (), MemberDefinition.DeclaringAssembly.FullName);
575 protected virtual string GetTypeNameSignature ()
580 return "<" + TypeManager.CSharpName (MemberDefinition.TypeParameters) + ">";
583 public bool ImplementsInterface (TypeSpec iface, bool variantly)
585 var ifaces = Interfaces;
586 if (ifaces != null) {
587 for (int i = 0; i < ifaces.Count; ++i) {
588 if (TypeSpecComparer.IsEqual (ifaces[i], iface))
591 if (variantly && TypeSpecComparer.Variant.IsEqual (ifaces[i], iface))
599 protected virtual void InitializeMemberCache (bool onlyTypes)
602 MemberDefinition.LoadMembers (this, onlyTypes, ref cache);
603 } catch (Exception e) {
604 throw new InternalErrorException (e, "Unexpected error when loading type `{0}'", GetSignatureForError ());
608 state |= StateFlags.PendingMemberCacheMembers;
610 state &= ~StateFlags.PendingMemberCacheMembers;
614 // Is @baseClass base implementation of @type. With enabled @dynamicIsEqual the slower
615 // comparison is used to hide differences between `object' and `dynamic' for generic
616 // types. Should not be used for comparisons where G<object> != G<dynamic>
618 public static bool IsBaseClass (TypeSpec type, TypeSpec baseClass, bool dynamicIsObject)
620 if (dynamicIsObject && baseClass.IsGeneric) {
622 // Returns true for a hierarchies like this when passing baseClass of A<dynamic>
624 // class B : A<object> {}
626 type = type.BaseType;
627 while (type != null) {
628 if (TypeSpecComparer.IsEqual (type, baseClass))
631 type = type.BaseType;
637 while (type != null) {
638 type = type.BaseType;
639 if (type == baseClass)
646 public static bool IsReferenceType (TypeSpec t)
649 case MemberKind.TypeParameter:
650 return ((TypeParameterSpec) t).IsReferenceType;
651 case MemberKind.Struct:
652 case MemberKind.Enum:
653 case MemberKind.Void:
654 case MemberKind.PointerType:
656 case MemberKind.InternalCompilerType:
658 // Null is considered to be a reference type
660 return t == InternalType.NullLiteral || t.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
666 public static bool IsNonNullableValueType (TypeSpec t)
669 case MemberKind.TypeParameter:
670 return ((TypeParameterSpec) t).IsValueType;
671 case MemberKind.Struct:
672 return !t.IsNullableType;
673 case MemberKind.Enum:
680 public static bool IsValueType (TypeSpec t)
683 case MemberKind.TypeParameter:
684 return ((TypeParameterSpec) t).IsValueType;
685 case MemberKind.Struct:
686 case MemberKind.Enum:
693 public override MemberSpec InflateMember (TypeParameterInflator inflator)
695 var targs = IsGeneric ? MemberDefinition.TypeParameters : TypeSpec.EmptyTypes;
698 // When inflating nested type from inside the type instance will be same
699 // because type parameters are same for all nested types
701 if (DeclaringType == inflator.TypeInstance) {
702 return MakeGenericType (inflator.Context, targs);
705 return new InflatedTypeSpec (inflator.Context, this, inflator.TypeInstance, targs);
709 // Inflates current type using specific type arguments
711 public InflatedTypeSpec MakeGenericType (IModuleContext context, TypeSpec[] targs)
713 if (targs.Length == 0 && !IsNested)
714 throw new ArgumentException ("Empty type arguments for type " + GetSignatureForError ());
716 InflatedTypeSpec instance;
718 if (inflated_instances == null) {
719 inflated_instances = new Dictionary<TypeSpec[], InflatedTypeSpec> (TypeSpecComparer.Default);
722 instance = this as InflatedTypeSpec;
723 if (instance != null) {
725 // Nested types could be inflated on already inflated instances
726 // Caching this type ensured we are using same instance for
727 // inside/outside inflation using local type parameters
729 inflated_instances.Add (TypeArguments, instance);
734 if (!inflated_instances.TryGetValue (targs, out instance)) {
735 if (GetDefinition () != this && !IsNested)
736 throw new InternalErrorException ("`{0}' must be type definition or nested non-inflated type to MakeGenericType",
737 GetSignatureForError ());
739 instance = new InflatedTypeSpec (context, this, declaringType, targs);
740 inflated_instances.Add (targs, instance);
746 public virtual TypeSpec Mutate (TypeParameterMutator mutator)
751 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
753 List<MissingTypeSpecReference> missing = null;
755 if (Kind == MemberKind.MissingType) {
756 missing = new List<MissingTypeSpecReference> ();
757 missing.Add (new MissingTypeSpecReference (this, caller));
761 foreach (var targ in TypeArguments) {
762 if (targ.Kind == MemberKind.MissingType) {
764 missing = new List<MissingTypeSpecReference> ();
766 missing.Add (new MissingTypeSpecReference (targ, caller));
770 if (Interfaces != null) {
771 foreach (var iface in Interfaces) {
772 if (iface.Kind == MemberKind.MissingType) {
774 missing = new List<MissingTypeSpecReference> ();
776 missing.Add (new MissingTypeSpecReference (iface, caller));
781 if (MemberDefinition.TypeParametersCount > 0) {
782 foreach (var tp in MemberDefinition.TypeParameters) {
783 var tp_missing = tp.GetMissingDependencies (this);
784 if (tp_missing != null) {
786 missing = new List<MissingTypeSpecReference> ();
788 missing.AddRange (tp_missing);
793 if (missing != null || BaseType == null)
796 return BaseType.ResolveMissingDependencies (this);
799 public void SetMetaInfo (MetaType info)
801 if (this.info != null)
802 throw new InternalErrorException ("MetaInfo reset");
807 public void SetExtensionMethodContainer ()
809 modifiers |= Modifiers.METHOD_EXTENSION;
812 public void UpdateInflatedInstancesBaseType ()
815 // When nested class has a partial part the situation where parent type
816 // is inflated before its base type is defined can occur. In such case
817 // all inflated (should be only 1) instansted need to be updated
819 // partial class A<T> {
820 // partial class B : A<int> { }
823 // partial class A<T> : X {}
825 if (inflated_instances == null)
828 foreach (var inflated in inflated_instances) {
830 // Don't need to inflate possible generic type because for now the method
831 // is always used from within the nested type
833 inflated.Value.BaseType = base_type;
839 // Special version used for types which must exist in corlib or
840 // the compiler cannot work
842 public sealed class BuiltinTypeSpec : TypeSpec
848 // Ordered carefully for fast compares
876 MulticastDelegate = 23,
889 readonly string name;
891 public BuiltinTypeSpec (MemberKind kind, string ns, string name, Type builtinKind)
892 : base (kind, null, null, null, Modifiers.PUBLIC)
894 this.type = builtinKind;
899 public BuiltinTypeSpec (string name, Type builtinKind)
900 : this (MemberKind.InternalCompilerType, "", name, builtinKind)
902 // Make all internal types CLS-compliant, non-obsolete, compact
903 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
908 public override int Arity {
914 public override BuiltinTypeSpec.Type BuiltinType {
920 public string FullName {
922 return ns + '.' + name;
926 public override string Name {
932 public string Namespace {
940 public static bool IsPrimitiveType (TypeSpec type)
942 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.LastPrimitive;
945 public static bool IsPrimitiveTypeOrDecimal (TypeSpec type)
947 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.Decimal;
950 public override string GetSignatureForError ()
953 case "Int32": return "int";
954 case "Int64": return "long";
955 case "String": return "string";
956 case "Boolean": return "bool";
957 case "Void": return "void";
958 case "Object": return "object";
959 case "UInt32": return "uint";
960 case "Int16": return "short";
961 case "UInt16": return "ushort";
962 case "UInt64": return "ulong";
963 case "Single": return "float";
964 case "Double": return "double";
965 case "Decimal": return "decimal";
966 case "Char": return "char";
967 case "Byte": return "byte";
968 case "SByte": return "sbyte";
978 // Returns the size of type if known, otherwise, 0
980 public static int GetSize (TypeSpec type)
982 switch (type.BuiltinType) {
1006 public void SetDefinition (ITypeDefinition td, MetaType type, Modifiers mod)
1008 this.definition = td;
1010 this.modifiers |= (mod & ~Modifiers.AccessibilityMask);
1013 public void SetDefinition (TypeSpec ts)
1015 this.definition = ts.MemberDefinition;
1016 this.info = ts.GetMetaInfo ();
1017 this.BaseType = ts.BaseType;
1018 this.Interfaces = ts.Interfaces;
1019 this.modifiers = ts.Modifiers;
1024 // Various type comparers used by compiler
1026 static class TypeSpecComparer
1029 // Does strict reference comparion only
1031 public static readonly DefaultImpl Default = new DefaultImpl ();
1033 public class DefaultImpl : IEqualityComparer<TypeSpec[]>
1035 #region IEqualityComparer<TypeSpec[]> Members
1037 bool IEqualityComparer<TypeSpec[]>.Equals (TypeSpec[] x, TypeSpec[] y)
1042 if (x.Length != y.Length)
1045 for (int i = 0; i < x.Length; ++i)
1052 int IEqualityComparer<TypeSpec[]>.GetHashCode (TypeSpec[] obj)
1055 for (int i = 0; i < obj.Length; ++i)
1056 hash = (hash << 5) - hash + obj[i].GetHashCode ();
1065 // When comparing type signature of overrides or overloads
1066 // this version tolerates different MVARs at same position
1068 public static class Override
1070 public static bool IsEqual (TypeSpec a, TypeSpec b)
1076 // Consider the following example:
1078 // public abstract class A
1080 // public abstract T Foo<T>();
1083 // public class B : A
1085 // public override U Foo<T>() { return default (U); }
1088 // Here, `T' and `U' are method type parameters from different methods
1089 // (A.Foo and B.Foo), so both `==' and Equals() will fail.
1091 // However, since we're determining whether B.Foo() overrides A.Foo(),
1092 // we need to do a signature based comparision and consider them equal.
1095 var tp_a = a as TypeParameterSpec;
1097 var tp_b = b as TypeParameterSpec;
1098 return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
1101 var ac_a = a as ArrayContainer;
1103 var ac_b = b as ArrayContainer;
1104 return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
1107 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1108 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1110 if (a.MemberDefinition != b.MemberDefinition)
1114 for (int i = 0; i < a.TypeArguments.Length; ++i) {
1115 if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
1119 a = a.DeclaringType;
1120 b = b.DeclaringType;
1121 } while (a != null);
1126 public static bool IsEqual (TypeSpec[] a, TypeSpec[] b)
1131 if (a.Length != b.Length)
1134 for (int i = 0; i < a.Length; ++i) {
1135 if (!IsEqual (a[i], b[i]))
1144 // Compares unordered arrays
1146 public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
1151 if (a == null || b == null || a.Length != b.Length)
1154 for (int ai = 0; ai < a.Length; ++ai) {
1156 for (int bi = 0; bi < b.Length; ++bi) {
1157 if (IsEqual (a[ai], b[bi])) {
1170 public static bool IsEqual (AParametersCollection a, AParametersCollection b)
1175 if (a.Count != b.Count)
1178 for (int i = 0; i < a.Count; ++i) {
1179 if (!IsEqual (a.Types[i], b.Types[i]))
1182 if ((a.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (b.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask))
1191 // Type variance equality comparison
1193 public static class Variant
1195 public static bool IsEqual (TypeSpec type1, TypeSpec type2)
1197 if (!type1.IsGeneric || !type2.IsGeneric)
1200 var target_type_def = type2.MemberDefinition;
1201 if (type1.MemberDefinition != target_type_def)
1204 var t1_targs = type1.TypeArguments;
1205 var t2_targs = type2.TypeArguments;
1206 var targs_definition = target_type_def.TypeParameters;
1208 if (!type1.IsInterface && !type1.IsDelegate) {
1212 for (int i = 0; i < targs_definition.Length; ++i) {
1213 if (TypeSpecComparer.IsEqual (t1_targs[i], t2_targs[i]))
1216 Variance v = targs_definition[i].Variance;
1217 if (v == Variance.None) {
1221 if (v == Variance.Covariant) {
1222 if (!Convert.ImplicitReferenceConversionExists (t1_targs[i], t2_targs[i]))
1224 } else if (!Convert.ImplicitReferenceConversionExists (t2_targs[i], t1_targs[i])) {
1234 // Checks whether two generic instances may become equal for some
1235 // particular instantiation (26.3.1).
1237 public static class Unify
1240 // Either @a or @b must be generic type
1242 public static bool IsEqual (TypeSpec a, TypeSpec b)
1244 if (a.MemberDefinition != b.MemberDefinition) {
1245 var base_ifaces = a.Interfaces;
1246 if (base_ifaces != null) {
1247 foreach (var base_iface in base_ifaces) {
1248 if (base_iface.Arity > 0 && IsEqual (base_iface, b))
1256 var ta = a.TypeArguments;
1257 var tb = b.TypeArguments;
1258 for (int i = 0; i < ta.Length; i++) {
1259 if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
1263 if (a.IsNested && b.IsNested)
1264 return IsEqual (a.DeclaringType, b.DeclaringType);
1269 static bool ContainsTypeParameter (TypeSpec tparam, TypeSpec type)
1271 TypeSpec[] targs = type.TypeArguments;
1272 for (int i = 0; i < targs.Length; i++) {
1273 if (tparam == targs[i])
1276 if (ContainsTypeParameter (tparam, targs[i]))
1284 /// Check whether `a' and `b' may become equal generic types.
1285 /// The algorithm to do that is a little bit complicated.
1287 static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
1289 if (a.IsGenericParameter) {
1291 // If a is an array of a's type, they may never
1298 // If b is a generic parameter or an actual type,
1299 // they may become equal:
1301 // class X<T,U> : I<T>, I<U>
1302 // class X<T> : I<T>, I<float>
1304 if (b.IsGenericParameter)
1305 return a != b && a.DeclaringType == b.DeclaringType;
1308 // We're now comparing a type parameter with a
1309 // generic instance. They may become equal unless
1310 // the type parameter appears anywhere in the
1311 // generic instance:
1313 // class X<T,U> : I<T>, I<X<U>>
1314 // -> error because you could instanciate it as
1317 // class X<T> : I<T>, I<X<T>> -> ok
1320 return !ContainsTypeParameter (a, b);
1323 if (b.IsGenericParameter)
1324 return MayBecomeEqualGenericTypes (b, a);
1327 // At this point, neither a nor b are a type parameter.
1329 // If one of them is a generic instance, compare them (if the
1330 // other one is not a generic instance, they can never
1333 if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
1334 return IsEqual (a, b);
1337 // If both of them are arrays.
1339 var a_ac = a as ArrayContainer;
1341 var b_ac = b as ArrayContainer;
1342 if (b_ac == null || a_ac.Rank != b_ac.Rank)
1345 return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
1349 // Ok, two ordinary types.
1355 public static bool Equals (TypeSpec[] x, TypeSpec[] y)
1360 if (x.Length != y.Length)
1363 for (int i = 0; i < x.Length; ++i)
1364 if (!IsEqual (x[i], y[i]))
1371 // Identity type conversion
1373 // Default reference comparison, it has to be used when comparing
1374 // two possible dynamic/internal types
1376 public static bool IsEqual (TypeSpec a, TypeSpec b)
1379 // This also rejects dynamic == dynamic
1380 return a.Kind != MemberKind.InternalCompilerType || a.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
1383 if (a == null || b == null)
1387 var a_a = (ArrayContainer) a;
1388 var b_a = b as ArrayContainer;
1392 return a_a.Rank == b_a.Rank && IsEqual (a_a.Element, b_a.Element);
1395 if (!a.IsGeneric || !b.IsGeneric) {
1397 // object and dynamic are considered equivalent there is an identity conversion
1398 // between object and dynamic, and between constructed types that are the same
1399 // when replacing all occurences of dynamic with object.
1401 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1402 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1407 if (a.MemberDefinition != b.MemberDefinition)
1411 if (!Equals (a.TypeArguments, b.TypeArguments))
1414 a = a.DeclaringType;
1415 b = b.DeclaringType;
1416 } while (a != null);
1422 public interface ITypeDefinition : IMemberDefinition
1424 IAssemblyDefinition DeclaringAssembly { get; }
1425 string Namespace { get; }
1426 bool IsPartial { get; }
1427 bool IsComImport { get; }
1428 bool IsTypeForwarder { get; }
1429 bool IsCyclicTypeForwarder { get; }
1430 int TypeParametersCount { get; }
1431 TypeParameterSpec[] TypeParameters { get; }
1433 TypeSpec GetAttributeCoClass ();
1434 string GetAttributeDefaultMember ();
1435 AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
1436 bool IsInternalAsPublic (IAssemblyDefinition assembly);
1437 void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache);
1440 class InternalType : TypeSpec, ITypeDefinition
1442 public static readonly InternalType AnonymousMethod = new InternalType ("anonymous method");
1443 public static readonly InternalType Arglist = new InternalType ("__arglist");
1444 public static readonly InternalType MethodGroup = new InternalType ("method group");
1445 public static readonly InternalType NullLiteral = new InternalType ("null");
1446 public static readonly InternalType FakeInternalType = new InternalType ("<fake$type>");
1447 public static readonly InternalType Namespace = new InternalType ("<namespace>");
1448 public static readonly InternalType ErrorType = new InternalType ("<error>");
1449 public static readonly InternalType VarOutType = new InternalType ("var out");
1451 readonly string name;
1453 InternalType (string name)
1454 : base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
1457 this.definition = this;
1458 cache = MemberCache.Empty;
1460 // Make all internal types CLS-compliant, non-obsolete
1461 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
1466 public override int Arity {
1472 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1474 throw new NotImplementedException ();
1478 bool ITypeDefinition.IsComImport {
1484 bool IMemberDefinition.IsImported {
1490 bool ITypeDefinition.IsPartial {
1496 bool ITypeDefinition.IsTypeForwarder {
1502 bool ITypeDefinition.IsCyclicTypeForwarder {
1508 public override string Name {
1514 string ITypeDefinition.Namespace {
1520 int ITypeDefinition.TypeParametersCount {
1526 TypeParameterSpec[] ITypeDefinition.TypeParameters {
1534 public override string GetSignatureForError ()
1539 #region ITypeDefinition Members
1541 TypeSpec ITypeDefinition.GetAttributeCoClass ()
1546 string ITypeDefinition.GetAttributeDefaultMember ()
1551 AttributeUsageAttribute ITypeDefinition.GetAttributeUsage (PredefinedAttribute pa)
1556 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1558 throw new NotImplementedException ();
1561 void ITypeDefinition.LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1563 throw new NotImplementedException ();
1566 string[] IMemberDefinition.ConditionalConditions ()
1571 ObsoleteAttribute IMemberDefinition.GetAttributeObsolete ()
1576 bool? IMemberDefinition.CLSAttributeValue {
1582 void IMemberDefinition.SetIsAssigned ()
1586 void IMemberDefinition.SetIsUsed ()
1594 // Common base class for composite types
1596 public abstract class ElementTypeSpec : TypeSpec, ITypeDefinition
1598 protected ElementTypeSpec (MemberKind kind, TypeSpec element, MetaType info)
1599 : base (kind, element.DeclaringType, null, info, element.Modifiers)
1601 this.Element = element;
1603 state &= ~SharedStateFlags;
1604 state |= (element.state & SharedStateFlags);
1606 if (element.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1607 state |= StateFlags.HasDynamicElement;
1609 // Has to use its own type definition instead of just element definition to
1610 // correctly identify itself for cases like x.MemberDefininition == predefined.MemberDefinition
1611 this.definition = this;
1613 cache = MemberCache.Empty;
1618 public TypeSpec Element { get; private set; }
1620 bool ITypeDefinition.IsComImport {
1626 bool ITypeDefinition.IsPartial {
1632 bool ITypeDefinition.IsTypeForwarder {
1638 bool ITypeDefinition.IsCyclicTypeForwarder {
1644 public override string Name {
1646 throw new NotSupportedException ();
1652 public override ObsoleteAttribute GetAttributeObsolete ()
1654 return Element.GetAttributeObsolete ();
1657 protected virtual string GetPostfixSignature ()
1662 public override string GetSignatureForDocumentation ()
1664 return Element.GetSignatureForDocumentation () + GetPostfixSignature ();
1667 public override string GetSignatureForError ()
1669 return Element.GetSignatureForError () + GetPostfixSignature ();
1672 public override TypeSpec Mutate (TypeParameterMutator mutator)
1674 var me = Element.Mutate (mutator);
1678 var mutated = (ElementTypeSpec) MemberwiseClone ();
1679 mutated.Element = me;
1680 mutated.info = null;
1684 #region ITypeDefinition Members
1686 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1688 return Element.MemberDefinition.DeclaringAssembly;
1692 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1694 return Element.MemberDefinition.IsInternalAsPublic (assembly);
1697 public string Namespace {
1698 get { throw new NotImplementedException (); }
1701 public int TypeParametersCount {
1707 public TypeParameterSpec[] TypeParameters {
1709 throw new NotSupportedException ();
1713 public TypeSpec GetAttributeCoClass ()
1715 return Element.MemberDefinition.GetAttributeCoClass ();
1718 public string GetAttributeDefaultMember ()
1720 return Element.MemberDefinition.GetAttributeDefaultMember ();
1723 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1725 Element.MemberDefinition.LoadMembers (declaringType, onlyTypes, ref cache);
1728 public bool IsImported {
1730 return Element.MemberDefinition.IsImported;
1734 public string[] ConditionalConditions ()
1736 return Element.MemberDefinition.ConditionalConditions ();
1739 bool? IMemberDefinition.CLSAttributeValue {
1741 return Element.MemberDefinition.CLSAttributeValue;
1745 public void SetIsAssigned ()
1747 Element.MemberDefinition.SetIsAssigned ();
1750 public void SetIsUsed ()
1752 Element.MemberDefinition.SetIsUsed ();
1758 public class ArrayContainer : ElementTypeSpec
1760 public struct TypeRankPair : IEquatable<TypeRankPair>
1765 public TypeRankPair (TypeSpec ts, int rank)
1771 public override int GetHashCode ()
1773 return ts.GetHashCode () ^ rank.GetHashCode ();
1776 #region IEquatable<Tuple<T1,T2>> Members
1778 public bool Equals (TypeRankPair other)
1780 return other.ts == ts && other.rank == rank;
1787 readonly ModuleContainer module;
1789 private ArrayContainer (ModuleContainer module, TypeSpec element, int rank)
1790 : base (MemberKind.ArrayType, element, null)
1792 this.module = module;
1802 public MethodInfo GetConstructor ()
1804 var mb = module.Builder;
1806 var arg_types = new MetaType[rank];
1807 for (int i = 0; i < rank; i++)
1808 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1810 var ctor = mb.GetArrayMethod (
1811 GetMetaInfo (), Constructor.ConstructorName,
1812 CallingConventions.HasThis,
1818 public MethodInfo GetAddressMethod ()
1820 var mb = module.Builder;
1822 var arg_types = new MetaType[rank];
1823 for (int i = 0; i < rank; i++)
1824 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1826 var address = mb.GetArrayMethod (
1827 GetMetaInfo (), "Address",
1828 CallingConventions.HasThis | CallingConventions.Standard,
1829 ReferenceContainer.MakeType (module, Element).GetMetaInfo (), arg_types);
1834 public MethodInfo GetGetMethod ()
1836 var mb = module.Builder;
1838 var arg_types = new MetaType[rank];
1839 for (int i = 0; i < rank; i++)
1840 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1842 var get = mb.GetArrayMethod (
1843 GetMetaInfo (), "Get",
1844 CallingConventions.HasThis | CallingConventions.Standard,
1845 Element.GetMetaInfo (), arg_types);
1850 public MethodInfo GetSetMethod ()
1852 var mb = module.Builder;
1854 var arg_types = new MetaType[rank + 1];
1855 for (int i = 0; i < rank; i++)
1856 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1858 arg_types[rank] = Element.GetMetaInfo ();
1860 var set = mb.GetArrayMethod (
1861 GetMetaInfo (), "Set",
1862 CallingConventions.HasThis | CallingConventions.Standard,
1863 module.Compiler.BuiltinTypes.Void.GetMetaInfo (), arg_types);
1868 public override MetaType GetMetaInfo ()
1872 info = Element.GetMetaInfo ().MakeArrayType ();
1874 info = Element.GetMetaInfo ().MakeArrayType (rank);
1880 protected override string GetPostfixSignature()
1882 return GetPostfixSignature (rank);
1885 public static string GetPostfixSignature (int rank)
1887 StringBuilder sb = new StringBuilder ();
1889 for (int i = 1; i < rank; i++) {
1894 return sb.ToString ();
1897 public override string GetSignatureForDocumentation ()
1899 StringBuilder sb = new StringBuilder ();
1900 GetElementSignatureForDocumentation (sb);
1901 return sb.ToString ();
1904 void GetElementSignatureForDocumentation (StringBuilder sb)
1906 var ac = Element as ArrayContainer;
1908 sb.Append (Element.GetSignatureForDocumentation ());
1910 ac.GetElementSignatureForDocumentation (sb);
1913 for (int i = 1; i < rank; i++) {
1922 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element)
1924 return MakeType (module, element, 1);
1927 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element, int rank)
1930 var key = new TypeRankPair (element, rank);
1931 if (!module.ArrayTypesCache.TryGetValue (key, out ac)) {
1932 ac = new ArrayContainer (module, element, rank);
1933 ac.BaseType = module.Compiler.BuiltinTypes.Array;
1934 ac.Interfaces = ac.BaseType.Interfaces;
1936 module.ArrayTypesCache.Add (key, ac);
1942 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1944 return Element.ResolveMissingDependencies (caller);
1948 class ReferenceContainer : ElementTypeSpec
1950 private ReferenceContainer (TypeSpec element)
1951 : base (MemberKind.Class, element, null) // TODO: Kind.Class is most likely wrong
1955 public override MetaType GetMetaInfo ()
1958 info = Element.GetMetaInfo ().MakeByRefType ();
1964 public static ReferenceContainer MakeType (ModuleContainer module, TypeSpec element)
1966 ReferenceContainer pc;
1967 if (!module.ReferenceTypesCache.TryGetValue (element, out pc)) {
1968 pc = new ReferenceContainer (element);
1969 module.ReferenceTypesCache.Add (element, pc);
1976 class PointerContainer : ElementTypeSpec
1978 private PointerContainer (TypeSpec element)
1979 : base (MemberKind.PointerType, element, null)
1981 // It's never CLS-Compliant
1982 state &= ~StateFlags.CLSCompliant_Undetected;
1985 public override MetaType GetMetaInfo ()
1988 info = Element.GetMetaInfo ().MakePointerType ();
1994 protected override string GetPostfixSignature()
1999 public static PointerContainer MakeType (ModuleContainer module, TypeSpec element)
2001 PointerContainer pc;
2002 if (!module.PointerTypesCache.TryGetValue (element, out pc)) {
2003 pc = new PointerContainer (element);
2004 module.PointerTypesCache.Add (element, pc);
2011 public class MissingTypeSpecReference
2013 public MissingTypeSpecReference (TypeSpec type, MemberSpec caller)
2019 public TypeSpec Type { get; private set; }
2020 public MemberSpec Caller { get; private set; }