2 // typemanager.cs: C# type manager
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Ravi Pratap (ravi@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
15 // We will eventually remove the SIMPLE_SPEEDUP, and should never change
16 // the behavior of the compilation. This can be removed if we rework
17 // the code to get a list of namespaces available.
19 #define SIMPLE_SPEEDUP
23 using System.Globalization;
24 using System.Collections;
25 using System.Reflection;
26 using System.Reflection.Emit;
28 using System.Runtime.CompilerServices;
29 using System.Diagnostics;
31 namespace Mono.CSharp {
38 // A list of core types that the compiler requires or uses
40 static public Type object_type;
41 static public Type value_type;
42 static public Type string_type;
43 static public Type int32_type;
44 static public Type uint32_type;
45 static public Type int64_type;
46 static public Type uint64_type;
47 static public Type float_type;
48 static public Type double_type;
49 static public Type char_type;
50 static public Type char_ptr_type;
51 static public Type short_type;
52 static public Type decimal_type;
53 static public Type bool_type;
54 static public Type sbyte_type;
55 static public Type byte_type;
56 static public Type ushort_type;
57 static public Type enum_type;
58 static public Type delegate_type;
59 static public Type multicast_delegate_type;
60 static public Type void_type;
61 static public Type null_type;
62 static public Type array_type;
63 static public Type runtime_handle_type;
64 static public Type type_type;
65 static public Type ienumerator_type;
66 static public Type ienumerable_type;
67 static public Type idisposable_type;
68 static public Type default_member_type;
69 static public Type iasyncresult_type;
70 static public Type asynccallback_type;
71 static public Type intptr_type;
72 static public Type uintptr_type;
73 static public Type runtime_field_handle_type;
74 static public Type runtime_argument_handle_type;
75 static public Type attribute_type;
76 static public Type attribute_usage_type;
77 static public Type decimal_constant_attribute_type;
78 static public Type dllimport_type;
79 static public Type methodimpl_attr_type;
80 static public Type marshal_as_attr_type;
81 static public Type param_array_type;
82 static public Type void_ptr_type;
83 static public Type indexer_name_type;
84 static public Type exception_type;
85 static public Type obsolete_attribute_type;
86 static public Type conditional_attribute_type;
87 static public Type in_attribute_type;
88 static public Type out_attribute_type;
89 static public Type extension_attribute_type;
90 static public Type default_parameter_value_attribute_type;
92 static public Type anonymous_method_type;
93 static public Type cls_compliant_attribute_type;
94 static public Type typed_reference_type;
95 static public Type arg_iterator_type;
96 static public Type mbr_type;
97 static public Type struct_layout_attribute_type;
98 static public Type field_offset_attribute_type;
99 static public Type security_attr_type;
100 static public Type required_attr_type;
101 static public Type guid_attr_type;
102 static public Type assembly_culture_attribute_type;
103 static public Type assembly_version_attribute_type;
104 static public Type coclass_attr_type;
105 static public Type comimport_attr_type;
106 public static Type runtime_helpers_type;
107 public static Type internals_visible_attr_type;
112 static internal Type fixed_buffer_attr_type;
113 static internal Type default_charset_type;
114 static internal Type type_forwarder_attr_type;
115 static internal Type isvolatile_type;
116 static public Type activator_type;
117 static public Type generic_ilist_type;
118 static public Type generic_icollection_type;
119 static public Type generic_ienumerator_type;
120 static public Type generic_ienumerable_type;
121 static public Type generic_nullable_type;
126 static internal Type expression_type;
127 public static Type parameter_expression_type;
130 // Expressions representing the internal types. Used during declaration
133 static public TypeExpr system_object_expr, system_string_expr;
134 static public TypeExpr system_boolean_expr, system_decimal_expr;
135 static public TypeExpr system_single_expr, system_double_expr;
136 static public TypeExpr system_sbyte_expr, system_byte_expr;
137 static public TypeExpr system_int16_expr, system_uint16_expr;
138 static public TypeExpr system_int32_expr, system_uint32_expr;
139 static public TypeExpr system_int64_expr, system_uint64_expr;
140 static public TypeExpr system_char_expr, system_void_expr;
141 static public TypeExpr system_valuetype_expr;
142 static public TypeExpr system_intptr_expr;
143 public static TypeExpr expression_type_expr;
147 // These methods are called by code generated by the compiler
149 static public MethodInfo string_isinterned_string;
150 static public MethodInfo system_type_get_type_from_handle;
151 static public MethodInfo bool_movenext_void;
152 static public MethodInfo void_dispose_void;
153 static public MethodInfo void_monitor_enter_object;
154 static public MethodInfo void_monitor_exit_object;
155 static public MethodInfo void_initializearray_array_fieldhandle;
156 static public MethodInfo int_getlength_int;
157 static public MethodInfo delegate_combine_delegate_delegate;
158 static public MethodInfo delegate_remove_delegate_delegate;
159 static public MethodInfo int_get_offset_to_string_data;
160 static public MethodInfo int_interlocked_compare_exchange;
161 static public PropertyInfo ienumerator_getcurrent;
162 public static MethodInfo methodbase_get_type_from_handle;
163 static public MethodInfo activator_create_instance;
166 // The attribute constructors.
168 static public ConstructorInfo void_decimal_ctor_five_args;
169 static public ConstructorInfo void_decimal_ctor_int_arg;
170 static public ConstructorInfo default_member_ctor;
171 static public ConstructorInfo decimal_constant_attribute_ctor;
172 static internal ConstructorInfo struct_layout_attribute_ctor;
173 static public ConstructorInfo field_offset_attribute_ctor;
174 public static ConstructorInfo invalid_operation_exception_ctor;
176 static public CustomAttributeBuilder param_array_attr;
177 static CustomAttributeBuilder compiler_generated_attr;
180 static internal ConstructorInfo fixed_buffer_attr_ctor;
183 static internal CustomAttributeBuilder extension_attribute_attr;
185 static PtrHashtable builder_to_declspace;
187 static PtrHashtable builder_to_member_cache;
190 // Tracks the interfaces implemented by typebuilders. We only
191 // enter those who do implement or or more interfaces
193 static PtrHashtable builder_to_ifaces;
196 // Maps PropertyBuilder to a Type array that contains
197 // the arguments to the indexer
199 static Hashtable indexer_arguments;
202 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
204 static Hashtable method_params;
207 // A hash table from override methods to their base virtual method.
209 static Hashtable method_overrides;
212 // Keeps track of methods
215 static Hashtable builder_to_method;
218 // Contains all public types from referenced assemblies.
219 // This member is used only if CLS Compliance verification is required.
221 public static Hashtable AllClsTopLevelTypes;
223 static Hashtable fieldbuilders_to_fields;
224 static Hashtable propertybuilder_to_property;
225 static Hashtable fields;
226 static Hashtable events;
227 static PtrHashtable assembly_internals_vis_attrs;
229 public static void CleanUp ()
231 // Lets get everything clean so that we can collect before generating code
232 builder_to_declspace = null;
233 builder_to_member_cache = null;
234 builder_to_ifaces = null;
235 builder_to_type_param = null;
236 indexer_arguments = null;
237 method_params = null;
238 builder_to_method = null;
243 propertybuilder_to_property = null;
244 assembly_internals_vis_attrs = null;
246 TypeHandle.CleanUp ();
250 // These are expressions that represent some of the internal data types, used
253 static void InitExpressionTypes ()
255 system_object_expr = new TypeLookupExpression ("System.Object");
256 system_string_expr = new TypeLookupExpression ("System.String");
257 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
258 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
259 system_single_expr = new TypeLookupExpression ("System.Single");
260 system_double_expr = new TypeLookupExpression ("System.Double");
261 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
262 system_byte_expr = new TypeLookupExpression ("System.Byte");
263 system_int16_expr = new TypeLookupExpression ("System.Int16");
264 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
265 system_int32_expr = new TypeLookupExpression ("System.Int32");
266 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
267 system_int64_expr = new TypeLookupExpression ("System.Int64");
268 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
269 system_char_expr = new TypeLookupExpression ("System.Char");
270 system_void_expr = new TypeLookupExpression ("System.Void");
271 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
272 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
275 static TypeManager ()
279 InitExpressionTypes ();
282 static public void Reset ()
284 builder_to_declspace = new PtrHashtable ();
285 builder_to_member_cache = new PtrHashtable ();
286 builder_to_method = new PtrHashtable ();
287 builder_to_type_param = new PtrHashtable ();
288 method_params = new PtrHashtable ();
289 method_overrides = new PtrHashtable ();
290 indexer_arguments = new PtrHashtable ();
291 builder_to_ifaces = new PtrHashtable ();
293 fieldbuilders_to_fields = new Hashtable ();
294 propertybuilder_to_property = new Hashtable ();
295 fields = new Hashtable ();
296 type_hash = new DoubleHash ();
297 assembly_internals_vis_attrs = new PtrHashtable ();
299 // TODO: I am really bored by all this static stuff
300 string_isinterned_string =
301 system_type_get_type_from_handle =
304 void_monitor_enter_object =
305 void_monitor_exit_object =
306 void_initializearray_array_fieldhandle =
308 delegate_combine_delegate_delegate =
309 delegate_remove_delegate_delegate =
310 int_get_offset_to_string_data =
311 int_interlocked_compare_exchange =
312 methodbase_get_type_from_handle =
313 activator_create_instance = null;
315 ienumerator_getcurrent = null;
317 void_decimal_ctor_five_args =
318 void_decimal_ctor_int_arg =
319 default_member_ctor =
320 decimal_constant_attribute_ctor =
321 struct_layout_attribute_ctor =
322 field_offset_attribute_ctor =
323 invalid_operation_exception_ctor =
324 fixed_buffer_attr_ctor = null;
327 compiler_generated_attr =
328 extension_attribute_attr = null;
330 // to uncover regressions
331 AllClsTopLevelTypes = null;
334 public static void AddUserType (DeclSpace ds)
336 builder_to_declspace.Add (ds.TypeBuilder, ds);
340 // This entry point is used by types that we define under the covers
342 public static void RegisterBuilder (Type tb, Type [] ifaces)
345 builder_to_ifaces [tb] = ifaces;
348 public static void AddMethod (MethodBase builder, IMethodData method)
350 builder_to_method.Add (builder, method);
351 method_params.Add (builder, method.ParameterInfo);
354 public static IMethodData GetMethod (MethodBase builder)
356 return (IMethodData) builder_to_method [builder];
360 /// Returns the DeclSpace whose Type is `t' or null if there is no
361 /// DeclSpace for `t' (ie, the Type comes from a library)
363 public static DeclSpace LookupDeclSpace (Type t)
365 return builder_to_declspace [t] as DeclSpace;
369 /// Returns the TypeContainer whose Type is `t' or null if there is no
370 /// TypeContainer for `t' (ie, the Type comes from a library)
372 public static TypeContainer LookupTypeContainer (Type t)
374 return builder_to_declspace [t] as TypeContainer;
377 public static MemberCache LookupMemberCache (Type t)
379 if (t.Module == CodeGen.Module.Builder) {
380 DeclSpace container = (DeclSpace)builder_to_declspace [t];
381 if (container != null)
382 return container.MemberCache;
386 if (t is GenericTypeParameterBuilder) {
387 TypeParameter container = builder_to_type_param [t] as TypeParameter;
389 if (container != null)
390 return container.MemberCache;
394 return TypeHandle.GetMemberCache (t);
397 public static MemberCache LookupBaseInterfacesCache (Type t)
399 Type [] ifaces = GetInterfaces (t);
401 if (ifaces != null && ifaces.Length == 1)
402 return LookupMemberCache (ifaces [0]);
404 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
405 MemberCache cache = builder_to_member_cache [t] as MemberCache;
409 cache = new MemberCache (ifaces);
410 builder_to_member_cache.Add (t, cache);
414 public static TypeContainer LookupInterface (Type t)
416 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
417 if ((tc == null) || (tc.Kind != Kind.Interface))
423 public static Delegate LookupDelegate (Type t)
425 return builder_to_declspace [t] as Delegate;
428 public static Class LookupClass (Type t)
430 return (Class) builder_to_declspace [t];
434 // We use this hash for multiple kinds of constructed types:
436 // (T, "&") Given T, get T &
437 // (T, "*") Given T, get T *
438 // (T, "[]") Given T and a array dimension, get T []
439 // (T, X) Given a type T and a simple name X, get the type T+X
441 // Accessibility tests, if necessary, should be done by the user
443 static DoubleHash type_hash = new DoubleHash ();
446 // Gets the reference to T version of the Type (T&)
448 public static Type GetReferenceType (Type t)
451 return t.MakeByRefType ();
453 return GetConstructedType (t, "&");
458 // Gets the pointer to T version of the Type (T*)
460 public static Type GetPointerType (Type t)
462 return GetConstructedType (t, "*");
465 public static Type GetConstructedType (Type t, string dim)
468 if (type_hash.Lookup (t, dim, out ret))
471 ret = t.Module.GetType (t.ToString () + dim);
473 type_hash.Insert (t, dim, ret);
478 ret = GetReferenceType (t);
479 type_hash.Insert (t, dim, ret);
484 if (t.IsGenericParameter || t.IsGenericType) {
487 while ((pos < dim.Length) && (dim [pos] == '[')) {
490 if (dim [pos] == ']') {
491 result = result.MakeArrayType ();
494 if (pos < dim.Length)
497 type_hash.Insert (t, dim, result);
502 while (dim [pos] == ',') {
506 if ((dim [pos] != ']') || (pos != dim.Length-1))
509 result = result.MakeArrayType (rank + 1);
510 type_hash.Insert (t, dim, result);
516 type_hash.Insert (t, dim, null);
520 public static CustomAttributeBuilder GetCompilerGeneratedAttribute (Location loc)
522 if (compiler_generated_attr != null)
523 return compiler_generated_attr;
525 Type t = TypeManager.CoreLookupType (
526 "System.Runtime.CompilerServices", "CompilerGeneratedAttribute", Kind.Class, true);
528 // TODO: it cannot be null
532 compiler_generated_attr = new CustomAttributeBuilder (
533 GetPredefinedConstructor (t, loc, Type.EmptyTypes), new object[0]);
535 return compiler_generated_attr;
538 public static Type GetNestedType (Type t, string name)
541 if (!type_hash.Lookup (t, name, out ret)) {
542 ret = t.GetNestedType (name,
543 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
544 type_hash.Insert (t, name, ret);
550 /// Fills static table with exported types from all referenced assemblies.
551 /// This information is required for CLS Compliance tests.
553 public static void LoadAllImportedTypes ()
555 AllClsTopLevelTypes = new Hashtable (1500);
556 foreach (Assembly a in RootNamespace.Global.Assemblies) {
557 foreach (Type t in a.GetExportedTypes ()) {
558 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
563 public static bool NamespaceClash (string name, Location loc)
565 if (! RootNamespace.Global.IsNamespace (name))
568 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
573 /// Returns the C# name of a type if possible, or the full type name otherwise
575 static public string CSharpName (Type t)
580 if (t == typeof (ArglistParameter))
583 if (t == typeof (AnonymousMethod))
584 return "anonymous method";
586 return CSharpName (GetFullName (t));
589 static readonly char [] elements = new char [] { '*', '[' };
591 public static string CSharpName (string name)
593 if (name.Length > 10) {
595 case "System.Int32": return "int";
596 case "System.Int64": return "long";
597 case "System.String": return "string";
598 case "System.Boolean": return "bool";
599 case "System.Void": return "void";
600 case "System.Object": return "object";
601 case "System.UInt32": return "uint";
602 case "System.Int16": return "short";
603 case "System.UInt16": return "ushort";
604 case "System.UInt64": return "ulong";
605 case "System.Single": return "float";
606 case "System.Double": return "double";
607 case "System.Decimal": return "decimal";
608 case "System.Char": return "char";
609 case "System.Byte": return "byte";
610 case "System.SByte": return "sbyte";
613 int idx = name.IndexOfAny (elements, 10);
615 return CSharpName (name.Substring (0, idx)) + name.Substring (idx);
618 if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
619 return AnonymousTypeClass.SignatureForError;
621 return name.Replace ('+', '.');
624 static public string CSharpName (Type[] types)
626 if (types.Length == 0)
629 StringBuilder sb = new StringBuilder ();
630 for (int i = 0; i < types.Length; ++i) {
634 sb.Append (CSharpName (types [i]));
636 return sb.ToString ();
639 // Used for error reporting to show symbolic name instead of underlying value
640 public static string CSharpEnumValue (Type t, object value)
642 t = DropGenericTypeArguments (t);
643 Enum e = LookupDeclSpace (t) as Enum;
645 return System.Enum.GetName (t, value);
647 return e.GetDefinition (value).GetSignatureForError ();
651 /// Returns the signature of the method with full namespace classification
653 static public string GetFullNameSignature (MemberInfo mi)
655 PropertyInfo pi = mi as PropertyInfo;
657 MethodBase pmi = pi.GetGetMethod (true);
659 pmi = pi.GetSetMethod (true);
660 if (GetParameterData (pmi).Count > 0)
663 return (mi is MethodBase)
664 ? CSharpSignature (mi as MethodBase)
665 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
669 private static int GetFullName (Type t, StringBuilder sb)
673 if (!t.IsGenericType) {
674 sb.Append (t.FullName);
678 if (t.DeclaringType != null) {
679 pos = GetFullName (t.DeclaringType, sb);
681 } else if (t.Namespace != null && t.Namespace.Length != 0) {
682 sb.Append (t.Namespace);
685 sb.Append (RemoveGenericArity (t.Name));
687 Type[] this_args = GetTypeArguments (t);
689 if (this_args.Length < pos)
690 throw new InternalErrorException (
691 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
692 if (this_args.Length == pos)
697 sb.Append (CSharpName (this_args [pos++]));
698 if (pos == this_args.Length)
706 static string GetFullName (Type t)
709 string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
710 return GetFullName (t.GetElementType ()) + dimension;
713 if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
714 t = GetTypeArguments (t)[0];
715 return CSharpName (t) + "?";
718 if (t.IsGenericParameter)
720 if (!t.IsGenericType)
723 StringBuilder sb = new StringBuilder ();
724 int pos = GetFullName (t, sb);
726 throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
727 return sb.ToString ();
730 public static string GetFullName (Type t)
736 public static string RemoveGenericArity (string from)
738 int i = from.IndexOf ('`');
740 return from.Substring (0, i);
745 /// When we need to report accessors as well
747 static public string CSharpSignature (MethodBase mb)
749 return CSharpSignature (mb, false);
753 /// Returns the signature of the method
755 static public string CSharpSignature (MethodBase mb, bool show_accessor)
757 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
760 ParameterData iparams = GetParameterData (mb);
761 string parameters = iparams.GetSignatureForError ();
762 int accessor_end = 0;
764 if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
765 Operator.OpType ot = Operator.GetOperatorType (mb.Name);
766 if (ot != Operator.OpType.TOP) {
767 sig.Append ("operator ");
768 sig.Append (Operator.GetName (ot));
769 sig.Append (parameters);
770 return sig.ToString ();
773 bool is_getter = mb.Name.StartsWith ("get_");
774 bool is_setter = mb.Name.StartsWith ("set_");
775 if (is_getter || is_setter || mb.Name.StartsWith ("add_")) {
777 } else if (mb.Name.StartsWith ("remove_")) {
782 if (iparams.Count > (is_getter ? 0 : 1)) {
783 sig.Append ("this[");
785 sig.Append (parameters.Substring (1, parameters.Length - 2));
787 sig.Append (parameters.Substring (1, parameters.LastIndexOf (',') - 1));
790 sig.Append (mb.Name.Substring (accessor_end + 1));
793 if (mb.Name == ".ctor")
794 sig.Append (RemoveGenericArity (mb.DeclaringType.Name));
796 sig.Append (mb.Name);
799 if (TypeManager.IsGenericMethod (mb)) {
800 Type[] args = mb.GetGenericArguments ();
802 for (int i = 0; i < args.Length; i++) {
805 sig.Append (CSharpName (args [i]));
812 sig.Append (parameters);
815 if (show_accessor && accessor_end > 0) {
817 sig.Append (mb.Name.Substring (0, accessor_end));
820 return sig.ToString ();
823 public static string GetMethodName (MethodInfo m)
826 if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
829 return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
835 static public string CSharpSignature (EventInfo ei)
837 return CSharpName (ei.DeclaringType) + "." + ei.Name;
841 // Looks up a type, and aborts if it is not found. This is used
842 // by predefined types required by the compiler
844 public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
847 if (RootContext.StdLib) {
848 Namespace ns = RootNamespace.Global.GetNamespace (ns_name, true);
849 expr = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
852 Report.DisableReporting ();
854 TypeLookupExpression tle = new TypeLookupExpression (ns_name + "." + name);
855 expr = tle.ResolveAsTypeTerminal (RootContext.ToplevelTypes, false);
858 Report.EnableReporting ();
863 Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
870 if (RootContext.StdLib || t == null || !required)
873 // TODO: All predefined imported types have to have correct signature
874 if (t.Module != CodeGen.Module.Builder)
877 DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
878 if (ds is Delegate) {
879 if (type_kind == Kind.Delegate)
882 TypeContainer tc = (TypeContainer)ds;
883 if (tc.Kind == type_kind)
887 Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
892 static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
894 const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
896 MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
897 if (members != null) {
898 for (int i = 0; i < members.Length; ++i) {
899 MemberInfo member = members [i];
900 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
901 MethodBase mb = member as MethodBase;
905 ParameterData pd = TypeManager.GetParameterData (mb);
906 if (IsEqual (pd.Types, args))
909 if (mt == MemberTypes.Field) {
910 FieldInfo fi = member as FieldInfo;
914 if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
920 if (mt == MemberTypes.Property) {
921 PropertyInfo pi = member as PropertyInfo;
925 if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
933 string method_args = null;
934 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
935 method_args = "(" + TypeManager.CSharpName (args) + ")";
937 Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
938 TypeManager.CSharpName (t), name, method_args);
944 // Returns the ConstructorInfo for "args"
946 public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
948 return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
952 // Returns the MethodInfo for a method named `name' defined
953 // in type `t' which takes arguments of types `args'
955 public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
957 return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
960 public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
962 return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
965 public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
967 return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
971 /// The types have to be initialized after the initial
972 /// population of the type has happened (for example, to
973 /// bootstrap the corlib.dll
975 public static bool InitCoreTypes ()
977 object_type = CoreLookupType ("System", "Object", Kind.Class, true);
978 system_object_expr.Type = object_type;
979 value_type = CoreLookupType ("System", "ValueType", Kind.Class, true);
980 system_valuetype_expr.Type = value_type;
981 attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
983 int32_type = CoreLookupType ("System", "Int32", Kind.Struct, true);
984 int64_type = CoreLookupType ("System", "Int64", Kind.Struct, true);
985 uint32_type = CoreLookupType ("System", "UInt32", Kind.Struct, true);
986 uint64_type = CoreLookupType ("System", "UInt64", Kind.Struct, true);
987 byte_type = CoreLookupType ("System", "Byte", Kind.Struct, true);
988 sbyte_type = CoreLookupType ("System", "SByte", Kind.Struct, true);
989 short_type = CoreLookupType ("System", "Int16", Kind.Struct, true);
990 ushort_type = CoreLookupType ("System", "UInt16", Kind.Struct, true);
992 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
993 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
994 idisposable_type = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
996 // HACK: DefineType immediately resolves iterators (very wrong)
997 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
999 char_type = CoreLookupType ("System", "Char", Kind.Struct, true);
1000 string_type = CoreLookupType ("System", "String", Kind.Class, true);
1001 float_type = CoreLookupType ("System", "Single", Kind.Struct, true);
1002 double_type = CoreLookupType ("System", "Double", Kind.Struct, true);
1003 decimal_type = CoreLookupType ("System", "Decimal", Kind.Struct, true);
1004 bool_type = CoreLookupType ("System", "Boolean", Kind.Struct, true);
1005 intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
1006 uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
1008 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
1009 delegate_type = CoreLookupType ("System", "Delegate", Kind.Class, true);
1011 enum_type = CoreLookupType ("System", "Enum", Kind.Class, true);
1012 array_type = CoreLookupType ("System", "Array", Kind.Class, true);
1013 void_type = CoreLookupType ("System", "Void", Kind.Struct, true);
1014 type_type = CoreLookupType ("System", "Type", Kind.Class, true);
1015 exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
1017 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
1018 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
1020 param_array_type = CoreLookupType ("System", "ParamArrayAttribute", Kind.Class, true);
1021 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute", Kind.Class, true);
1023 return Report.Errors == 0;
1027 // Initializes optional core types
1029 public static void InitOptionalCoreTypes ()
1031 void_ptr_type = GetPointerType (void_type);
1032 char_ptr_type = GetPointerType (char_type);
1035 // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
1036 // types cache with incorrect accessiblity when any of optional types is internal.
1038 internals_visible_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute", Kind.Class, false);
1040 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
1041 asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
1042 iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
1043 typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
1044 arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
1045 mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
1048 // Optional attributes, used for error reporting only
1050 obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute", Kind.Class, false);
1051 if (obsolete_attribute_type != null) {
1052 Class c = TypeManager.LookupClass (obsolete_attribute_type);
1057 dllimport_type = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute", Kind.Class, false);
1058 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute", Kind.Class, false);
1059 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute", Kind.Class, false);
1060 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "InAttribute", Kind.Class, false);
1061 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute", Kind.Class, false);
1062 conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute", Kind.Class, false);
1063 cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute", Kind.Class, false);
1064 security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute", Kind.Class, false);
1065 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute", Kind.Class, false);
1066 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute", Kind.Class, false);
1067 assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute", Kind.Class, false);
1068 assembly_version_attribute_type = CoreLookupType ("System.Reflection", "AssemblyVersionAttribute", Kind.Class, false);
1069 comimport_attr_type = CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute", Kind.Class, false);
1070 coclass_attr_type = CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute", Kind.Class, false);
1071 attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute", Kind.Class, false);
1072 default_parameter_value_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultParameterValueAttribute", Kind.Class, false);
1075 default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute", Kind.Class, false);
1076 type_forwarder_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "TypeForwardedToAttribute", Kind.Class, false);
1077 generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
1078 generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
1079 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
1080 generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
1083 // Optional types which are used as types and for member lookup
1085 default_member_type = CoreLookupType ("System.Reflection", "DefaultMemberAttribute", Kind.Class, false);
1086 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
1087 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute", Kind.Class, false);
1088 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, false);
1089 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute", Kind.Class, false);
1092 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, false);
1095 extension_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "ExtensionAttribute", Kind.Class, false);
1096 expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
1098 if (!RootContext.StdLib) {
1100 // HACK: When building Mono corlib mcs uses loaded mscorlib which
1101 // has different predefined types and this method sets mscorlib types
1102 // to be same to avoid any type check errors.
1105 Type type = typeof (Type);
1106 Type [] system_4_type_arg = { type, type, type, type };
1108 MethodInfo set_corlib_type_builders =
1109 typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
1110 "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
1111 system_4_type_arg, null);
1113 if (set_corlib_type_builders != null) {
1114 object[] args = new object [4];
1115 args [0] = object_type;
1116 args [1] = value_type;
1117 args [2] = enum_type;
1118 args [3] = void_type;
1120 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1122 Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
1123 TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
1124 TypeManager.CSharpName (system_4_type_arg));
1128 system_string_expr.Type = string_type;
1129 system_boolean_expr.Type = bool_type;
1130 system_decimal_expr.Type = decimal_type;
1131 system_single_expr.Type = float_type;
1132 system_double_expr.Type = double_type;
1133 system_sbyte_expr.Type = sbyte_type;
1134 system_byte_expr.Type = byte_type;
1135 system_int16_expr.Type = short_type;
1136 system_uint16_expr.Type = ushort_type;
1137 system_int32_expr.Type = int32_type;
1138 system_uint32_expr.Type = uint32_type;
1139 system_int64_expr.Type = int64_type;
1140 system_uint64_expr.Type = uint64_type;
1141 system_char_expr.Type = char_type;
1142 system_void_expr.Type = void_type;
1145 // These are only used for compare purposes
1147 anonymous_method_type = typeof (AnonymousMethod);
1148 null_type = typeof (NullLiteral);
1151 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1154 /// This is the "old", non-cache based FindMembers() function. We cannot use
1155 /// the cache here because there is no member name argument.
1157 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1158 MemberFilter filter, object criteria)
1160 #if MS_COMPATIBLE && GMCS_SOURCE
1161 if (t.IsGenericType)
1162 t = t.GetGenericTypeDefinition ();
1165 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1168 // `builder_to_declspace' contains all dynamic types.
1172 Timer.StartTimer (TimerType.FindMembers);
1173 list = decl.FindMembers (mt, bf, filter, criteria);
1174 Timer.StopTimer (TimerType.FindMembers);
1179 // We have to take care of arrays specially, because GetType on
1180 // a TypeBuilder array will return a Type, not a TypeBuilder,
1181 // and we can not call FindMembers on this type.
1184 #if MS_COMPATIBLE && GMCS_SOURCE
1187 t.IsSubclassOf (TypeManager.array_type))
1188 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1191 if (t is GenericTypeParameterBuilder) {
1192 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1194 Timer.StartTimer (TimerType.FindMembers);
1195 MemberList list = tparam.FindMembers (
1196 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1197 Timer.StopTimer (TimerType.FindMembers);
1203 // Since FindMembers will not lookup both static and instance
1204 // members, we emulate this behaviour here.
1206 if ((bf & instance_and_static) == instance_and_static){
1207 MemberInfo [] i_members = t.FindMembers (
1208 mt, bf & ~BindingFlags.Static, filter, criteria);
1210 int i_len = i_members.Length;
1212 MemberInfo one = i_members [0];
1215 // If any of these are present, we are done!
1217 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1218 return new MemberList (i_members);
1221 MemberInfo [] s_members = t.FindMembers (
1222 mt, bf & ~BindingFlags.Instance, filter, criteria);
1224 int s_len = s_members.Length;
1225 if (i_len > 0 || s_len > 0)
1226 return new MemberList (i_members, s_members);
1229 return new MemberList (i_members);
1231 return new MemberList (s_members);
1235 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1240 /// This method is only called from within MemberLookup. It tries to use the member
1241 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1242 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1243 /// our return value will already contain all inherited members and the caller don't need
1244 /// to check base classes and interfaces anymore.
1246 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1247 string name, out bool used_cache)
1252 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1253 // and we can ask the DeclSpace for the MemberCache.
1256 if (t.Assembly == CodeGen.Assembly.Builder) {
1257 if (t.IsGenericParameter) {
1258 TypeParameter tparam = (TypeParameter) builder_to_type_param[t];
1261 if (tparam.MemberCache == null)
1262 return new MemberInfo[0];
1264 return tparam.MemberCache.FindMembers (
1265 mt, bf, name, FilterWithClosure_delegate, null);
1268 if (t.IsGenericType && !t.IsGenericTypeDefinition)
1269 t = t.GetGenericTypeDefinition ();
1271 if (t is TypeBuilder) {
1273 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1274 cache = decl.MemberCache;
1277 // If this DeclSpace has a MemberCache, use it.
1280 if (cache != null) {
1282 return cache.FindMembers (
1283 mt, bf, name, FilterWithClosure_delegate, null);
1286 // If there is no MemberCache, we need to use the "normal" FindMembers.
1287 // Note, this is a VERY uncommon route!
1290 Timer.StartTimer (TimerType.FindMembers);
1291 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1292 FilterWithClosure_delegate, name);
1293 Timer.StopTimer (TimerType.FindMembers);
1295 return (MemberInfo []) list;
1299 // We have to take care of arrays specially, because GetType on
1300 // a TypeBuilder array will return a Type, not a TypeBuilder,
1301 // and we can not call FindMembers on this type.
1305 return TypeHandle.ArrayType.MemberCache.FindMembers (
1306 mt, bf, name, FilterWithClosure_delegate, null);
1310 if (t is GenericTypeParameterBuilder) {
1311 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1314 if (tparam.MemberCache == null)
1315 return new MemberInfo [0];
1317 return tparam.MemberCache.FindMembers (
1318 mt, bf, name, FilterWithClosure_delegate, null);
1322 if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
1324 // This happens if we're resolving a class'es base class and interfaces
1325 // in TypeContainer.DefineType(). At this time, the types aren't
1326 // populated yet, so we can't use the cache.
1328 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1329 FilterWithClosure_delegate, name);
1335 // This call will always succeed. There is exactly one TypeHandle instance per
1336 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1337 // the corresponding MemberCache.
1339 cache = TypeHandle.GetMemberCache (t);
1342 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1345 public static bool IsBuiltinType (Type t)
1347 t = TypeToCoreType (t);
1348 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1349 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1350 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1351 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1358 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1359 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1361 public static bool IsPrimitiveType (Type t)
1363 return (t == int32_type || t == uint32_type ||
1364 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1365 t == char_type || t == short_type || t == bool_type ||
1366 t == sbyte_type || t == byte_type || t == ushort_type);
1369 public static bool IsDelegateType (Type t)
1372 if (t.IsGenericParameter)
1376 if (t == TypeManager.delegate_type)
1379 t = DropGenericTypeArguments (t);
1380 return IsSubclassOf (t, TypeManager.delegate_type);
1383 public static bool IsEnumType (Type t)
1385 t = DropGenericTypeArguments (t);
1386 return t.BaseType == TypeManager.enum_type;
1389 public static bool IsBuiltinOrEnum (Type t)
1391 if (IsBuiltinType (t))
1400 public static bool IsAttributeType (Type t)
1402 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1405 static Stack unmanaged_enclosing_types = new Stack (4);
1408 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1410 public static bool IsUnmanagedType (Type t)
1412 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1413 if (unmanaged_enclosing_types.Contains (t))
1416 // builtins that are not unmanaged types
1417 if (t == TypeManager.object_type || t == TypeManager.string_type)
1420 if (IsGenericType (t) || IsGenericParameter (t))
1423 if (IsBuiltinOrEnum (t))
1426 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1430 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1434 if (!IsValueType (t))
1438 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1439 if (p.IsGenericTypeDefinition)
1444 unmanaged_enclosing_types.Push (t);
1448 if (t is TypeBuilder) {
1449 TypeContainer tc = LookupTypeContainer (t);
1450 if (tc.Fields != null){
1451 foreach (FieldBase f in tc.Fields){
1452 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1453 if ((f.ModFlags & Modifiers.STATIC) != 0)
1455 if (f.MemberType == null)
1457 if (!IsUnmanagedType (f.MemberType)){
1458 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1464 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1466 foreach (FieldInfo f in fields){
1467 if (!IsUnmanagedType (f.FieldType)){
1468 Report.SymbolRelatedToPreviousError (f);
1474 unmanaged_enclosing_types.Pop ();
1479 public static bool IsReferenceType (Type t)
1481 if (TypeManager.IsGenericParameter (t)) {
1482 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1483 if (constraints == null)
1486 return constraints.IsReferenceType;
1489 if (t == TypeManager.null_type)
1492 return !t.IsValueType;
1495 public static bool IsValueType (Type t)
1497 return t.IsValueType || IsGenericParameter (t);
1500 public static bool IsInterfaceType (Type t)
1502 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1506 return tc.Kind == Kind.Interface;
1509 public static bool IsSubclassOf (Type type, Type base_type)
1511 TypeParameter tparam = LookupTypeParameter (type);
1512 TypeParameter pparam = LookupTypeParameter (base_type);
1514 if ((tparam != null) && (pparam != null)) {
1515 if (tparam == pparam)
1518 return tparam.IsSubclassOf (base_type);
1521 #if MS_COMPATIBLE && GMCS_SOURCE
1522 if (type.IsGenericType)
1523 type = type.GetGenericTypeDefinition ();
1526 if (type.IsSubclassOf (base_type))
1530 if (IsEqual (type, base_type))
1533 type = type.BaseType;
1534 } while (type != null);
1539 public static bool IsPrivateAccessible (Type type, Type parent)
1544 if (type.Equals (parent))
1547 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1550 public static bool IsFamilyAccessible (Type type, Type parent)
1552 TypeParameter tparam = LookupTypeParameter (type);
1553 TypeParameter pparam = LookupTypeParameter (parent);
1555 if ((tparam != null) && (pparam != null)) {
1556 if (tparam == pparam)
1559 return tparam.IsSubclassOf (parent);
1563 if (IsInstantiationOfSameGenericType (type, parent))
1566 type = type.BaseType;
1567 } while (type != null);
1573 // Checks whether `type' is a subclass or nested child of `base_type'.
1575 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1578 if (IsFamilyAccessible (type, base_type))
1581 // Handle nested types.
1582 type = type.DeclaringType;
1583 } while (type != null);
1589 // Checks whether `type' is a nested child of `parent'.
1591 public static bool IsNestedChildOf (Type type, Type parent)
1596 type = DropGenericTypeArguments (type);
1597 parent = DropGenericTypeArguments (parent);
1599 if (IsEqual (type, parent))
1602 type = type.DeclaringType;
1603 while (type != null) {
1604 if (IsEqual (type, parent))
1607 type = type.DeclaringType;
1614 // Checks whether `extern_type' is friend of the output assembly
1616 public static bool IsThisOrFriendAssembly (Assembly assembly)
1618 if (assembly == CodeGen.Assembly.Builder)
1621 if (assembly_internals_vis_attrs.Contains (assembly))
1622 return (bool)(assembly_internals_vis_attrs [assembly]);
1624 if (internals_visible_attr_type == null)
1627 object [] attrs = assembly.GetCustomAttributes (internals_visible_attr_type, false);
1628 if (attrs.Length == 0) {
1629 assembly_internals_vis_attrs.Add (assembly, false);
1633 bool is_friend = false;
1635 AssemblyName this_name = CodeGen.Assembly.Name;
1636 byte [] this_token = this_name.GetPublicKeyToken ();
1637 foreach (InternalsVisibleToAttribute attr in attrs) {
1638 if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1641 AssemblyName aname = null;
1643 aname = new AssemblyName (attr.AssemblyName);
1644 } catch (FileLoadException) {
1645 } catch (ArgumentException) {
1648 if (aname == null || aname.Name != this_name.Name)
1651 byte [] key_token = aname.GetPublicKeyToken ();
1652 if (key_token != null) {
1653 if (this_token.Length == 0) {
1654 // Same name, but assembly is not strongnamed
1655 Error_FriendAccessNameNotMatching (aname.FullName);
1659 if (!CompareKeyTokens (this_token, key_token))
1667 assembly_internals_vis_attrs.Add (assembly, is_friend);
1672 static bool CompareKeyTokens (byte [] token1, byte [] token2)
1674 for (int i = 0; i < token1.Length; i++)
1675 if (token1 [i] != token2 [i])
1681 static void Error_FriendAccessNameNotMatching (string other_name)
1683 Report.Error (281, "Friend access was granted to `" + other_name +
1684 "', but the output assembly is named `" + CodeGen.Assembly.Name.FullName +
1685 "'. Try adding a reference to `" + other_name +
1686 "' or change the output assembly name to match it");
1691 // Do the right thing when returning the element type of an
1692 // array type based on whether we are compiling corlib or not
1694 public static Type GetElementType (Type t)
1696 if (RootContext.StdLib)
1697 return t.GetElementType ();
1699 return TypeToCoreType (t.GetElementType ());
1703 /// This method is not implemented by MS runtime for dynamic types
1705 public static bool HasElementType (Type t)
1707 return t.IsArray || t.IsPointer || t.IsByRef;
1710 public static Type GetEnumUnderlyingType (Type t)
1712 t = DropGenericTypeArguments (t);
1713 Enum e = LookupTypeContainer (t) as Enum;
1715 return e.UnderlyingType;
1718 FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null);
1720 return TypeManager.int32_type;
1722 return TypeToCoreType (fi.FieldType);
1726 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1730 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1731 /// for anything which is dynamic, and we need this in a number of places,
1732 /// we register this information here, and use it afterwards.
1734 static public void RegisterMethod (MethodBase mb, Parameters ip)
1736 method_params.Add (mb, ip);
1739 static public ParameterData GetParameterData (MethodBase mb)
1741 ParameterData pd = (ParameterData)method_params [mb];
1744 if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
1745 MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
1746 pd = GetParameterData (mi);
1747 if (mi.IsGenericMethod)
1748 pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
1750 pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
1751 method_params.Add (mb, pd);
1755 if (mb.DeclaringType.Assembly == CodeGen.Assembly.Builder) {
1756 throw new InternalErrorException ("Parameters are not registered for method `{0}'",
1757 TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
1760 pd = new ReflectionParameters (mb);
1761 method_params.Add (mb, pd);
1766 public static ParameterData GetDelegateParameters (Type t)
1768 Delegate d = builder_to_declspace [t] as Delegate;
1770 return d.Parameters;
1772 MethodInfo invoke_mb = Delegate.GetInvokeMethod (t, t);
1773 return GetParameterData (invoke_mb);
1776 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1778 if (!method_overrides.Contains (override_method))
1779 method_overrides [override_method] = base_method;
1780 if (method_overrides [override_method] != base_method)
1781 throw new InternalErrorException ("Override mismatch: " + override_method);
1784 static public bool IsOverride (MethodBase m)
1786 m = DropGenericMethodArguments (m);
1788 return m.IsVirtual &&
1789 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1790 (m is MethodBuilder || method_overrides.Contains (m));
1793 static public MethodBase TryGetBaseDefinition (MethodBase m)
1795 m = DropGenericMethodArguments (m);
1797 return (MethodBase) method_overrides [m];
1801 /// Returns the argument types for an indexer based on its PropertyInfo
1803 /// For dynamic indexers, we use the compiler provided types, for
1804 /// indexers from existing assemblies we load them from GetParameters,
1805 /// and insert them into the cache
1807 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1809 if (indexer_arguments.Contains (indexer))
1810 return (Type []) indexer_arguments [indexer];
1811 else if (indexer is PropertyBuilder)
1812 // If we're a PropertyBuilder and not in the
1813 // `indexer_arguments' hash, then we're a property and
1815 return Type.EmptyTypes;
1817 ParameterInfo [] pi = indexer.GetIndexParameters ();
1818 // Property, not an indexer.
1820 return Type.EmptyTypes;
1822 Type [] types = new Type [c];
1824 for (int i = 0; i < c; i++)
1825 types [i] = pi [i].ParameterType;
1827 indexer_arguments.Add (indexer, types);
1832 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1834 fields.Add (fb, ic);
1837 public static IConstant GetConstant (FieldInfo fb)
1842 return (IConstant)fields [fb];
1845 public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
1847 propertybuilder_to_property.Add (pi, pb);
1850 public static PropertyBase GetProperty (PropertyInfo pi)
1852 return (PropertyBase)propertybuilder_to_property [pi];
1855 static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
1857 fieldbuilders_to_fields.Add (fb, f);
1861 // The return value can be null; This will be the case for
1862 // auxiliary FieldBuilders created by the compiler that have no
1863 // real field being declared on the source code
1865 static public FieldBase GetField (FieldInfo fb)
1868 fb = GetGenericFieldDefinition (fb);
1870 return (FieldBase) fieldbuilders_to_fields [fb];
1873 static public MethodInfo GetAddMethod (EventInfo ei)
1875 if (ei is MyEventBuilder) {
1876 return ((MyEventBuilder)ei).GetAddMethod (true);
1878 return ei.GetAddMethod (true);
1881 static public MethodInfo GetRemoveMethod (EventInfo ei)
1883 if (ei is MyEventBuilder) {
1884 return ((MyEventBuilder)ei).GetRemoveMethod (true);
1886 return ei.GetRemoveMethod (true);
1889 static public void RegisterEventField (EventInfo einfo, EventField e)
1892 events = new Hashtable ();
1894 events.Add (einfo, e);
1897 static public EventField GetEventField (EventInfo ei)
1902 return (EventField) events [ei];
1905 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1906 MethodBase set, Type[] args)
1908 indexer_arguments.Add (pb, args);
1913 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1915 Hashtable hash = new Hashtable ();
1916 return CheckStructCycles (tc, seen, hash);
1919 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1922 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
1926 // `seen' contains all types we've already visited.
1928 if (seen.Contains (tc))
1930 seen.Add (tc, null);
1932 if (tc.Fields == null)
1935 foreach (FieldBase field in tc.Fields) {
1936 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1939 Type ftype = field.FieldBuilder.FieldType;
1940 TypeContainer ftc = LookupTypeContainer (ftype);
1944 if (hash.Contains (ftc)) {
1945 Report.Error (523, tc.Location,
1946 "Struct member `{0}.{1}' of type `{2}' " +
1947 "causes a cycle in the struct layout",
1948 tc.Name, field.Name, ftc.Name);
1953 // `hash' contains all types in the current path.
1955 hash.Add (tc, null);
1957 bool ok = CheckStructCycles (ftc, seen, hash);
1964 if (!seen.Contains (ftc))
1965 seen.Add (ftc, null);
1972 /// Given an array of interface types, expand and eliminate repeated ocurrences
1973 /// of an interface.
1977 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1980 public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
1982 ArrayList new_ifaces = new ArrayList ();
1984 foreach (TypeExpr iface in base_interfaces){
1985 Type itype = iface.Type;
1987 if (new_ifaces.Contains (itype))
1990 new_ifaces.Add (itype);
1992 Type [] implementing = GetInterfaces (itype);
1994 foreach (Type imp in implementing){
1995 if (!new_ifaces.Contains (imp))
1996 new_ifaces.Add (imp);
1999 Type [] ret = new Type [new_ifaces.Count];
2000 new_ifaces.CopyTo (ret, 0);
2004 public static Type[] ExpandInterfaces (Type [] base_interfaces)
2006 ArrayList new_ifaces = new ArrayList ();
2008 foreach (Type itype in base_interfaces){
2009 if (new_ifaces.Contains (itype))
2012 new_ifaces.Add (itype);
2014 Type [] implementing = GetInterfaces (itype);
2016 foreach (Type imp in implementing){
2017 if (!new_ifaces.Contains (imp))
2018 new_ifaces.Add (imp);
2021 Type [] ret = new Type [new_ifaces.Count];
2022 new_ifaces.CopyTo (ret, 0);
2026 static PtrHashtable iface_cache = new PtrHashtable ();
2029 /// This function returns the interfaces in the type `t'. Works with
2030 /// both types and TypeBuilders.
2032 public static Type [] GetInterfaces (Type t)
2034 Type [] cached = iface_cache [t] as Type [];
2039 // The reason for catching the Array case is that Reflection.Emit
2040 // will not return a TypeBuilder for Array types of TypeBuilder types,
2041 // but will still throw an exception if we try to call GetInterfaces
2044 // Since the array interfaces are always constant, we return those for
2049 t = TypeManager.array_type;
2051 if ((t is TypeBuilder) || IsGenericType (t)) {
2052 Type [] base_ifaces;
2054 if (t.BaseType == null)
2055 base_ifaces = Type.EmptyTypes;
2057 base_ifaces = GetInterfaces (t.BaseType);
2059 if (IsGenericType (t))
2060 #if MS_COMPATIBLE && GMCS_SOURCE
2061 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
2063 type_ifaces = t.GetInterfaces ();
2066 type_ifaces = (Type []) builder_to_ifaces [t];
2067 if (type_ifaces == null || type_ifaces.Length == 0)
2068 type_ifaces = Type.EmptyTypes;
2070 int base_count = base_ifaces.Length;
2071 Type [] result = new Type [base_count + type_ifaces.Length];
2072 base_ifaces.CopyTo (result, 0);
2073 type_ifaces.CopyTo (result, base_count);
2075 iface_cache [t] = result;
2078 } else if (t is GenericTypeParameterBuilder){
2079 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2080 if (type_ifaces == null || type_ifaces.Length == 0)
2081 type_ifaces = Type.EmptyTypes;
2083 iface_cache [t] = type_ifaces;
2087 Type[] ifaces = t.GetInterfaces ();
2088 iface_cache [t] = ifaces;
2094 // gets the interfaces that are declared explicitly on t
2096 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2098 return (Type []) builder_to_ifaces [t];
2102 /// The following is used to check if a given type implements an interface.
2103 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2105 public static bool ImplementsInterface (Type t, Type iface)
2110 // FIXME OPTIMIZATION:
2111 // as soon as we hit a non-TypeBuiler in the interface
2112 // chain, we could return, as the `Type.GetInterfaces'
2113 // will return all the interfaces implement by the type
2117 interfaces = GetInterfaces (t);
2119 if (interfaces != null){
2120 foreach (Type i in interfaces){
2127 } while (t != null);
2132 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2134 // This is a custom version of Convert.ChangeType() which works
2135 // with the TypeBuilder defined types when compiling corlib.
2136 public static object ChangeType (object value, Type conversionType, out bool error)
2138 IConvertible convert_value = value as IConvertible;
2140 if (convert_value == null){
2147 // We must use Type.Equals() here since `conversionType' is
2148 // the TypeBuilder created version of a system type and not
2149 // the system type itself. You cannot use Type.GetTypeCode()
2150 // on such a type - it'd always return TypeCode.Object.
2153 // We cannot rely on build-in type conversions as they are
2154 // more limited than what C# supports.
2155 // See char -> float/decimal/double conversion
2160 if (conversionType.Equals (typeof (Boolean)))
2161 return (object)(convert_value.ToBoolean (nf_provider));
2162 if (conversionType.Equals (typeof (Byte)))
2163 return (object)(convert_value.ToByte (nf_provider));
2164 if (conversionType.Equals (typeof (Char)))
2165 return (object)(convert_value.ToChar (nf_provider));
2166 if (conversionType.Equals (typeof (DateTime)))
2167 return (object)(convert_value.ToDateTime (nf_provider));
2169 if (conversionType.Equals (decimal_type)) {
2170 if (convert_value.GetType () == TypeManager.char_type)
2171 return (decimal)convert_value.ToInt32 (nf_provider);
2172 return convert_value.ToDecimal (nf_provider);
2175 if (conversionType.Equals (typeof (Double))) {
2176 if (convert_value.GetType () == TypeManager.char_type)
2177 return (double)convert_value.ToInt32 (nf_provider);
2178 return convert_value.ToDouble (nf_provider);
2181 if (conversionType.Equals (typeof (Int16)))
2182 return (object)(convert_value.ToInt16 (nf_provider));
2183 if (conversionType.Equals (int32_type))
2184 return (object)(convert_value.ToInt32 (nf_provider));
2185 if (conversionType.Equals (int64_type))
2186 return (object)(convert_value.ToInt64 (nf_provider));
2187 if (conversionType.Equals (typeof (SByte)))
2188 return (object)(convert_value.ToSByte (nf_provider));
2190 if (conversionType.Equals (typeof (Single))) {
2191 if (convert_value.GetType () == TypeManager.char_type)
2192 return (float)convert_value.ToInt32 (nf_provider);
2193 return convert_value.ToSingle (nf_provider);
2196 if (conversionType.Equals (typeof (String)))
2197 return (object)(convert_value.ToString (nf_provider));
2198 if (conversionType.Equals (typeof (UInt16)))
2199 return (object)(convert_value.ToUInt16 (nf_provider));
2200 if (conversionType.Equals (typeof (UInt32)))
2201 return (object)(convert_value.ToUInt32 (nf_provider));
2202 if (conversionType.Equals (typeof (UInt64)))
2203 return (object)(convert_value.ToUInt64 (nf_provider));
2204 if (conversionType.Equals (typeof (Object)))
2205 return (object)(value);
2215 // When compiling with -nostdlib and the type is imported from an external assembly
2216 // SRE uses "wrong" type and we have to convert it to the right compiler instance.
2218 public static Type TypeToCoreType (Type t)
2220 if (RootContext.StdLib || t.Module != typeof (object).Module)
2223 TypeCode tc = Type.GetTypeCode (t);
2226 case TypeCode.Boolean:
2227 return TypeManager.bool_type;
2229 return TypeManager.byte_type;
2230 case TypeCode.SByte:
2231 return TypeManager.sbyte_type;
2233 return TypeManager.char_type;
2234 case TypeCode.Int16:
2235 return TypeManager.short_type;
2236 case TypeCode.UInt16:
2237 return TypeManager.ushort_type;
2238 case TypeCode.Int32:
2239 return TypeManager.int32_type;
2240 case TypeCode.UInt32:
2241 return TypeManager.uint32_type;
2242 case TypeCode.Int64:
2243 return TypeManager.int64_type;
2244 case TypeCode.UInt64:
2245 return TypeManager.uint64_type;
2246 case TypeCode.Single:
2247 return TypeManager.float_type;
2248 case TypeCode.Double:
2249 return TypeManager.double_type;
2250 case TypeCode.String:
2251 return TypeManager.string_type;
2252 case TypeCode.Decimal:
2253 return TypeManager.decimal_type;
2256 if (t == typeof (void))
2257 return TypeManager.void_type;
2258 if (t == typeof (object))
2259 return TypeManager.object_type;
2260 if (t == typeof (System.Type))
2261 return TypeManager.type_type;
2262 if (t == typeof (System.IntPtr))
2263 return TypeManager.intptr_type;
2264 if (t == typeof (System.UIntPtr))
2265 return TypeManager.uintptr_type;
2268 int dim = t.GetArrayRank ();
2269 t = GetElementType (t);
2270 return t.MakeArrayType (dim);
2273 t = GetElementType (t);
2274 return t.MakeByRefType ();
2277 t = GetElementType (t);
2278 return t.MakePointerType ();
2285 /// Utility function that can be used to probe whether a type
2286 /// is managed or not.
2288 public static bool VerifyUnManaged (Type t, Location loc)
2290 if (IsUnmanagedType (t))
2293 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2300 /// Returns the name of the indexer in a given type.
2303 /// The default is not always `Item'. The user can change this behaviour by
2304 /// using the IndexerNameAttribute in the container.
2305 /// For example, the String class indexer is named `Chars' not `Item'
2307 public static string IndexerPropertyName (Type t)
2309 t = DropGenericTypeArguments (t);
2310 if (t is TypeBuilder) {
2311 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2312 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2315 System.Attribute attr = System.Attribute.GetCustomAttribute (
2316 t, TypeManager.default_member_type);
2318 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2319 return dma.MemberName;
2322 return TypeContainer.DefaultIndexerName;
2325 static MethodInfo declare_local_method = null;
2327 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2329 if (declare_local_method == null){
2330 declare_local_method = typeof (ILGenerator).GetMethod (
2332 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2334 new Type [] { typeof (Type), typeof (bool)},
2336 if (declare_local_method == null){
2337 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2338 return ig.DeclareLocal (t);
2341 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2344 private static bool IsSignatureEqual (Type a, Type b)
2347 /// Consider the following example (bug #77674):
2349 /// public abstract class A
2351 /// public abstract T Foo<T> ();
2354 /// public abstract class B : A
2356 /// public override U Foo<T> ()
2357 /// { return default (U); }
2360 /// Here, `T' and `U' are method type parameters from different methods
2361 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2363 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2364 /// we need to do a signature based comparision and consider them equal.
2370 if (a.IsGenericParameter && b.IsGenericParameter &&
2371 (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2372 return a.GenericParameterPosition == b.GenericParameterPosition;
2376 if (a.IsArray && b.IsArray) {
2377 if (a.GetArrayRank () != b.GetArrayRank ())
2380 return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
2383 if (a.IsByRef && b.IsByRef)
2384 return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
2387 if (a.IsGenericType && b.IsGenericType) {
2388 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2391 Type[] aargs = a.GetGenericArguments ();
2392 Type[] bargs = b.GetGenericArguments ();
2394 if (aargs.Length != bargs.Length)
2397 for (int i = 0; i < aargs.Length; i++) {
2398 if (!IsSignatureEqual (aargs [i], bargs [i]))
2410 // Returns whether the array of memberinfos contains the given method
2412 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2414 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2416 foreach (MethodBase method in array) {
2417 if (method.Name != new_method.Name)
2420 if (method is MethodInfo && new_method is MethodInfo &&
2422 TypeToCoreType (((MethodInfo) method).ReturnType),
2423 TypeToCoreType (((MethodInfo) new_method).ReturnType)))
2426 Type [] old_args = TypeManager.GetParameterData (method).Types;
2427 int old_count = old_args.Length;
2430 if (new_args.Length != old_count)
2433 for (i = 0; i < old_count; i++){
2434 if (!IsSignatureEqual (old_args [i], new_args [i]))
2447 // We copy methods from `new_members' into `target_list' if the signature
2448 // for the method from in the new list does not exist in the target_list
2450 // The name is assumed to be the same.
2452 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2454 if (target_list == null){
2455 target_list = new ArrayList ();
2457 foreach (MemberInfo mi in new_members){
2458 if (mi is MethodBase)
2459 target_list.Add (mi);
2464 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2465 target_list.CopyTo (target_array, 0);
2467 foreach (MemberInfo mi in new_members){
2468 MethodBase new_method = (MethodBase) mi;
2470 if (!ArrayContainsMethod (target_array, new_method))
2471 target_list.Add (new_method);
2478 // Tracks the generic parameters.
2480 static PtrHashtable builder_to_type_param;
2482 public static void AddTypeParameter (Type t, TypeParameter tparam)
2484 if (!builder_to_type_param.Contains (t))
2485 builder_to_type_param.Add (t, tparam);
2488 public static TypeParameter LookupTypeParameter (Type t)
2490 return (TypeParameter) builder_to_type_param [t];
2493 // This method always return false for non-generic compiler,
2494 // while Type.IsGenericParameter is returned if it is supported.
2495 public static bool IsGenericParameter (Type type)
2498 return type.IsGenericParameter;
2504 public static int GenericParameterPosition (Type type)
2507 return type.GenericParameterPosition;
2509 throw new InternalErrorException ("should not be called");
2513 public static bool IsGenericType (Type type)
2516 return type.IsGenericType;
2522 public static bool IsGenericTypeDefinition (Type type)
2525 return type.IsGenericTypeDefinition;
2531 public static bool ContainsGenericParameters (Type type)
2534 return type.ContainsGenericParameters;
2540 public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2543 if (fi.DeclaringType.IsGenericTypeDefinition ||
2544 !fi.DeclaringType.IsGenericType)
2547 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2548 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2549 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2551 // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
2552 foreach (FieldInfo f in t.GetFields (bf))
2553 if (f.MetadataToken == fi.MetadataToken)
2560 public static bool IsEqual (Type a, Type b)
2563 // MS BCL returns true even if enum types are different
2564 if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
2565 return a.FullName == b.FullName;
2571 if (a.IsGenericParameter && b.IsGenericParameter) {
2572 // TODO: needs more testing before cleaning up
2573 //if (a.DeclaringMethod != b.DeclaringMethod &&
2574 // (a.DeclaringMethod == null || b.DeclaringMethod == null))
2576 return a.GenericParameterPosition == b.GenericParameterPosition;
2579 if (a.IsArray && b.IsArray) {
2580 if (a.GetArrayRank () != b.GetArrayRank ())
2582 return IsEqual (a.GetElementType (), b.GetElementType ());
2585 if (a.IsByRef && b.IsByRef)
2586 return IsEqual (a.GetElementType (), b.GetElementType ());
2588 if (a.IsGenericType && b.IsGenericType) {
2589 Type adef = a.GetGenericTypeDefinition ();
2590 Type bdef = b.GetGenericTypeDefinition ();
2595 if (adef.IsEnum && bdef.IsEnum)
2598 Type[] aargs = a.GetGenericArguments ();
2599 Type[] bargs = b.GetGenericArguments ();
2601 if (aargs.Length != bargs.Length)
2604 for (int i = 0; i < aargs.Length; i++) {
2605 if (!IsEqual (aargs [i], bargs [i]))
2616 public static bool IsEqual (Type[] a, Type[] b)
2618 if (a.Length != b.Length)
2621 for (int i = 0; i < a.Length; ++i) {
2622 if (!IsEqual (a [i], b [i]))
2629 public static Type DropGenericTypeArguments (Type t)
2632 if (!t.IsGenericType)
2634 // Micro-optimization: a generic typebuilder is always a generic type definition
2635 if (t is TypeBuilder)
2637 return t.GetGenericTypeDefinition ();
2643 public static MethodBase DropGenericMethodArguments (MethodBase m)
2646 if (m.IsGenericMethod)
2647 m = ((MethodInfo) m).GetGenericMethodDefinition ();
2649 Type t = m.DeclaringType;
2650 if (!t.IsGenericType || t.IsGenericTypeDefinition)
2653 t = t.GetGenericTypeDefinition ();
2654 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2655 BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2658 // TODO: use CodeGen.Module.Builder.ResolveMethod ()
2662 if (m is ConstructorInfo) {
2663 foreach (ConstructorInfo c in t.GetConstructors (bf))
2664 if (c.MetadataToken == m.MetadataToken)
2667 foreach (MethodBase mb in t.GetMethods (bf))
2668 if (mb.MetadataToken == m.MetadataToken)
2676 public static Type[] GetGenericArguments (MethodBase mi)
2679 return mi.GetGenericArguments ();
2681 return Type.EmptyTypes;
2685 public static Type[] GetTypeArguments (Type t)
2688 DeclSpace tc = LookupDeclSpace (t);
2691 return Type.EmptyTypes;
2693 TypeParameter[] tparam = tc.TypeParameters;
2694 Type[] ret = new Type [tparam.Length];
2695 for (int i = 0; i < tparam.Length; i++) {
2696 ret [i] = tparam [i].Type;
2697 if (ret [i] == null)
2698 throw new InternalErrorException ();
2703 return t.GetGenericArguments ();
2705 throw new InternalErrorException ();
2709 public static GenericConstraints GetTypeParameterConstraints (Type t)
2712 if (!t.IsGenericParameter)
2713 throw new InvalidOperationException ();
2715 TypeParameter tparam = LookupTypeParameter (t);
2717 return tparam.GenericConstraints;
2719 return ReflectionConstraints.GetConstraints (t);
2721 throw new InternalErrorException ();
2725 public static bool HasGenericArguments (Type t)
2727 return GetNumberOfTypeArguments (t) > 0;
2730 public static int GetNumberOfTypeArguments (Type t)
2733 if (t.IsGenericParameter)
2735 DeclSpace tc = LookupDeclSpace (t);
2737 return tc.IsGeneric ? tc.CountTypeParameters : 0;
2739 return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2746 /// Check whether `type' and `parent' are both instantiations of the same
2747 /// generic type. Note that we do not check the type parameters here.
2749 public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2751 int tcount = GetNumberOfTypeArguments (type);
2752 int pcount = GetNumberOfTypeArguments (parent);
2754 if (tcount != pcount)
2757 type = DropGenericTypeArguments (type);
2758 parent = DropGenericTypeArguments (parent);
2760 return type.Equals (parent);
2764 /// Whether `mb' is a generic method definition.
2766 public static bool IsGenericMethodDefinition (MethodBase mb)
2769 if (mb.DeclaringType is TypeBuilder) {
2770 IMethodData method = (IMethodData) builder_to_method [mb];
2774 return method.GenericMethod != null;
2777 return mb.IsGenericMethodDefinition;
2784 /// Whether `mb' is a generic method.
2786 public static bool IsGenericMethod (MethodBase mb)
2789 return mb.IsGenericMethod;
2795 public static bool IsNullableType (Type t)
2798 return generic_nullable_type == DropGenericTypeArguments (t);
2804 public static bool IsNullableTypeOf (Type t, Type nullable)
2807 if (!IsNullableType (t))
2810 return GetTypeArguments (t) [0] == nullable;
2816 public static bool IsNullableValueType (Type t)
2819 if (!IsNullableType (t))
2822 return GetTypeArguments (t) [0].IsValueType;
2829 #region MemberLookup implementation
2832 // Whether we allow private members in the result (since FindMembers
2833 // uses NonPublic for both protected and private), we need to distinguish.
2836 internal class Closure {
2837 internal bool private_ok;
2839 // Who is invoking us and which type is being queried currently.
2840 internal Type invocation_type;
2841 internal Type qualifier_type;
2843 // The assembly that defines the type is that is calling us
2844 internal Assembly invocation_assembly;
2845 internal IList almost_match;
2847 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2849 if (invocation_type == null)
2852 if (is_static && qualifier_type == null)
2853 // It resolved from a simple name, so it should be visible.
2856 if (IsNestedChildOf (invocation_type, m.DeclaringType))
2859 for (Type t = invocation_type; t != null; t = t.DeclaringType) {
2860 if (!IsFamilyAccessible (t, m.DeclaringType))
2863 // Although a derived class can access protected members of its base class
2864 // it cannot do so through an instance of the base class (CS1540).
2865 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2866 if (is_static || qualifier_type == null ||
2867 IsInstantiationOfSameGenericType (t, qualifier_type) ||
2868 IsFamilyAccessible (qualifier_type, t))
2872 if (almost_match != null)
2873 almost_match.Add (m);
2879 // This filter filters by name + whether it is ok to include private
2880 // members in the search
2882 internal bool Filter (MemberInfo m, object filter_criteria)
2885 // Hack: we know that the filter criteria will always be in the
2886 // `closure' // fields.
2889 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2892 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2893 (invocation_type != null) &&
2894 IsPrivateAccessible (m.DeclaringType, invocation_type))
2898 // Ugly: we need to find out the type of `m', and depending
2899 // on this, tell whether we accept or not
2901 if (m is MethodBase){
2902 MethodBase mb = (MethodBase) m;
2903 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2905 if (ma == MethodAttributes.Public)
2908 if (ma == MethodAttributes.PrivateScope)
2911 if (ma == MethodAttributes.Private)
2912 return private_ok ||
2913 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2914 IsNestedChildOf (invocation_type, m.DeclaringType);
2916 if (TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly)) {
2917 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2920 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2924 // Family, FamORAssem or FamANDAssem
2925 return CheckValidFamilyAccess (mb.IsStatic, m);
2928 if (m is FieldInfo){
2929 FieldInfo fi = (FieldInfo) m;
2930 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2932 if (fa == FieldAttributes.Public)
2935 if (fa == FieldAttributes.PrivateScope)
2938 if (fa == FieldAttributes.Private)
2939 return private_ok ||
2940 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2941 IsNestedChildOf (invocation_type, m.DeclaringType);
2943 if (TypeManager.IsThisOrFriendAssembly (fi.DeclaringType.Assembly)) {
2944 if ((fa == FieldAttributes.Assembly) ||
2945 (fa == FieldAttributes.FamORAssem))
2948 if ((fa == FieldAttributes.Assembly) ||
2949 (fa == FieldAttributes.FamANDAssem))
2953 // Family, FamORAssem or FamANDAssem
2954 return CheckValidFamilyAccess (fi.IsStatic, m);
2958 // EventInfos and PropertyInfos, return true because they lack
2959 // permission information, so we need to check later on the methods.
2965 static Closure closure = new Closure ();
2966 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2969 // Looks up a member called `name' in the `queried_type'. This lookup
2970 // is done by code that is contained in the definition for `invocation_type'
2971 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2973 // `invocation_type' is used to check whether we're allowed to access the requested
2974 // member wrt its protection level.
2976 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2977 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2978 // is B and qualifier_type is A). This is used to do the CS1540 check.
2980 // When resolving a SimpleName, `qualifier_type' is null.
2982 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2983 // the same than `queried_type' - except when we're being called from BaseAccess;
2984 // in this case, `invocation_type' is the current type and `queried_type' the base
2985 // type, so this'd normally trigger a CS1540.
2987 // The binding flags are `bf' and the kind of members being looked up are `mt'
2989 // The return value always includes private members which code in `invocation_type'
2990 // is allowed to access (using the specified `qualifier_type' if given); only use
2991 // BindingFlags.NonPublic to bypass the permission check.
2993 // The 'almost_match' argument is used for reporting error CS1540.
2995 // Returns an array of a single element for everything but Methods/Constructors
2996 // that might return multiple matches.
2998 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2999 Type queried_type, MemberTypes mt,
3000 BindingFlags original_bf, string name, IList almost_match)
3002 Timer.StartTimer (TimerType.MemberLookup);
3004 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
3005 queried_type, mt, original_bf, name, almost_match);
3007 Timer.StopTimer (TimerType.MemberLookup);
3012 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
3013 Type queried_type, MemberTypes mt,
3014 BindingFlags original_bf, string name, IList almost_match)
3016 BindingFlags bf = original_bf;
3018 ArrayList method_list = null;
3019 Type current_type = queried_type;
3020 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
3021 bool skip_iface_check = true, used_cache = false;
3022 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
3024 closure.invocation_type = invocation_type;
3025 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
3026 closure.qualifier_type = qualifier_type;
3027 closure.almost_match = almost_match;
3029 // This is from the first time we find a method
3030 // in most cases, we do not actually find a method in the base class
3031 // so we can just ignore it, and save the arraylist allocation
3032 MemberInfo [] first_members_list = null;
3033 bool use_first_members_list = false;
3039 // `NonPublic' is lame, because it includes both protected and
3040 // private methods, so we need to control this behavior by
3041 // explicitly tracking if a private method is ok or not.
3043 // The possible cases are:
3044 // public, private and protected (internal does not come into the
3047 if ((invocation_type != null) &&
3048 ((invocation_type == current_type) ||
3049 IsNestedChildOf (invocation_type, current_type)) ||
3051 bf = original_bf | BindingFlags.NonPublic;
3055 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
3057 Timer.StopTimer (TimerType.MemberLookup);
3059 list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
3061 Timer.StartTimer (TimerType.MemberLookup);
3064 // When queried for an interface type, the cache will automatically check all
3065 // inherited members, so we don't need to do this here. However, this only
3066 // works if we already used the cache in the first iteration of this loop.
3068 // If we used the cache in any further iteration, we can still terminate the
3069 // loop since the cache always looks in all base classes.
3075 skip_iface_check = false;
3077 if (current_type == TypeManager.object_type)
3080 current_type = current_type.BaseType;
3083 // This happens with interfaces, they have a null
3084 // basetype. Look members up in the Object class.
3086 if (current_type == null) {
3087 current_type = TypeManager.object_type;
3092 if (list.Length == 0)
3096 // Events and types are returned by both `static' and `instance'
3097 // searches, which means that our above FindMembers will
3098 // return two copies of the same.
3100 if (list.Length == 1 && !(list [0] is MethodBase)){
3105 // Multiple properties: we query those just to find out the indexer
3108 if (list [0] is PropertyInfo)
3112 // We found an event: the cache lookup returns both the event and
3113 // its private field.
3115 if (list [0] is EventInfo) {
3116 if ((list.Length == 2) && (list [1] is FieldInfo))
3117 return new MemberInfo [] { list [0] };
3123 // We found methods, turn the search into "method scan"
3127 if (first_members_list != null) {
3128 if (use_first_members_list) {
3129 method_list = CopyNewMethods (method_list, first_members_list);
3130 use_first_members_list = false;
3133 method_list = CopyNewMethods (method_list, list);
3135 first_members_list = list;
3136 use_first_members_list = true;
3137 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3139 } while (searching);
3141 if (use_first_members_list)
3142 return first_members_list;
3144 if (method_list != null && method_list.Count > 0) {
3145 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3148 // This happens if we already used the cache in the first iteration, in this case
3149 // the cache already looked in all interfaces.
3151 if (skip_iface_check)
3155 // Interfaces do not list members they inherit, so we have to
3158 if (!queried_type.IsInterface)
3161 if (queried_type.IsArray)
3162 queried_type = TypeManager.array_type;
3164 Type [] ifaces = GetInterfaces (queried_type);
3168 foreach (Type itype in ifaces){
3171 x = MemberLookup (null, null, itype, mt, bf, name, null);
3179 const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
3180 BindingFlags.Static | BindingFlags.Instance |
3181 BindingFlags.DeclaredOnly;
3183 // Currently is designed to work with external types only
3184 public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
3186 if (!mb.IsSpecialName)
3189 string name = mb.Name;
3190 if (name.Length < 5)
3193 if (name [3] != '_')
3196 if (name.StartsWith ("get") || name.StartsWith ("set")) {
3197 MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
3198 Type.FilterName, name.Substring (4));
3203 // This can happen when property is indexer (it can have same name but different parameters)
3204 foreach (PropertyInfo p in pi) {
3205 foreach (MethodInfo p_mi in p.GetAccessors (true)) {
3206 if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
3215 // Currently is designed to work with external types only
3216 public static MemberInfo GetEventFromAccessor (MethodBase mb)
3218 if (!mb.IsSpecialName)
3221 string name = mb.Name;
3222 if (name.Length < 5)
3225 if (name.StartsWith ("add_"))
3226 return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
3228 if (name.StartsWith ("remove_"))
3229 return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
3234 // Tests whether external method is really special
3235 public static bool IsSpecialMethod (MethodBase mb)
3237 if (!mb.IsSpecialName)
3240 IMethodData md = TypeManager.GetMethod (mb);
3242 return (md is AbstractPropertyEventMethod || md is Operator);
3244 PropertyInfo pi = GetPropertyFromAccessor (mb);
3246 return IsValidProperty (pi);
3248 if (GetEventFromAccessor (mb) != null)
3251 string name = mb.Name;
3252 if (name.StartsWith ("op_")){
3253 foreach (string oname in Unary.oper_names) {
3258 foreach (string oname in Binary.oper_names) {
3266 // Tests whether imported property is valid C# property.
3267 // TODO: It seems to me that we should do a lot of sanity tests before
3268 // we accept property as C# property
3269 static bool IsValidProperty (PropertyInfo pi)
3271 MethodInfo get_method = pi.GetGetMethod (true);
3272 MethodInfo set_method = pi.GetSetMethod (true);
3273 if (get_method != null && set_method != null) {
3274 int g_count = get_method.GetParameters ().Length;
3275 int s_count = set_method.GetParameters ().Length;
3276 if (g_count + 1 != s_count)
3287 /// There is exactly one instance of this class per type.
3289 public sealed class TypeHandle : IMemberContainer {
3290 public readonly IMemberContainer BaseType;
3292 readonly int id = ++next_id;
3293 static int next_id = 0;
3295 static TypeHandle ()
3301 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
3302 /// a TypeHandle yet, a new instance of it is created. This static method
3303 /// ensures that we'll only have one TypeHandle instance per type.
3305 private static TypeHandle GetTypeHandle (Type t)
3307 TypeHandle handle = (TypeHandle) type_hash [t];
3311 handle = new TypeHandle (t);
3312 type_hash.Add (t, handle);
3316 public static MemberCache GetMemberCache (Type t)
3318 return GetTypeHandle (t).MemberCache;
3321 public static void CleanUp ()
3326 public static void Reset ()
3328 type_hash = new PtrHashtable ();
3332 /// Returns the TypeHandle for TypeManager.object_type.
3334 public static IMemberContainer ObjectType {
3336 if (object_type != null)
3339 object_type = GetTypeHandle (TypeManager.object_type);
3346 /// Returns the TypeHandle for TypeManager.array_type.
3348 public static TypeHandle ArrayType {
3350 if (array_type != null)
3353 array_type = GetTypeHandle (TypeManager.array_type);
3359 private static PtrHashtable type_hash;
3361 private static TypeHandle object_type = null;
3362 private static TypeHandle array_type = null;
3365 private string full_name;
3366 private bool is_interface;
3367 private MemberCache member_cache;
3368 private MemberCache base_cache;
3370 private TypeHandle (Type type)
3373 full_name = type.FullName != null ? type.FullName : type.Name;
3374 if (type.BaseType != null) {
3375 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3376 BaseType = base_cache.Container;
3377 } else if (type.IsInterface)
3378 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3379 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3380 this.member_cache = new MemberCache (this);
3383 // IMemberContainer methods
3385 public string Name {
3397 public MemberCache BaseCache {
3403 public bool IsInterface {
3405 return is_interface;
3409 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3411 MemberInfo [] members;
3414 if (type is GenericTypeParameterBuilder)
3415 return MemberList.Empty;
3418 if (mt == MemberTypes.Event)
3419 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3421 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3424 if (members.Length == 0)
3425 return MemberList.Empty;
3427 Array.Reverse (members);
3428 return new MemberList (members);
3431 // IMemberFinder methods
3433 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3434 MemberFilter filter, object criteria)
3436 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3439 public MemberCache MemberCache {
3441 return member_cache;
3445 public override string ToString ()
3447 if (BaseType != null)
3448 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3450 return "TypeHandle (" + id + "," + Name + ")";