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;
17 using MetaType = IKVM.Reflection.Type;
18 using IKVM.Reflection;
20 using MetaType = System.Type;
21 using System.Reflection;
26 public class TypeSpec : MemberSpec
28 protected MetaType info;
29 protected MemberCache cache;
30 protected IList<TypeSpec> ifaces;
33 Dictionary<TypeSpec[], InflatedTypeSpec> inflated_instances;
35 public static readonly TypeSpec[] EmptyTypes = new TypeSpec[0];
38 // Reflection Emit hacking
39 static readonly Type TypeBuilder;
40 static readonly Type GenericTypeBuilder;
44 var assembly = typeof (object).Assembly;
45 TypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilder");
46 GenericTypeBuilder = assembly.GetType ("System.Reflection.MonoGenericClass");
47 if (GenericTypeBuilder == null)
48 GenericTypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilderInstantiation");
52 public TypeSpec (MemberKind kind, TypeSpec declaringType, ITypeDefinition definition, MetaType info, Modifiers modifiers)
53 : base (kind, declaringType, definition, modifiers)
55 this.declaringType = declaringType;
58 if (definition != null && definition.TypeParametersCount > 0)
59 state |= StateFlags.IsGeneric;
64 public override int Arity {
66 return MemberDefinition.TypeParametersCount;
70 public virtual TypeSpec BaseType {
79 public virtual BuiltinTypeSpec.Type BuiltinType {
81 return BuiltinTypeSpec.Type.None;
85 public bool HasDynamicElement {
87 return (state & StateFlags.HasDynamicElement) != 0;
91 public virtual IList<TypeSpec> Interfaces {
100 public bool IsArray {
102 return Kind == MemberKind.ArrayType;
106 public bool IsAttribute {
113 if (type.BuiltinType == BuiltinTypeSpec.Type.Attribute)
119 type = type.base_type;
120 } while (type != null);
126 public bool IsInterface {
128 return Kind == MemberKind.Interface;
132 public bool IsClass {
134 return Kind == MemberKind.Class;
138 public bool IsConstantCompatible {
140 if ((Kind & (MemberKind.Enum | MemberKind.Class | MemberKind.Interface | MemberKind.Delegate | MemberKind.ArrayType)) != 0)
143 switch (BuiltinType) {
144 case BuiltinTypeSpec.Type.Int:
145 case BuiltinTypeSpec.Type.UInt:
146 case BuiltinTypeSpec.Type.Long:
147 case BuiltinTypeSpec.Type.ULong:
148 case BuiltinTypeSpec.Type.Float:
149 case BuiltinTypeSpec.Type.Double:
150 case BuiltinTypeSpec.Type.Char:
151 case BuiltinTypeSpec.Type.Short:
152 case BuiltinTypeSpec.Type.Decimal:
153 case BuiltinTypeSpec.Type.Bool:
154 case BuiltinTypeSpec.Type.SByte:
155 case BuiltinTypeSpec.Type.Byte:
156 case BuiltinTypeSpec.Type.UShort:
157 case BuiltinTypeSpec.Type.Dynamic:
165 public bool IsDelegate {
167 return Kind == MemberKind.Delegate;
172 // Returns true for instances of Expression<T>
174 public virtual bool IsExpressionTreeType {
179 state = value ? state | StateFlags.InflatedExpressionType : state & ~StateFlags.InflatedExpressionType;
185 return Kind == MemberKind.Enum;
190 // Returns true for instances of IList<T>, IEnumerable<T>, ICollection<T>
192 public virtual bool IsGenericIterateInterface {
197 state = value ? state | StateFlags.GenericIterateInterface : state & ~StateFlags.GenericIterateInterface;
202 // Returns true for instances of System.Threading.Tasks.Task<T>
204 public virtual bool IsGenericTask {
209 state = value ? state | StateFlags.GenericTask : state & ~StateFlags.GenericTask;
213 // TODO: Should probably do
214 // IsGenericType -- recursive
215 // HasTypeParameter -- non-recursive
216 public bool IsGenericOrParentIsGeneric {
222 ts = ts.declaringType;
223 } while (ts != null);
229 public bool IsGenericParameter {
231 return Kind == MemberKind.TypeParameter;
236 // Returns true for instances of Nullable<T>
238 public virtual bool IsNullableType {
243 state = value ? state | StateFlags.InflatedNullableType : state & ~StateFlags.InflatedNullableType;
247 public bool IsNested {
248 get { return declaringType != null && Kind != MemberKind.TypeParameter; }
251 public bool IsPointer {
253 return Kind == MemberKind.PointerType;
257 public bool IsSealed {
258 get { return (Modifiers & Modifiers.SEALED) != 0; }
261 public bool IsSpecialRuntimeType {
263 return (state & StateFlags.SpecialRuntimeType) != 0;
266 state = value ? state | StateFlags.SpecialRuntimeType : state & ~StateFlags.SpecialRuntimeType;
270 public bool IsStruct {
272 return Kind == MemberKind.Struct;
276 public bool IsTypeBuilder {
281 var meta = GetMetaInfo().GetType ();
282 return meta == TypeBuilder || meta == GenericTypeBuilder;
287 public MemberCache MemberCache {
289 if (cache == null || (state & StateFlags.PendingMemberCacheMembers) != 0)
290 InitializeMemberCache (false);
296 throw new InternalErrorException ("Membercache reset");
302 public MemberCache MemberCacheTypes {
305 InitializeMemberCache (true);
311 public new ITypeDefinition MemberDefinition {
313 return (ITypeDefinition) definition;
317 // TODO: Wouldn't be better to rely on cast to InflatedTypeSpec and
318 // remove the property, YES IT WOULD !!!
319 public virtual TypeSpec[] TypeArguments {
320 get { return TypeSpec.EmptyTypes; }
325 public bool AddInterface (TypeSpec iface)
327 if ((state & StateFlags.InterfacesExpanded) != 0)
328 throw new InternalErrorException ("Modifying expanded interface list");
330 if (ifaces == null) {
331 ifaces = new List<TypeSpec> () { iface };
335 if (!ifaces.Contains (iface)) {
344 // Special version used during type definition
346 public bool AddInterfaceDefined (TypeSpec iface)
348 if (!AddInterface (iface))
352 // We can get into a situation where a type is inflated before
353 // its interfaces are resoved. Consider this situation
355 // class A<T> : X<A<int>>, IFoo {}
357 // When resolving base class of X`1 we inflate context type A`1
358 // All this happens before we even hit IFoo resolve. Without
359 // additional expansion any inside usage of A<T> would miss IFoo
360 // interface because it comes from early inflated TypeSpec
362 if (inflated_instances != null) {
363 foreach (var inflated in inflated_instances) {
364 inflated.Value.AddInterface (iface);
371 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
373 if (Kind != MemberKind.Class)
374 throw new InternalErrorException ();
377 return Attribute.DefaultUsageAttribute;
379 AttributeUsageAttribute aua = null;
381 while (type != null) {
382 aua = type.MemberDefinition.GetAttributeUsage (pa);
386 type = type.BaseType;
392 public virtual MetaType GetMetaInfo ()
397 public virtual TypeSpec GetDefinition ()
402 public override string GetSignatureForDocumentation ()
404 StringBuilder sb = new StringBuilder ();
406 sb.Append (DeclaringType.GetSignatureForDocumentation ());
408 sb.Append (MemberDefinition.Namespace);
416 if (this is InflatedTypeSpec) {
418 for (int i = 0; i < Arity; ++i) {
422 sb.Append (TypeArguments[i].GetSignatureForDocumentation ());
427 sb.Append (Arity.ToString ());
431 return sb.ToString ();
434 public string GetExplicitNameSignatureForDocumentation ()
436 StringBuilder sb = new StringBuilder ();
438 sb.Append (DeclaringType.GetExplicitNameSignatureForDocumentation ());
439 } else if (MemberDefinition.Namespace != null) {
440 sb.Append (MemberDefinition.Namespace.Replace ('.', '#'));
449 for (int i = 0; i < Arity; ++i) {
453 sb.Append (TypeArguments[i].GetExplicitNameSignatureForDocumentation ());
458 return sb.ToString ();
461 public override string GetSignatureForError ()
466 s = DeclaringType.GetSignatureForError ();
467 } else if (MemberDefinition is AnonymousTypeClass) {
468 return ((AnonymousTypeClass) MemberDefinition).GetSignatureForError ();
470 s = MemberDefinition.Namespace;
473 if (!string.IsNullOrEmpty (s))
476 return s + Name + GetTypeNameSignature ();
479 public string GetSignatureForErrorIncludingAssemblyName ()
481 return string.Format ("{0} [{1}]", GetSignatureForError (), MemberDefinition.DeclaringAssembly.FullName);
484 protected virtual string GetTypeNameSignature ()
489 return "<" + TypeManager.CSharpName (MemberDefinition.TypeParameters) + ">";
492 public bool ImplementsInterface (TypeSpec iface, bool variantly)
496 var ifaces = t.Interfaces;
497 if (ifaces != null) {
498 for (int i = 0; i < ifaces.Count; ++i) {
499 if (TypeSpecComparer.IsEqual (ifaces[i], iface))
502 if (variantly && TypeSpecComparer.Variant.IsEqual (ifaces[i], iface))
507 // TODO: Why is it needed when we do it during import
514 protected virtual void InitializeMemberCache (bool onlyTypes)
517 MemberDefinition.LoadMembers (this, onlyTypes, ref cache);
518 } catch (Exception e) {
519 throw new InternalErrorException (e, "Unexpected error when loading type `{0}'", GetSignatureForError ());
523 state |= StateFlags.PendingMemberCacheMembers;
525 state &= ~StateFlags.PendingMemberCacheMembers;
529 // Is @baseClass base implementation of @type. With enabled @dynamicIsEqual the slower
530 // comparison is used to hide differences between `object' and `dynamic' for generic
531 // types. Should not be used for comparisons where G<object> != G<dynamic>
533 public static bool IsBaseClass (TypeSpec type, TypeSpec baseClass, bool dynamicIsObject)
535 if (dynamicIsObject && baseClass.IsGeneric) {
537 // Returns true for a hierarchies like this when passing baseClass of A<dynamic>
539 // class B : A<object> {}
541 type = type.BaseType;
542 while (type != null) {
543 if (TypeSpecComparer.IsEqual (type, baseClass))
546 type = type.BaseType;
552 while (type != null) {
553 type = type.BaseType;
554 if (type == baseClass)
561 public static bool IsReferenceType (TypeSpec t)
564 case MemberKind.TypeParameter:
565 return ((TypeParameterSpec) t).IsReferenceType;
566 case MemberKind.Struct:
567 case MemberKind.Enum:
568 case MemberKind.Void:
570 case MemberKind.InternalCompilerType:
572 // Null is considered to be a reference type
574 return t == InternalType.NullLiteral || t.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
580 public static bool IsValueType (TypeSpec t)
583 case MemberKind.TypeParameter:
584 return ((TypeParameterSpec) t).IsValueType;
585 case MemberKind.Struct:
586 case MemberKind.Enum:
593 public override MemberSpec InflateMember (TypeParameterInflator inflator)
595 var targs = IsGeneric ? MemberDefinition.TypeParameters : TypeSpec.EmptyTypes;
598 // When inflating nested type from inside the type instance will be same
599 // because type parameters are same for all nested types
601 if (DeclaringType == inflator.TypeInstance) {
602 return MakeGenericType (inflator.Context, targs);
605 return new InflatedTypeSpec (inflator.Context, this, inflator.TypeInstance, targs);
608 public InflatedTypeSpec MakeGenericType (IModuleContext context, TypeSpec[] targs)
610 if (targs.Length == 0 && !IsNested)
611 throw new ArgumentException ("Empty type arguments for type " + GetSignatureForError ());
613 InflatedTypeSpec instance;
615 if (inflated_instances == null) {
616 inflated_instances = new Dictionary<TypeSpec[], InflatedTypeSpec> (TypeSpecComparer.Default);
619 instance = this as InflatedTypeSpec;
620 if (instance != null) {
622 // Nested types could be inflated on already inflated instances
623 // Caching this type ensured we are using same instance for
624 // inside/outside inflation using local type parameters
626 inflated_instances.Add (TypeArguments, instance);
631 if (!inflated_instances.TryGetValue (targs, out instance)) {
632 if (GetDefinition () != this && !IsNested)
633 throw new InternalErrorException ("`{0}' must be type definition or nested non-inflated type to MakeGenericType",
634 GetSignatureForError ());
636 instance = new InflatedTypeSpec (context, this, declaringType, targs);
637 inflated_instances.Add (targs, instance);
643 public virtual TypeSpec Mutate (TypeParameterMutator mutator)
648 public override List<TypeSpec> ResolveMissingDependencies ()
650 List<TypeSpec> missing = null;
652 if (Kind == MemberKind.MissingType) {
653 missing = new List<TypeSpec> ();
658 foreach (var targ in TypeArguments) {
659 if (targ.Kind == MemberKind.MissingType) {
661 missing = new List<TypeSpec> ();
667 if (Interfaces != null) {
668 foreach (var iface in Interfaces) {
669 if (iface.Kind == MemberKind.MissingType) {
671 missing = new List<TypeSpec> ();
678 if (missing != null || BaseType == null)
681 return BaseType.ResolveMissingDependencies ();
684 public void SetMetaInfo (MetaType info)
686 if (this.info != null)
687 throw new InternalErrorException ("MetaInfo reset");
692 public void SetExtensionMethodContainer ()
694 modifiers |= Modifiers.METHOD_EXTENSION;
698 public sealed class BuiltinTypeSpec : TypeSpec
704 // Ordered carefully for fast compares
732 MulticastDelegate = 23,
745 readonly string name;
747 public BuiltinTypeSpec (MemberKind kind, string ns, string name, Type builtinKind)
748 : base (kind, null, null, null, Modifiers.PUBLIC)
750 this.type = builtinKind;
755 public BuiltinTypeSpec (string name, Type builtinKind)
756 : this (MemberKind.InternalCompilerType, "", name, builtinKind)
758 // Make all internal types CLS-compliant, non-obsolete, compact
759 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
764 public override int Arity {
770 public override BuiltinTypeSpec.Type BuiltinType {
776 public string FullName {
778 return ns + '.' + name;
782 public override string Name {
788 public string Namespace {
796 public static bool IsPrimitiveType (TypeSpec type)
798 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.LastPrimitive;
801 public static bool IsPrimitiveTypeOrDecimal (TypeSpec type)
803 return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.Decimal;
806 public override string GetSignatureForError ()
809 case "Int32": return "int";
810 case "Int64": return "long";
811 case "String": return "string";
812 case "Boolean": return "bool";
813 case "Void": return "void";
814 case "Object": return "object";
815 case "UInt32": return "uint";
816 case "Int16": return "short";
817 case "UInt16": return "ushort";
818 case "UInt64": return "ulong";
819 case "Single": return "float";
820 case "Double": return "double";
821 case "Decimal": return "decimal";
822 case "Char": return "char";
823 case "Byte": return "byte";
824 case "SByte": return "sbyte";
834 // Returns the size of type if known, otherwise, 0
836 public static int GetSize (TypeSpec type)
838 switch (type.BuiltinType) {
862 public void SetDefinition (ITypeDefinition td, MetaType type, Modifiers mod)
864 this.definition = td;
866 this.modifiers |= (mod & ~Modifiers.AccessibilityMask);
869 public void SetDefinition (TypeSpec ts)
871 this.definition = ts.MemberDefinition;
872 this.info = ts.GetMetaInfo ();
873 this.BaseType = ts.BaseType;
874 this.Interfaces = ts.Interfaces;
875 this.modifiers = ts.Modifiers;
879 static class TypeSpecComparer
882 // Does strict reference comparion only
884 public static readonly DefaultImpl Default = new DefaultImpl ();
886 public class DefaultImpl : IEqualityComparer<TypeSpec[]>
888 #region IEqualityComparer<TypeSpec[]> Members
890 bool IEqualityComparer<TypeSpec[]>.Equals (TypeSpec[] x, TypeSpec[] y)
895 if (x.Length != y.Length)
898 for (int i = 0; i < x.Length; ++i)
905 int IEqualityComparer<TypeSpec[]>.GetHashCode (TypeSpec[] obj)
908 for (int i = 0; i < obj.Length; ++i)
909 hash = (hash << 5) - hash + obj[i].GetHashCode ();
918 // When comparing type signature of overrides or overloads
919 // this version tolerates different MVARs at same position
921 public static class Override
923 public static bool IsEqual (TypeSpec a, TypeSpec b)
929 // Consider the following example:
931 // public abstract class A
933 // public abstract T Foo<T>();
936 // public class B : A
938 // public override U Foo<T>() { return default (U); }
941 // Here, `T' and `U' are method type parameters from different methods
942 // (A.Foo and B.Foo), so both `==' and Equals() will fail.
944 // However, since we're determining whether B.Foo() overrides A.Foo(),
945 // we need to do a signature based comparision and consider them equal.
948 var tp_a = a as TypeParameterSpec;
950 var tp_b = b as TypeParameterSpec;
951 return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
954 var ac_a = a as ArrayContainer;
956 var ac_b = b as ArrayContainer;
957 return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
960 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
961 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
963 if (a.MemberDefinition != b.MemberDefinition)
967 for (int i = 0; i < a.TypeArguments.Length; ++i) {
968 if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
980 // Compares unordered arrays
982 public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
987 if (a == null || b == null || a.Length != b.Length)
990 for (int ai = 0; ai < a.Length; ++ai) {
992 for (int bi = 0; bi < b.Length; ++bi) {
993 if (IsEqual (a[ai], b[bi])) {
1006 public static bool IsEqual (AParametersCollection a, AParametersCollection b)
1011 if (a.Count != b.Count)
1014 for (int i = 0; i < a.Count; ++i) {
1015 if (!IsEqual (a.Types[i], b.Types[i]))
1018 const Parameter.Modifier ref_out = Parameter.Modifier.REF | Parameter.Modifier.OUT;
1019 if ((a.FixedParameters[i].ModFlags & ref_out) != (b.FixedParameters[i].ModFlags & ref_out))
1028 // Type variance equality comparison
1030 public static class Variant
1032 public static bool IsEqual (TypeSpec type1, TypeSpec type2)
1034 if (!type1.IsGeneric || !type2.IsGeneric)
1037 var target_type_def = type2.MemberDefinition;
1038 if (type1.MemberDefinition != target_type_def)
1041 var t1_targs = type1.TypeArguments;
1042 var t2_targs = type2.TypeArguments;
1043 var targs_definition = target_type_def.TypeParameters;
1045 if (!type1.IsInterface && !type1.IsDelegate) {
1049 for (int i = 0; i < targs_definition.Length; ++i) {
1050 if (TypeSpecComparer.IsEqual (t1_targs[i], t2_targs[i]))
1053 Variance v = targs_definition[i].Variance;
1054 if (v == Variance.None) {
1058 if (v == Variance.Covariant) {
1059 if (!Convert.ImplicitReferenceConversionExists (t1_targs[i], t2_targs[i]))
1061 } else if (!Convert.ImplicitReferenceConversionExists (t2_targs[i], t1_targs[i])) {
1071 // Checks whether two generic instances may become equal for some
1072 // particular instantiation (26.3.1).
1074 public static class Unify
1077 // Either @a or @b must be generic type
1079 public static bool IsEqual (TypeSpec a, TypeSpec b)
1081 if (a.MemberDefinition != b.MemberDefinition) {
1082 var base_ifaces = a.Interfaces;
1083 if (base_ifaces != null) {
1084 foreach (var base_iface in base_ifaces) {
1085 if (base_iface.Arity > 0 && IsEqual (base_iface, b))
1093 var ta = a.TypeArguments;
1094 var tb = b.TypeArguments;
1095 for (int i = 0; i < ta.Length; i++) {
1096 if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
1103 static bool ContainsTypeParameter (TypeSpec tparam, TypeSpec type)
1105 TypeSpec[] targs = type.TypeArguments;
1106 for (int i = 0; i < targs.Length; i++) {
1107 if (tparam == targs[i])
1110 if (ContainsTypeParameter (tparam, targs[i]))
1118 /// Check whether `a' and `b' may become equal generic types.
1119 /// The algorithm to do that is a little bit complicated.
1121 static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
1123 if (a.IsGenericParameter) {
1125 // If a is an array of a's type, they may never
1132 // If b is a generic parameter or an actual type,
1133 // they may become equal:
1135 // class X<T,U> : I<T>, I<U>
1136 // class X<T> : I<T>, I<float>
1138 if (b.IsGenericParameter)
1139 return a != b && a.DeclaringType == b.DeclaringType;
1142 // We're now comparing a type parameter with a
1143 // generic instance. They may become equal unless
1144 // the type parameter appears anywhere in the
1145 // generic instance:
1147 // class X<T,U> : I<T>, I<X<U>>
1148 // -> error because you could instanciate it as
1151 // class X<T> : I<T>, I<X<T>> -> ok
1154 return !ContainsTypeParameter (a, b);
1157 if (b.IsGenericParameter)
1158 return MayBecomeEqualGenericTypes (b, a);
1161 // At this point, neither a nor b are a type parameter.
1163 // If one of them is a generic instance, compare them (if the
1164 // other one is not a generic instance, they can never
1167 if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
1168 return IsEqual (a, b);
1171 // If both of them are arrays.
1173 var a_ac = a as ArrayContainer;
1175 var b_ac = b as ArrayContainer;
1176 if (b_ac == null || a_ac.Rank != b_ac.Rank)
1179 return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
1183 // Ok, two ordinary types.
1189 public static bool Equals (TypeSpec[] x, TypeSpec[] y)
1194 if (x.Length != y.Length)
1197 for (int i = 0; i < x.Length; ++i)
1198 if (!IsEqual (x[i], y[i]))
1205 // Identity type conversion
1207 // Default reference comparison, it has to be used when comparing
1208 // two possible dynamic/internal types
1210 public static bool IsEqual (TypeSpec a, TypeSpec b)
1213 // This also rejects dynamic == dynamic
1214 return a.Kind != MemberKind.InternalCompilerType || a.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
1217 if (a == null || b == null)
1221 var a_a = (ArrayContainer) a;
1222 var b_a = b as ArrayContainer;
1226 return a_a.Rank == b_a.Rank && IsEqual (a_a.Element, b_a.Element);
1229 if (!a.IsGeneric || !b.IsGeneric) {
1231 // object and dynamic are considered equivalent there is an identity conversion
1232 // between object and dynamic, and between constructed types that are the same
1233 // when replacing all occurences of dynamic with object.
1235 if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1236 return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
1241 if (a.MemberDefinition != b.MemberDefinition)
1245 if (!Equals (a.TypeArguments, b.TypeArguments))
1248 a = a.DeclaringType;
1249 b = b.DeclaringType;
1250 } while (a != null);
1256 public interface ITypeDefinition : IMemberDefinition
1258 IAssemblyDefinition DeclaringAssembly { get; }
1259 string Namespace { get; }
1260 int TypeParametersCount { get; }
1261 TypeParameterSpec[] TypeParameters { get; }
1263 TypeSpec GetAttributeCoClass ();
1264 string GetAttributeDefaultMember ();
1265 AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
1266 bool IsInternalAsPublic (IAssemblyDefinition assembly);
1267 void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache);
1270 class InternalType : TypeSpec, ITypeDefinition
1272 public static readonly InternalType AnonymousMethod = new InternalType ("anonymous method");
1273 public static readonly InternalType Arglist = new InternalType ("__arglist");
1274 public static readonly InternalType MethodGroup = new InternalType ("method group");
1275 public static readonly InternalType NullLiteral = new InternalType ("null");
1276 public static readonly InternalType FakeInternalType = new InternalType ("<fake$type>");
1277 public static readonly InternalType Namespace = new InternalType ("<namespace>");
1279 readonly string name;
1281 InternalType (string name, MemberCache cache)
1287 InternalType (string name)
1288 : base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
1291 this.definition = this;
1292 cache = MemberCache.Empty;
1294 // Make all internal types CLS-compliant, non-obsolete
1295 state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected)) | StateFlags.CLSCompliant;
1300 public override int Arity {
1306 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1308 throw new NotImplementedException ();
1312 bool IMemberDefinition.IsImported {
1318 public override string Name {
1324 string ITypeDefinition.Namespace {
1330 int ITypeDefinition.TypeParametersCount {
1336 TypeParameterSpec[] ITypeDefinition.TypeParameters {
1344 public override string GetSignatureForError ()
1349 #region ITypeDefinition Members
1351 TypeSpec ITypeDefinition.GetAttributeCoClass ()
1356 string ITypeDefinition.GetAttributeDefaultMember ()
1361 AttributeUsageAttribute ITypeDefinition.GetAttributeUsage (PredefinedAttribute pa)
1366 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1368 throw new NotImplementedException ();
1371 void ITypeDefinition.LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1373 throw new NotImplementedException ();
1376 string[] IMemberDefinition.ConditionalConditions ()
1381 ObsoleteAttribute IMemberDefinition.GetAttributeObsolete ()
1386 bool? IMemberDefinition.CLSAttributeValue {
1392 void IMemberDefinition.SetIsAssigned ()
1396 void IMemberDefinition.SetIsUsed ()
1403 public abstract class ElementTypeSpec : TypeSpec, ITypeDefinition
1405 protected ElementTypeSpec (MemberKind kind, TypeSpec element, MetaType info)
1406 : base (kind, element.DeclaringType, null, info, element.Modifiers)
1408 this.Element = element;
1410 // Some flags can be copied directly from the element
1411 const StateFlags shared_flags = StateFlags.CLSCompliant | StateFlags.CLSCompliant_Undetected
1412 | StateFlags.Obsolete | StateFlags.Obsolete_Undetected | StateFlags.HasDynamicElement;
1413 state &= ~shared_flags;
1414 state |= (element.state & shared_flags);
1416 if (element.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1417 state |= StateFlags.HasDynamicElement;
1419 // Has to use its own type definition instead of just element definition to
1420 // correctly identify itself for cases like x.MemberDefininition == predefined.MemberDefinition
1421 this.definition = this;
1423 cache = MemberCache.Empty;
1428 public TypeSpec Element { get; private set; }
1430 public override string Name {
1432 throw new NotSupportedException ();
1438 public override ObsoleteAttribute GetAttributeObsolete ()
1440 return Element.GetAttributeObsolete ();
1443 protected virtual string GetPostfixSignature ()
1448 public override string GetSignatureForDocumentation ()
1450 return Element.GetSignatureForDocumentation () + GetPostfixSignature ();
1453 public override string GetSignatureForError ()
1455 return Element.GetSignatureForError () + GetPostfixSignature ();
1458 public override TypeSpec Mutate (TypeParameterMutator mutator)
1460 var me = Element.Mutate (mutator);
1464 var mutated = (ElementTypeSpec) MemberwiseClone ();
1465 mutated.Element = me;
1466 mutated.info = null;
1470 #region ITypeDefinition Members
1472 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
1474 return Element.MemberDefinition.DeclaringAssembly;
1478 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1480 return Element.MemberDefinition.IsInternalAsPublic (assembly);
1483 public string Namespace {
1484 get { throw new NotImplementedException (); }
1487 public int TypeParametersCount {
1493 public TypeParameterSpec[] TypeParameters {
1495 throw new NotSupportedException ();
1499 public TypeSpec GetAttributeCoClass ()
1501 return Element.MemberDefinition.GetAttributeCoClass ();
1504 public string GetAttributeDefaultMember ()
1506 return Element.MemberDefinition.GetAttributeDefaultMember ();
1509 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1511 Element.MemberDefinition.LoadMembers (declaringType, onlyTypes, ref cache);
1514 public bool IsImported {
1516 return Element.MemberDefinition.IsImported;
1520 public string[] ConditionalConditions ()
1522 return Element.MemberDefinition.ConditionalConditions ();
1525 bool? IMemberDefinition.CLSAttributeValue {
1527 return Element.MemberDefinition.CLSAttributeValue;
1531 public void SetIsAssigned ()
1533 Element.MemberDefinition.SetIsAssigned ();
1536 public void SetIsUsed ()
1538 Element.MemberDefinition.SetIsUsed ();
1544 public class ArrayContainer : ElementTypeSpec
1546 public struct TypeRankPair : IEquatable<TypeRankPair>
1551 public TypeRankPair (TypeSpec ts, int rank)
1557 public override int GetHashCode ()
1559 return ts.GetHashCode () ^ rank.GetHashCode ();
1562 #region IEquatable<Tuple<T1,T2>> Members
1564 public bool Equals (TypeRankPair other)
1566 return other.ts == ts && other.rank == rank;
1573 readonly ModuleContainer module;
1575 private ArrayContainer (ModuleContainer module, TypeSpec element, int rank)
1576 : base (MemberKind.ArrayType, element, null)
1578 this.module = module;
1588 public MethodInfo GetConstructor ()
1590 var mb = module.Builder;
1592 var arg_types = new MetaType[rank];
1593 for (int i = 0; i < rank; i++)
1594 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1596 var ctor = mb.GetArrayMethod (
1597 GetMetaInfo (), Constructor.ConstructorName,
1598 CallingConventions.HasThis,
1604 public MethodInfo GetAddressMethod ()
1606 var mb = module.Builder;
1608 var arg_types = new MetaType[rank];
1609 for (int i = 0; i < rank; i++)
1610 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1612 var address = mb.GetArrayMethod (
1613 GetMetaInfo (), "Address",
1614 CallingConventions.HasThis | CallingConventions.Standard,
1615 ReferenceContainer.MakeType (module, Element).GetMetaInfo (), arg_types);
1620 public MethodInfo GetGetMethod ()
1622 var mb = module.Builder;
1624 var arg_types = new MetaType[rank];
1625 for (int i = 0; i < rank; i++)
1626 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1628 var get = mb.GetArrayMethod (
1629 GetMetaInfo (), "Get",
1630 CallingConventions.HasThis | CallingConventions.Standard,
1631 Element.GetMetaInfo (), arg_types);
1636 public MethodInfo GetSetMethod ()
1638 var mb = module.Builder;
1640 var arg_types = new MetaType[rank + 1];
1641 for (int i = 0; i < rank; i++)
1642 arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
1644 arg_types[rank] = Element.GetMetaInfo ();
1646 var set = mb.GetArrayMethod (
1647 GetMetaInfo (), "Set",
1648 CallingConventions.HasThis | CallingConventions.Standard,
1649 module.Compiler.BuiltinTypes.Void.GetMetaInfo (), arg_types);
1654 public override MetaType GetMetaInfo ()
1658 info = Element.GetMetaInfo ().MakeArrayType ();
1660 info = Element.GetMetaInfo ().MakeArrayType (rank);
1666 protected override string GetPostfixSignature()
1668 return GetPostfixSignature (rank);
1671 public static string GetPostfixSignature (int rank)
1673 StringBuilder sb = new StringBuilder ();
1675 for (int i = 1; i < rank; i++) {
1680 return sb.ToString ();
1683 public override string GetSignatureForDocumentation ()
1685 StringBuilder sb = new StringBuilder ();
1686 GetElementSignatureForDocumentation (sb);
1687 return sb.ToString ();
1690 void GetElementSignatureForDocumentation (StringBuilder sb)
1692 var ac = Element as ArrayContainer;
1694 sb.Append (Element.GetSignatureForDocumentation ());
1696 ac.GetElementSignatureForDocumentation (sb);
1699 for (int i = 1; i < rank; i++) {
1708 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element)
1710 return MakeType (module, element, 1);
1713 public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element, int rank)
1716 var key = new TypeRankPair (element, rank);
1717 if (!module.ArrayTypesCache.TryGetValue (key, out ac)) {
1718 ac = new ArrayContainer (module, element, rank) {
1719 BaseType = module.Compiler.BuiltinTypes.Array
1722 module.ArrayTypesCache.Add (key, ac);
1729 class ReferenceContainer : ElementTypeSpec
1731 private ReferenceContainer (TypeSpec element)
1732 : base (MemberKind.Class, element, null) // TODO: Kind.Class is most likely wrong
1736 public override MetaType GetMetaInfo ()
1739 info = Element.GetMetaInfo ().MakeByRefType ();
1745 public static ReferenceContainer MakeType (ModuleContainer module, TypeSpec element)
1747 ReferenceContainer pc;
1748 if (!module.ReferenceTypesCache.TryGetValue (element, out pc)) {
1749 pc = new ReferenceContainer (element);
1750 module.ReferenceTypesCache.Add (element, pc);
1757 class PointerContainer : ElementTypeSpec
1759 private PointerContainer (TypeSpec element)
1760 : base (MemberKind.PointerType, element, null)
1762 // It's never CLS-Compliant
1763 state &= ~StateFlags.CLSCompliant_Undetected;
1766 public override MetaType GetMetaInfo ()
1769 info = Element.GetMetaInfo ().MakePointerType ();
1775 protected override string GetPostfixSignature()
1780 public static PointerContainer MakeType (ModuleContainer module, TypeSpec element)
1782 PointerContainer pc;
1783 if (!module.PointerTypesCache.TryGetValue (element, out pc)) {
1784 pc = new PointerContainer (element);
1785 module.PointerTypesCache.Add (element, pc);