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;
95 public bool HasNamedTupleElement {
97 return (state & StateFlags.HasNamedTupleElement) != 0;
102 // Returns a list of all interfaces including
103 // interfaces from base type or base interfaces
105 public virtual IList<TypeSpec> Interfaces {
107 if ((state & StateFlags.InterfacesImported) == 0) {
108 state |= StateFlags.InterfacesImported;
111 // Delay interfaces expansion to save memory and once all
112 // base types has been imported to avoid problems where
113 // interface references type before its base was imported
115 var imported = MemberDefinition as ImportedTypeDefinition;
116 if (imported != null && Kind != MemberKind.MissingType)
117 imported.DefineInterfaces (this);
127 public bool IsArray {
129 return Kind == MemberKind.ArrayType;
133 public bool IsAttribute {
140 if (type.BuiltinType == BuiltinTypeSpec.Type.Attribute)
146 type = type.base_type;
147 } while (type != null);
153 public bool IsInterface {
155 return Kind == MemberKind.Interface;
159 public bool IsClass {
161 return Kind == MemberKind.Class;
165 public bool IsConstantCompatible {
167 if ((Kind & (MemberKind.Enum | MemberKind.Class | MemberKind.Interface | MemberKind.Delegate | MemberKind.ArrayType)) != 0)
170 switch (BuiltinType) {
171 case BuiltinTypeSpec.Type.Int:
172 case BuiltinTypeSpec.Type.UInt:
173 case BuiltinTypeSpec.Type.Long:
174 case BuiltinTypeSpec.Type.ULong:
175 case BuiltinTypeSpec.Type.Float:
176 case BuiltinTypeSpec.Type.Double:
177 case BuiltinTypeSpec.Type.Char:
178 case BuiltinTypeSpec.Type.Short:
179 case BuiltinTypeSpec.Type.Decimal:
180 case BuiltinTypeSpec.Type.Bool:
181 case BuiltinTypeSpec.Type.SByte:
182 case BuiltinTypeSpec.Type.Byte:
183 case BuiltinTypeSpec.Type.UShort:
184 case BuiltinTypeSpec.Type.Dynamic:
192 public bool IsDelegate {
194 return Kind == MemberKind.Delegate;
199 // Returns true for instances of Expression<T>
201 public virtual bool IsExpressionTreeType {
206 state = value ? state | StateFlags.InflatedExpressionType : state & ~StateFlags.InflatedExpressionType;
212 return Kind == MemberKind.Enum;
217 // Returns true for instances of IList<T>, IEnumerable<T>, ICollection<T>
219 public virtual bool IsArrayGenericInterface {
224 state = value ? state | StateFlags.GenericIterateInterface : state & ~StateFlags.GenericIterateInterface;
229 // Returns true for instances of System.Threading.Tasks.Task<T>
231 public virtual bool IsGenericTask {
236 state = value ? state | StateFlags.GenericTask : state & ~StateFlags.GenericTask;
241 // Returns true for instances of any System.ValueTuple<......> type
243 public virtual bool IsTupleType {
245 return (state & StateFlags.Tuple) != 0;
248 state = value ? state | StateFlags.Tuple : state & ~StateFlags.Tuple;
252 // TODO: Should probably do
253 // IsGenericType -- recursive
254 // HasTypeParameter -- non-recursive
255 public bool IsGenericOrParentIsGeneric {
261 ts = ts.declaringType;
262 } while (ts != null);
268 public bool IsGenericParameter {
270 return Kind == MemberKind.TypeParameter;
275 // Returns true for instances of Nullable<T>
277 public virtual bool IsNullableType {
282 state = value ? state | StateFlags.InflatedNullableType : state & ~StateFlags.InflatedNullableType;
286 public bool IsNested {
287 get { return declaringType != null && Kind != MemberKind.TypeParameter; }
290 public bool IsPointer {
292 return Kind == MemberKind.PointerType;
296 public bool IsSealed {
297 get { return (Modifiers & Modifiers.SEALED) != 0; }
300 public bool IsSpecialRuntimeType {
302 return (state & StateFlags.SpecialRuntimeType) != 0;
305 state = value ? state | StateFlags.SpecialRuntimeType : state & ~StateFlags.SpecialRuntimeType;
309 public bool IsStruct {
311 return Kind == MemberKind.Struct;
315 public bool IsStructOrEnum {
317 return (Kind & (MemberKind.Struct | MemberKind.Enum)) != 0;
321 public bool IsTypeBuilder {
326 var meta = GetMetaInfo().GetType ();
327 return meta == TypeBuilder || meta == GenericTypeBuilder;
333 // Whether a type is unmanaged. This is used by the unsafe code
335 public bool IsUnmanaged {
338 return ((ElementTypeSpec) this).Element.IsUnmanaged;
340 var ds = MemberDefinition as TypeDefinition;
342 return ds.IsUnmanagedType ();
344 if (Kind == MemberKind.Void)
347 if (Kind == MemberKind.TypeParameter)
350 if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
353 return IsValueType (this);
358 // A cache of all type members (including nested types)
360 public MemberCache MemberCache {
362 if (cache == null || (state & StateFlags.PendingMemberCacheMembers) != 0)
363 InitializeMemberCache (false);
369 throw new InternalErrorException ("Membercache reset");
375 public MemberCache MemberCacheTypes {
378 InitializeMemberCache (true);
384 public new ITypeDefinition MemberDefinition {
386 return (ITypeDefinition) definition;
390 // TODO: Wouldn't be better to rely on cast to InflatedTypeSpec and
391 // remove the property, YES IT WOULD !!!
392 public virtual TypeSpec[] TypeArguments {
393 get { return TypeSpec.EmptyTypes; }
398 public virtual bool AddInterface (TypeSpec iface)
400 if ((state & StateFlags.InterfacesExpanded) != 0)
401 throw new InternalErrorException ("Modifying expanded interface list");
403 if (ifaces == null) {
404 ifaces = new List<TypeSpec> { iface };
408 if (!ifaces.Contains (iface)) {
417 // Special version used during type definition
419 public bool AddInterfaceDefined (TypeSpec iface)
421 if (!AddInterface (iface))
425 // We can get into a situation where a type is inflated before
426 // its interfaces are resoved. Consider this situation
428 // class A<T> : X<A<int>>, IFoo {}
430 // When resolving base class of X`1 we inflate context type A`1
431 // All this happens before we even hit IFoo resolve. Without
432 // additional expansion any inside usage of A<T> would miss IFoo
433 // interface because it comes from early inflated A`1 definition.
435 if (inflated_instances != null) {
437 // Inflate only existing instances not any new instances added
438 // during AddInterface
440 var inflated_existing = inflated_instances.Values.ToArray ();
441 foreach (var inflated in inflated_existing) {
442 inflated.AddInterface (iface);
450 // Returns all type arguments, usefull for nested types
452 public static TypeSpec[] GetAllTypeArguments (TypeSpec type)
454 IList<TypeSpec> targs = TypeSpec.EmptyTypes;
457 if (type.Arity > 0) {
458 if (targs.Count == 0) {
459 targs = type.TypeArguments;
461 var list = targs as List<TypeSpec> ?? new List<TypeSpec> (targs);
462 list.AddRange (type.TypeArguments);
467 type = type.declaringType;
468 } while (type != null);
470 return targs as TypeSpec[] ?? ((List<TypeSpec>) targs).ToArray ();
473 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
475 if (Kind != MemberKind.Class)
476 throw new InternalErrorException ();
479 return Attribute.DefaultUsageAttribute;
481 AttributeUsageAttribute aua = null;
483 while (type != null) {
484 aua = type.MemberDefinition.GetAttributeUsage (pa);
488 type = type.BaseType;
495 // Return metadata information used during emit to describe the type
497 public virtual MetaType GetMetaInfo ()
502 public virtual TypeSpec GetDefinition ()
508 // Text representation of type used by documentation writer
510 public sealed override string GetSignatureForDocumentation ()
512 return GetSignatureForDocumentation (false);
515 public virtual string GetSignatureForDocumentation (bool explicitName)
517 StringBuilder sb = new StringBuilder ();
519 sb.Append (DeclaringType.GetSignatureForDocumentation (explicitName));
520 } else if (MemberDefinition.Namespace != null) {
521 sb.Append (explicitName ? MemberDefinition.Namespace.Replace ('.', '#') : MemberDefinition.Namespace);
525 sb.Append (explicitName ? "#" : ".");
529 if (this is InflatedTypeSpec) {
531 for (int i = 0; i < Arity; ++i) {
535 sb.Append (TypeArguments[i].GetSignatureForDocumentation (explicitName));
540 sb.Append (Arity.ToString ());
544 return sb.ToString ();
547 public override string GetSignatureForError ()
552 s = DeclaringType.GetSignatureForError ();
553 } else if (MemberDefinition is AnonymousTypeClass) {
554 return ((AnonymousTypeClass)MemberDefinition).GetSignatureForError ();
555 } else if (IsTupleType) {
556 return FormatTupleSignature ();
558 s = MemberDefinition.Namespace;
561 if (!string.IsNullOrEmpty (s))
564 return s + Name + GetTypeNameSignature ();
567 string FormatTupleSignature ()
569 var sb = new StringBuilder ();
571 for (int i = 0; i < TypeArguments.Length; ++i) {
575 sb.Append (TypeArguments[i].GetSignatureForError ());
579 return sb.ToString ();
582 public string GetSignatureForErrorIncludingAssemblyName ()
584 var imported = MemberDefinition.DeclaringAssembly as ImportedAssemblyDefinition;
586 var location = imported != null ?
587 System.IO.Path.GetFullPath (imported.Location) :
588 ((MemberCore)MemberDefinition).Location.NameFullPath;
590 return string.Format ("{0} [{1} -- {2}]", GetSignatureForError (),
591 MemberDefinition.DeclaringAssembly.FullName,
595 protected virtual string GetTypeNameSignature ()
600 return "<" + TypeManager.CSharpName (MemberDefinition.TypeParameters) + ">";
603 public bool ImplementsInterface (TypeSpec iface, bool variantly)
605 var ifaces = Interfaces;
606 if (ifaces != null) {
607 for (int i = 0; i < ifaces.Count; ++i) {
608 if (TypeSpecComparer.IsEqual (ifaces[i], iface))
611 if (variantly && TypeSpecComparer.Variant.IsEqual (ifaces[i], iface))
619 protected virtual void InitializeMemberCache (bool onlyTypes)
622 MemberDefinition.LoadMembers (this, onlyTypes, ref cache);
623 } catch (Exception e) {
624 throw new InternalErrorException (e, "Unexpected error when loading type `{0}'", GetSignatureForError ());
628 state |= StateFlags.PendingMemberCacheMembers;
630 state &= ~StateFlags.PendingMemberCacheMembers;
634 // Is @baseClass base implementation of @type. With enabled @dynamicIsEqual the slower
635 // comparison is used to hide differences between `object' and `dynamic' for generic
636 // types. Should not be used for comparisons where G<object> != G<dynamic>
638 public static bool IsBaseClass (TypeSpec type, TypeSpec baseClass, bool dynamicIsObject)
640 if (dynamicIsObject && baseClass.IsGeneric) {
642 // Returns true for a hierarchies like this when passing baseClass of A<dynamic>
644 // class B : A<object> {}
646 type = type.BaseType;
647 while (type != null) {
648 if (TypeSpecComparer.IsEqual (type, baseClass))
651 type = type.BaseType;
657 while (type != null) {
658 type = type.BaseType;
659 if (type == baseClass)
666 public static bool IsReferenceType (TypeSpec t)
669 case MemberKind.TypeParameter:
670 return ((TypeParameterSpec) t).IsReferenceType;
671 case MemberKind.Struct:
672 case MemberKind.Enum:
673 case MemberKind.Void:
674 case MemberKind.PointerType:
676 case MemberKind.InternalCompilerType:
678 // Null is considered to be a reference type
680 return t == InternalType.NullLiteral || t.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
686 public static bool IsNonNullableValueType (TypeSpec t)
689 case MemberKind.TypeParameter:
690 return ((TypeParameterSpec) t).IsValueType;
691 case MemberKind.Struct:
692 return !t.IsNullableType;
693 case MemberKind.Enum:
700 public static bool IsValueType (TypeSpec t)
703 case MemberKind.TypeParameter:
704 return ((TypeParameterSpec) t).IsValueType;
705 case MemberKind.Struct:
706 case MemberKind.Enum:
713 public override MemberSpec InflateMember (TypeParameterInflator inflator)
715 var targs = IsGeneric ? MemberDefinition.TypeParameters : TypeSpec.EmptyTypes;
718 // When inflating nested type from inside the type instance will be same
719 // because type parameters are same for all nested types
721 if (DeclaringType == inflator.TypeInstance) {
722 return MakeGenericType (inflator.Context, targs);
725 return new InflatedTypeSpec (inflator.Context, this, inflator.TypeInstance, targs);
729 // Inflates current type using specific type arguments
731 public InflatedTypeSpec MakeGenericType (IModuleContext context, TypeSpec[] targs)
733 if (targs.Length == 0 && !IsNested)
734 throw new ArgumentException ("Empty type arguments for type " + GetSignatureForError ());
736 InflatedTypeSpec instance;
738 if (inflated_instances == null) {
739 inflated_instances = new Dictionary<TypeSpec[], InflatedTypeSpec> (TypeSpecComparer.Default);
742 instance = this as InflatedTypeSpec;
743 if (instance != null) {
745 // Nested types could be inflated on already inflated instances
746 // Caching this type ensured we are using same instance for
747 // inside/outside inflation using local type parameters
749 inflated_instances.Add (TypeArguments, instance);
754 if (!inflated_instances.TryGetValue (targs, out instance)) {
755 if (GetDefinition () != this && !IsNested)
756 throw new InternalErrorException ("`{0}' must be type definition or nested non-inflated type to MakeGenericType",
757 GetSignatureForError ());
759 instance = new InflatedTypeSpec (context, this, declaringType, targs);
760 inflated_instances.Add (targs, instance);
766 public virtual TypeSpec Mutate (TypeParameterMutator mutator)
771 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
773 List<MissingTypeSpecReference> missing = null;
775 if (Kind == MemberKind.MissingType) {
776 missing = new List<MissingTypeSpecReference> ();
777 missing.Add (new MissingTypeSpecReference (this, caller));
781 foreach (var targ in TypeArguments) {
782 if (targ.Kind == MemberKind.MissingType) {
784 missing = new List<MissingTypeSpecReference> ();
786 missing.Add (new MissingTypeSpecReference (targ, caller));
790 if (Interfaces != null) {
791 foreach (var iface in Interfaces) {
792 if (iface.Kind == MemberKind.MissingType) {
794 missing = new List<MissingTypeSpecReference> ();
796 missing.Add (new MissingTypeSpecReference (iface, caller));
801 if (MemberDefinition.TypeParametersCount > 0) {
802 foreach (var tp in MemberDefinition.TypeParameters) {
803 var tp_missing = tp.GetMissingDependencies (this);
804 if (tp_missing != null) {
806 missing = new List<MissingTypeSpecReference> ();
808 missing.AddRange (tp_missing);
813 if (missing != null || BaseType == null)
816 return BaseType.ResolveMissingDependencies (this);
819 public void SetMetaInfo (MetaType info)
821 if (this.info != null)
822 throw new InternalErrorException ("MetaInfo reset");
827 public void SetExtensionMethodContainer ()
829 modifiers |= Modifiers.METHOD_EXTENSION;
832 public void UpdateInflatedInstancesBaseType ()
835 // When nested class has a partial part the situation where parent type
836 // is inflated before its base type is defined can occur. In such case
837 // all inflated (should be only 1) instansted need to be updated
839 // partial class A<T> {
840 // partial class B : A<int> { }
843 // partial class A<T> : X {}
845 if (inflated_instances == null)
848 foreach (var inflated in inflated_instances) {
850 // Don't need to inflate possible generic type because for now the method
851 // is always used from within the nested type
853 inflated.Value.BaseType = base_type;
859 // Special version used for types which must exist in corlib or
860 // the compiler cannot work
862 public sealed class BuiltinTypeSpec : TypeSpec
868 // Ordered carefully for fast compares
896 MulticastDelegate = 23,
909 readonly string name;
911 public BuiltinTypeSpec (MemberKind kind, string ns, string name, Type builtinKind)
912 : base (kind, null, null, null, Modifiers.PUBLIC)
914 this.type = builtinKind;
919 public BuiltinTypeSpec (string name, Type builtinKind)
920 : this (MemberKind.InternalCompilerType, "", name, builtinKind)
922 // Make all internal types CLS-compliant, non-obsolete, compact
923 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
928 public override int Arity {
934 public override BuiltinTypeSpec.Type BuiltinType {
940 public string FullName {
942 return ns + '.' + name;
946 public override string Name {
952 public string Namespace {
960 public static bool IsPrimitiveType (TypeSpec type)
962 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.LastPrimitive;
965 public static bool IsPrimitiveTypeOrDecimal (TypeSpec type)
967 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.Decimal;
970 public override string GetSignatureForError ()
973 case "Int32": return "int";
974 case "Int64": return "long";
975 case "String": return "string";
976 case "Boolean": return "bool";
977 case "Void": return "void";
978 case "Object": return "object";
979 case "UInt32": return "uint";
980 case "Int16": return "short";
981 case "UInt16": return "ushort";
982 case "UInt64": return "ulong";
983 case "Single": return "float";
984 case "Double": return "double";
985 case "Decimal": return "decimal";
986 case "Char": return "char";
987 case "Byte": return "byte";
988 case "SByte": return "sbyte";
998 // Returns the size of type if known, otherwise, 0
1000 public static int GetSize (TypeSpec type)
1002 switch (type.BuiltinType) {
1026 public void SetDefinition (ITypeDefinition td, MetaType type, Modifiers mod)
1028 this.definition = td;
1030 this.modifiers |= (mod & ~Modifiers.AccessibilityMask);
1033 public void SetDefinition (TypeSpec ts)
1035 this.definition = ts.MemberDefinition;
1036 this.info = ts.GetMetaInfo ();
1037 this.BaseType = ts.BaseType;
1038 this.Interfaces = ts.Interfaces;
1039 this.modifiers = ts.Modifiers;
1044 // Various type comparers used by compiler
1046 static class TypeSpecComparer
1049 // Does strict reference comparion only
1051 public static readonly DefaultImpl Default = new DefaultImpl ();
1053 public class DefaultImpl : IEqualityComparer<TypeSpec[]>
1055 #region IEqualityComparer<TypeSpec[]> Members
1057 bool IEqualityComparer<TypeSpec[]>.Equals (TypeSpec[] x, TypeSpec[] y)
1062 if (x.Length != y.Length)
1065 for (int i = 0; i < x.Length; ++i)
1072 int IEqualityComparer<TypeSpec[]>.GetHashCode (TypeSpec[] obj)
1075 for (int i = 0; i < obj.Length; ++i)
1076 hash = (hash << 5) - hash + obj[i].GetHashCode ();
1085 // When comparing type signature of overrides or overloads
1086 // this version tolerates different MVARs at same position
1088 public static class Override
1090 public static bool IsEqual (TypeSpec a, TypeSpec b)
1096 // Consider the following example:
1098 // public abstract class A
1100 // public abstract T Foo<T>();
1103 // public class B : A
1105 // public override U Foo<T>() { return default (U); }
1108 // Here, `T' and `U' are method type parameters from different methods
1109 // (A.Foo and B.Foo), so both `==' and Equals() will fail.
1111 // However, since we're determining whether B.Foo() overrides A.Foo(),
1112 // we need to do a signature based comparision and consider them equal.
1115 var tp_a = a as TypeParameterSpec;
1117 var tp_b = b as TypeParameterSpec;
1118 return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
1121 var ac_a = a as ArrayContainer;
1123 var ac_b = b as ArrayContainer;
1124 return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
1127 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1128 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1130 if (a.MemberDefinition != b.MemberDefinition)
1134 for (int i = 0; i < a.TypeArguments.Length; ++i) {
1135 if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
1139 a = a.DeclaringType;
1140 b = b.DeclaringType;
1141 } while (a != null);
1146 public static bool IsEqual (TypeSpec[] a, TypeSpec[] b)
1151 if (a.Length != b.Length)
1154 for (int i = 0; i < a.Length; ++i) {
1155 if (!IsEqual (a[i], b[i]))
1164 // Compares unordered arrays
1166 public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
1171 if (a == null || b == null || a.Length != b.Length)
1174 for (int ai = 0; ai < a.Length; ++ai) {
1176 for (int bi = 0; bi < b.Length; ++bi) {
1177 if (IsEqual (a[ai], b[bi])) {
1190 public static bool IsEqual (AParametersCollection a, AParametersCollection b)
1195 if (a.Count != b.Count)
1198 for (int i = 0; i < a.Count; ++i) {
1199 if (!IsEqual (a.Types[i], b.Types[i]))
1202 if ((a.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (b.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask))
1211 // Type variance equality comparison
1213 public static class Variant
1215 public static bool IsEqual (TypeSpec type1, TypeSpec type2)
1217 if (!type1.IsGeneric || !type2.IsGeneric)
1220 var target_type_def = type2.MemberDefinition;
1221 if (type1.MemberDefinition != target_type_def)
1224 var t1_targs = type1.TypeArguments;
1225 var t2_targs = type2.TypeArguments;
1226 var targs_definition = target_type_def.TypeParameters;
1228 if (!type1.IsInterface && !type1.IsDelegate) {
1232 for (int i = 0; i < targs_definition.Length; ++i) {
1233 if (TypeSpecComparer.IsEqual (t1_targs[i], t2_targs[i]))
1236 Variance v = targs_definition[i].Variance;
1237 if (v == Variance.None) {
1241 if (v == Variance.Covariant) {
1242 if (!Convert.ImplicitReferenceConversionExists (t1_targs[i], t2_targs[i]))
1244 } else if (!Convert.ImplicitReferenceConversionExists (t2_targs[i], t1_targs[i])) {
1254 // Checks whether two generic instances may become equal for some
1255 // particular instantiation (26.3.1).
1257 public static class Unify
1260 // Either @a or @b must be generic type
1262 public static bool IsEqual (TypeSpec a, TypeSpec b)
1264 if (a.MemberDefinition != b.MemberDefinition) {
1265 var base_ifaces = a.Interfaces;
1266 if (base_ifaces != null) {
1267 foreach (var base_iface in base_ifaces) {
1268 if (base_iface.Arity > 0 && IsEqual (base_iface, b))
1276 var ta = a.TypeArguments;
1277 var tb = b.TypeArguments;
1278 for (int i = 0; i < ta.Length; i++) {
1279 if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
1283 if (a.IsNested && b.IsNested)
1284 return IsEqual (a.DeclaringType, b.DeclaringType);
1289 static bool ContainsTypeParameter (TypeSpec tparam, TypeSpec type)
1291 TypeSpec[] targs = type.TypeArguments;
1292 for (int i = 0; i < targs.Length; i++) {
1293 if (tparam == targs[i])
1296 if (ContainsTypeParameter (tparam, targs[i]))
1304 /// Check whether `a' and `b' may become equal generic types.
1305 /// The algorithm to do that is a little bit complicated.
1307 static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
1309 if (a.IsGenericParameter) {
1311 // If a is an array of a's type, they may never
1318 // If b is a generic parameter or an actual type,
1319 // they may become equal:
1321 // class X<T,U> : I<T>, I<U>
1322 // class X<T> : I<T>, I<float>
1324 if (b.IsGenericParameter)
1325 return a != b && a.DeclaringType == b.DeclaringType;
1328 // We're now comparing a type parameter with a
1329 // generic instance. They may become equal unless
1330 // the type parameter appears anywhere in the
1331 // generic instance:
1333 // class X<T,U> : I<T>, I<X<U>>
1334 // -> error because you could instanciate it as
1337 // class X<T> : I<T>, I<X<T>> -> ok
1340 return !ContainsTypeParameter (a, b);
1343 if (b.IsGenericParameter)
1344 return MayBecomeEqualGenericTypes (b, a);
1347 // At this point, neither a nor b are a type parameter.
1349 // If one of them is a generic instance, compare them (if the
1350 // other one is not a generic instance, they can never
1353 if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
1354 return IsEqual (a, b);
1357 // If both of them are arrays.
1359 var a_ac = a as ArrayContainer;
1361 var b_ac = b as ArrayContainer;
1362 if (b_ac == null || a_ac.Rank != b_ac.Rank)
1365 return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
1369 // Ok, two ordinary types.
1375 public static bool Equals (TypeSpec[] x, TypeSpec[] y)
1380 if (x.Length != y.Length)
1383 for (int i = 0; i < x.Length; ++i)
1384 if (!IsEqual (x[i], y[i]))
1391 // Identity type conversion
1393 // Default reference comparison, it has to be used when comparing
1394 // two possible dynamic/internal types
1396 public static bool IsEqual (TypeSpec a, TypeSpec b)
1399 // This also rejects dynamic == dynamic
1400 return a.Kind != MemberKind.InternalCompilerType || a.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
1403 if (a == null || b == null)
1407 var a_a = (ArrayContainer) a;
1408 var b_a = b as ArrayContainer;
1412 return a_a.Rank == b_a.Rank && IsEqual (a_a.Element, b_a.Element);
1415 if (!a.IsGeneric || !b.IsGeneric) {
1417 // object and dynamic are considered equivalent there is an identity conversion
1418 // between object and dynamic, and between constructed types that are the same
1419 // when replacing all occurences of dynamic with object.
1421 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1422 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1427 if (a.MemberDefinition != b.MemberDefinition)
1431 if (!Equals (a.TypeArguments, b.TypeArguments))
1434 a = a.DeclaringType;
1435 b = b.DeclaringType;
1436 } while (a != null);
1442 public interface ITypeDefinition : IMemberDefinition
1444 IAssemblyDefinition DeclaringAssembly { get; }
1445 string Namespace { get; }
1446 bool IsPartial { get; }
1447 bool IsComImport { get; }
1448 bool IsTypeForwarder { get; }
1449 bool IsCyclicTypeForwarder { get; }
1450 int TypeParametersCount { get; }
1451 TypeParameterSpec[] TypeParameters { get; }
1453 TypeSpec GetAttributeCoClass ();
1454 string GetAttributeDefaultMember ();
1455 AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
1456 bool IsInternalAsPublic (IAssemblyDefinition assembly);
1457 void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache);
1460 class InternalType : TypeSpec, ITypeDefinition
1462 public static readonly InternalType AnonymousMethod = new InternalType ("anonymous method");
1463 public static readonly InternalType Arglist = new InternalType ("__arglist");
1464 public static readonly InternalType MethodGroup = new InternalType ("method group");
1465 public static readonly InternalType NullLiteral = new InternalType ("null");
1466 public static readonly InternalType FakeInternalType = new InternalType ("<fake$type>");
1467 public static readonly InternalType Namespace = new InternalType ("<namespace>");
1468 public static readonly InternalType ErrorType = new InternalType ("<error>");
1469 public static readonly InternalType VarOutType = new InternalType ("var out");
1470 public static readonly InternalType ThrowExpr = new InternalType ("throw expression");
1472 readonly string name;
1474 InternalType (string name)
1475 : base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
1478 this.definition = this;
1479 cache = MemberCache.Empty;
1481 // Make all internal types CLS-compliant, non-obsolete
1482 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
1487 public override int Arity {
1493 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1495 throw new NotImplementedException ();
1499 bool ITypeDefinition.IsComImport {
1505 bool IMemberDefinition.IsImported {
1511 bool ITypeDefinition.IsPartial {
1517 bool ITypeDefinition.IsTypeForwarder {
1523 bool ITypeDefinition.IsCyclicTypeForwarder {
1529 public override string Name {
1535 string ITypeDefinition.Namespace {
1541 int ITypeDefinition.TypeParametersCount {
1547 TypeParameterSpec[] ITypeDefinition.TypeParameters {
1555 public override string GetSignatureForError ()
1560 #region ITypeDefinition Members
1562 TypeSpec ITypeDefinition.GetAttributeCoClass ()
1567 string ITypeDefinition.GetAttributeDefaultMember ()
1572 AttributeUsageAttribute ITypeDefinition.GetAttributeUsage (PredefinedAttribute pa)
1577 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1579 throw new NotImplementedException ();
1582 void ITypeDefinition.LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1584 throw new NotImplementedException ();
1587 string[] IMemberDefinition.ConditionalConditions ()
1592 ObsoleteAttribute IMemberDefinition.GetAttributeObsolete ()
1597 bool? IMemberDefinition.CLSAttributeValue {
1603 void IMemberDefinition.SetIsAssigned ()
1607 void IMemberDefinition.SetIsUsed ()
1613 public static bool HasNoType (TypeSpec type)
1615 return type == AnonymousMethod || type == MethodGroup || type == NullLiteral || type == ThrowExpr;
1620 // Common base class for composite types
1622 public abstract class ElementTypeSpec : TypeSpec, ITypeDefinition
1624 protected ElementTypeSpec (MemberKind kind, TypeSpec element, MetaType info)
1625 : base (kind, element.DeclaringType, null, info, element.Modifiers)
1627 this.Element = element;
1629 state &= ~SharedStateFlags;
1630 state |= (element.state & SharedStateFlags);
1632 if (element.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1633 state |= StateFlags.HasDynamicElement;
1635 // Has to use its own type definition instead of just element definition to
1636 // correctly identify itself for cases like x.MemberDefininition == predefined.MemberDefinition
1637 this.definition = this;
1639 cache = MemberCache.Empty;
1644 public TypeSpec Element { get; private set; }
1646 public override IList<TypeSpec> Interfaces {
1648 throw new NotSupportedException ();
1652 bool ITypeDefinition.IsComImport {
1658 bool ITypeDefinition.IsPartial {
1664 bool ITypeDefinition.IsTypeForwarder {
1670 bool ITypeDefinition.IsCyclicTypeForwarder {
1676 public override string Name {
1678 throw new NotSupportedException ();
1684 public override void CheckObsoleteness (IMemberContext mc, Location loc)
1686 Element.CheckObsoleteness (mc, loc);
1689 public override ObsoleteAttribute GetAttributeObsolete ()
1691 return Element.GetAttributeObsolete ();
1694 protected virtual string GetPostfixSignature ()
1699 public override string GetSignatureForDocumentation (bool explicitName)
1701 return Element.GetSignatureForDocumentation (explicitName) + GetPostfixSignature ();
1704 public override string GetSignatureForError ()
1706 return Element.GetSignatureForError () + GetPostfixSignature ();
1709 public override TypeSpec Mutate (TypeParameterMutator mutator)
1711 var me = Element.Mutate (mutator);
1715 var mutated = (ElementTypeSpec) MemberwiseClone ();
1716 mutated.Element = me;
1717 mutated.info = null;
1721 #region ITypeDefinition Members
1723 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1725 return Element.MemberDefinition.DeclaringAssembly;
1729 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1731 return Element.MemberDefinition.IsInternalAsPublic (assembly);
1734 public string Namespace {
1735 get { throw new NotImplementedException (); }
1738 public int TypeParametersCount {
1744 public TypeParameterSpec[] TypeParameters {
1746 throw new NotSupportedException ();
1750 public TypeSpec GetAttributeCoClass ()
1752 return Element.MemberDefinition.GetAttributeCoClass ();
1755 public string GetAttributeDefaultMember ()
1757 return Element.MemberDefinition.GetAttributeDefaultMember ();
1760 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1762 Element.MemberDefinition.LoadMembers (declaringType, onlyTypes, ref cache);
1765 public bool IsImported {
1767 return Element.MemberDefinition.IsImported;
1771 public string[] ConditionalConditions ()
1773 return Element.MemberDefinition.ConditionalConditions ();
1776 bool? IMemberDefinition.CLSAttributeValue {
1778 return Element.MemberDefinition.CLSAttributeValue;
1782 public void SetIsAssigned ()
1784 Element.MemberDefinition.SetIsAssigned ();
1787 public void SetIsUsed ()
1789 Element.MemberDefinition.SetIsUsed ();
1795 public class ArrayContainer : ElementTypeSpec
1797 public struct TypeRankPair : IEquatable<TypeRankPair>
1802 public TypeRankPair (TypeSpec ts, int rank)
1808 public override int GetHashCode ()
1810 return ts.GetHashCode () ^ rank.GetHashCode ();
1813 #region IEquatable<Tuple<T1,T2>> Members
1815 public bool Equals (TypeRankPair other)
1817 return other.ts == ts && other.rank == rank;
1824 readonly ModuleContainer module;
1826 ArrayContainer (ModuleContainer module, TypeSpec element, int rank)
1827 : base (MemberKind.ArrayType, element, null)
1829 this.module = module;
1833 public override IList<TypeSpec> Interfaces {
1835 return BaseType.Interfaces;
1845 public MethodInfo GetConstructor ()
1847 var mb = module.Builder;
1849 var arg_types = new MetaType[rank];
1850 for (int i = 0; i < rank; i++)
1851 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1853 var ctor = mb.GetArrayMethod (
1854 GetMetaInfo (), Constructor.ConstructorName,
1855 CallingConventions.HasThis,
1861 public MethodInfo GetAddressMethod ()
1863 var mb = module.Builder;
1865 var arg_types = new MetaType[rank];
1866 for (int i = 0; i < rank; i++)
1867 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1869 var address = mb.GetArrayMethod (
1870 GetMetaInfo (), "Address",
1871 CallingConventions.HasThis | CallingConventions.Standard,
1872 ReferenceContainer.MakeType (module, Element).GetMetaInfo (), arg_types);
1877 public MethodInfo GetGetMethod ()
1879 var mb = module.Builder;
1881 var arg_types = new MetaType[rank];
1882 for (int i = 0; i < rank; i++)
1883 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1885 var get = mb.GetArrayMethod (
1886 GetMetaInfo (), "Get",
1887 CallingConventions.HasThis | CallingConventions.Standard,
1888 Element.GetMetaInfo (), arg_types);
1893 public MethodInfo GetSetMethod ()
1895 var mb = module.Builder;
1897 var arg_types = new MetaType[rank + 1];
1898 for (int i = 0; i < rank; i++)
1899 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1901 arg_types[rank] = Element.GetMetaInfo ();
1903 var set = mb.GetArrayMethod (
1904 GetMetaInfo (), "Set",
1905 CallingConventions.HasThis | CallingConventions.Standard,
1906 module.Compiler.BuiltinTypes.Void.GetMetaInfo (), arg_types);
1911 public override MetaType GetMetaInfo ()
1915 info = Element.GetMetaInfo ().MakeArrayType ();
1917 info = Element.GetMetaInfo ().MakeArrayType (rank);
1923 protected override string GetPostfixSignature()
1925 return GetPostfixSignature (rank);
1928 public static string GetPostfixSignature (int rank)
1930 StringBuilder sb = new StringBuilder ();
1932 for (int i = 1; i < rank; i++) {
1937 return sb.ToString ();
1940 public override string GetSignatureForDocumentation (bool explicitName)
1942 StringBuilder sb = new StringBuilder ();
1943 GetElementSignatureForDocumentation (sb, explicitName);
1944 return sb.ToString ();
1947 void GetElementSignatureForDocumentation (StringBuilder sb, bool explicitName)
1949 var ac = Element as ArrayContainer;
1951 sb.Append (Element.GetSignatureForDocumentation (explicitName));
1953 ac.GetElementSignatureForDocumentation (sb, explicitName);
1956 sb.Append (GetPostfixSignature (rank));
1959 for (int i = 1; i < rank; i++) {
1969 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element)
1971 return MakeType (module, element, 1);
1974 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element, int rank)
1977 var key = new TypeRankPair (element, rank);
1978 if (!module.ArrayTypesCache.TryGetValue (key, out ac)) {
1979 ac = new ArrayContainer (module, element, rank);
1980 ac.BaseType = module.Compiler.BuiltinTypes.Array;
1982 module.ArrayTypesCache.Add (key, ac);
1988 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1990 return Element.ResolveMissingDependencies (caller);
1994 class ReferenceContainer : ElementTypeSpec
1996 ReferenceContainer (TypeSpec element)
1997 : base (MemberKind.Class, element, null) // TODO: Kind.Class is most likely wrong
2001 public override IList<TypeSpec> Interfaces {
2007 public override MetaType GetMetaInfo ()
2010 info = Element.GetMetaInfo ().MakeByRefType ();
2016 public static ReferenceContainer MakeType (ModuleContainer module, TypeSpec element)
2018 ReferenceContainer pc;
2019 if (!module.ReferenceTypesCache.TryGetValue (element, out pc)) {
2020 pc = new ReferenceContainer (element);
2021 module.ReferenceTypesCache.Add (element, pc);
2028 class PointerContainer : ElementTypeSpec
2030 private PointerContainer (TypeSpec element)
2031 : base (MemberKind.PointerType, element, null)
2033 // It's never CLS-Compliant
2034 state &= ~StateFlags.CLSCompliant_Undetected;
2037 public override IList<TypeSpec> Interfaces {
2043 public override MetaType GetMetaInfo ()
2046 info = Element.GetMetaInfo ().MakePointerType ();
2052 protected override string GetPostfixSignature()
2057 public static PointerContainer MakeType (ModuleContainer module, TypeSpec element)
2059 PointerContainer pc;
2060 if (!module.PointerTypesCache.TryGetValue (element, out pc)) {
2061 pc = new PointerContainer (element);
2062 module.PointerTypesCache.Add (element, pc);
2069 public class MissingTypeSpecReference
2071 public MissingTypeSpecReference (TypeSpec type, MemberSpec caller)
2077 public TypeSpec Type { get; private set; }
2078 public MemberSpec Caller { get; private set; }