2 // typemanager.cs: C# type manager
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Ravi Pratap (ravi@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
14 // We will eventually remove the SIMPLE_SPEEDUP, and should never change
15 // the behavior of the compilation. This can be removed if we rework
16 // the code to get a list of namespaces available.
18 #define SIMPLE_SPEEDUP
22 using System.Globalization;
23 using System.Collections;
24 using System.Reflection;
25 using System.Reflection.Emit;
27 using System.Text.RegularExpressions;
28 using System.Runtime.CompilerServices;
29 using System.Diagnostics;
31 namespace Mono.CSharp {
33 public partial class TypeManager {
35 // A list of core types that the compiler requires or uses
37 static public Type object_type;
38 static public Type value_type;
39 static public Type string_type;
40 static public Type int32_type;
41 static public Type uint32_type;
42 static public Type int64_type;
43 static public Type uint64_type;
44 static public Type float_type;
45 static public Type double_type;
46 static public Type char_type;
47 static public Type char_ptr_type;
48 static public Type short_type;
49 static public Type decimal_type;
50 static public Type bool_type;
51 static public Type sbyte_type;
52 static public Type byte_type;
53 static public Type ushort_type;
54 static public Type enum_type;
55 static public Type delegate_type;
56 static public Type multicast_delegate_type;
57 static public Type void_type;
58 static public Type null_type;
59 static public Type enumeration_type;
60 static public Type array_type;
61 static public Type runtime_handle_type;
62 static public Type icloneable_type;
63 static public Type type_type;
64 static public Type ienumerator_type;
65 static public Type ienumerable_type;
66 static public Type idisposable_type;
67 static public Type iconvertible_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 monitor_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 unverifiable_code_type;
80 static public Type methodimpl_attr_type;
81 static public Type marshal_as_attr_type;
82 static public Type param_array_type;
83 static public Type void_ptr_type;
84 static public Type indexer_name_type;
85 static public Type exception_type;
86 static public Type invalid_operation_exception_type;
87 static public Type not_supported_exception_type;
88 static public Type obsolete_attribute_type;
89 static public Type conditional_attribute_type;
90 static public Type in_attribute_type;
91 static public Type out_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 runtime_compatibility_attribute_type;
108 static internal Type compiler_generated_attr_type;
109 static internal Type fixed_buffer_attr_type;
110 static internal Type default_charset_type;
113 // An empty array of types
115 static public Type [] NoTypes;
116 static public TypeExpr [] NoTypeExprs;
120 // Expressions representing the internal types. Used during declaration
123 static public TypeExpr system_object_expr, system_string_expr;
124 static public TypeExpr system_boolean_expr, system_decimal_expr;
125 static public TypeExpr system_single_expr, system_double_expr;
126 static public TypeExpr system_sbyte_expr, system_byte_expr;
127 static public TypeExpr system_int16_expr, system_uint16_expr;
128 static public TypeExpr system_int32_expr, system_uint32_expr;
129 static public TypeExpr system_int64_expr, system_uint64_expr;
130 static public TypeExpr system_char_expr, system_void_expr;
131 static public TypeExpr system_asynccallback_expr;
132 static public TypeExpr system_iasyncresult_expr;
133 static public TypeExpr system_valuetype_expr;
134 static public TypeExpr system_intptr_expr;
137 // This is only used when compiling corlib
139 static public Type system_int32_type;
140 static public Type system_array_type;
141 static public Type system_type_type;
142 static public Type system_assemblybuilder_type;
143 static public MethodInfo system_int_array_get_length;
144 static public MethodInfo system_int_array_get_rank;
145 static public MethodInfo system_object_array_clone;
146 static public MethodInfo system_int_array_get_length_int;
147 static public MethodInfo system_int_array_get_lower_bound_int;
148 static public MethodInfo system_int_array_get_upper_bound_int;
149 static public MethodInfo system_void_array_copyto_array_int;
153 // Internal, not really used outside
155 static Type runtime_helpers_type;
158 // These methods are called by code generated by the compiler
160 static public MethodInfo string_concat_string_string;
161 static public MethodInfo string_concat_string_string_string;
162 static public MethodInfo string_concat_string_string_string_string;
163 static public MethodInfo string_concat_string_dot_dot_dot;
164 static public MethodInfo string_concat_object_object;
165 static public MethodInfo string_concat_object_object_object;
166 static public MethodInfo string_concat_object_dot_dot_dot;
167 static public MethodInfo string_isinterneted_string;
168 static public MethodInfo system_type_get_type_from_handle;
169 static public MethodInfo bool_movenext_void;
170 static public MethodInfo ienumerable_getenumerator_void;
171 static public MethodInfo void_reset_void;
172 static public MethodInfo void_dispose_void;
173 static public MethodInfo void_monitor_enter_object;
174 static public MethodInfo void_monitor_exit_object;
175 static public MethodInfo void_initializearray_array_fieldhandle;
176 static public MethodInfo int_getlength_int;
177 static public MethodInfo delegate_combine_delegate_delegate;
178 static public MethodInfo delegate_remove_delegate_delegate;
179 static public MethodInfo int_get_offset_to_string_data;
180 static public MethodInfo int_array_get_length;
181 static public MethodInfo int_array_get_rank;
182 static public MethodInfo object_array_clone;
183 static public MethodInfo int_array_get_length_int;
184 static public MethodInfo int_array_get_lower_bound_int;
185 static public MethodInfo int_array_get_upper_bound_int;
186 static public MethodInfo void_array_copyto_array_int;
187 static public PropertyInfo ienumerator_getcurrent;
190 // The attribute constructors.
192 static public ConstructorInfo object_ctor;
193 static public ConstructorInfo cons_param_array_attribute;
194 static public ConstructorInfo void_decimal_ctor_five_args;
195 static public ConstructorInfo void_decimal_ctor_int_arg;
196 static public ConstructorInfo unverifiable_code_ctor;
197 static public ConstructorInfo default_member_ctor;
198 static public ConstructorInfo decimal_constant_attribute_ctor;
199 static internal ConstructorInfo struct_layout_attribute_ctor;
200 static public ConstructorInfo field_offset_attribute_ctor;
205 static internal CustomAttributeBuilder compiler_generated_attr;
206 static internal ConstructorInfo fixed_buffer_attr_ctor;
209 // Holds the Array of Assemblies that have been loaded
210 // (either because it is the default or the user used the
211 // -r command line option)
213 static Assembly [] assemblies;
216 // Keeps a list of modules. We used this to do lookups
217 // on the module using GetType -- needed for arrays
219 static Module [] modules;
221 static PtrHashtable builder_to_declspace;
223 static PtrHashtable builder_to_member_cache;
226 // Tracks the interfaces implemented by typebuilders. We only
227 // enter those who do implement or or more interfaces
229 static PtrHashtable builder_to_ifaces;
232 // Maps MethodBase.RuntimeTypeHandle to a Type array that contains
233 // the arguments to the method
235 static Hashtable method_arguments;
238 // Maps PropertyBuilder to a Type array that contains
239 // the arguments to the indexer
241 static Hashtable indexer_arguments;
244 // Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
246 static Hashtable method_params;
249 // A hash table from override methods to their base virtual method.
251 static Hashtable method_overrides;
254 // Keeps track of methods
257 static Hashtable builder_to_method;
260 // Contains all public types from referenced assemblies.
261 // This member is used only if CLS Compliance verification is required.
263 public static Hashtable AllClsTopLevelTypes;
265 static Hashtable fieldbuilders_to_fields;
266 static Hashtable fields;
273 public static void CleanUp ()
275 // Lets get everything clean so that we can collect before generating code
278 builder_to_declspace = null;
279 builder_to_member_cache = null;
280 builder_to_ifaces = null;
281 method_arguments = null;
282 indexer_arguments = null;
283 method_params = null;
284 builder_to_method = null;
287 fieldbuilders_to_fields = null;
289 priv_fields_events = null;
294 TypeHandle.CleanUp ();
298 /// A filter for Findmembers that uses the Signature object to
301 static bool SignatureFilter (MemberInfo mi, object criteria)
303 Signature sig = (Signature) criteria;
305 if (!(mi is MethodBase))
308 if (mi.Name != sig.name)
311 int count = sig.args.Length;
313 if (mi is MethodBuilder || mi is ConstructorBuilder){
314 Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
316 if (candidate_args.Length != count)
319 for (int i = 0; i < count; i++)
320 if (candidate_args [i] != sig.args [i])
325 ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
327 if (pars.Length != count)
330 for (int i = 0; i < count; i++)
331 if (pars [i].ParameterType != sig.args [i])
337 // A delegate that points to the filter above.
338 static MemberFilter signature_filter;
341 // These are expressions that represent some of the internal data types, used
344 static void InitExpressionTypes ()
346 system_object_expr = new TypeLookupExpression ("System.Object");
347 system_string_expr = new TypeLookupExpression ("System.String");
348 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
349 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
350 system_single_expr = new TypeLookupExpression ("System.Single");
351 system_double_expr = new TypeLookupExpression ("System.Double");
352 system_sbyte_expr = new TypeLookupExpression ("System.SByte");
353 system_byte_expr = new TypeLookupExpression ("System.Byte");
354 system_int16_expr = new TypeLookupExpression ("System.Int16");
355 system_uint16_expr = new TypeLookupExpression ("System.UInt16");
356 system_int32_expr = new TypeLookupExpression ("System.Int32");
357 system_uint32_expr = new TypeLookupExpression ("System.UInt32");
358 system_int64_expr = new TypeLookupExpression ("System.Int64");
359 system_uint64_expr = new TypeLookupExpression ("System.UInt64");
360 system_char_expr = new TypeLookupExpression ("System.Char");
361 system_void_expr = new TypeLookupExpression ("System.Void");
362 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
363 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
364 system_valuetype_expr = new TypeLookupExpression ("System.ValueType");
365 system_intptr_expr = new TypeLookupExpression ("System.IntPtr");
368 static TypeManager ()
372 signature_filter = new MemberFilter (SignatureFilter);
373 InitExpressionTypes ();
376 static public void Reset ()
378 assemblies = new Assembly [0];
381 builder_to_declspace = new PtrHashtable ();
382 builder_to_member_cache = new PtrHashtable ();
383 builder_to_method = new PtrHashtable ();
384 method_arguments = new PtrHashtable ();
385 method_params = new PtrHashtable ();
386 method_overrides = new PtrHashtable ();
387 indexer_arguments = new PtrHashtable ();
388 builder_to_ifaces = new PtrHashtable ();
390 NoTypes = new Type [0];
391 NoTypeExprs = new TypeExpr [0];
393 fieldbuilders_to_fields = new Hashtable ();
394 fields = new Hashtable ();
395 type_hash = new DoubleHash ();
400 public static void AddUserType (string name, DeclSpace ds)
402 builder_to_declspace.Add (ds.TypeBuilder, ds);
406 // This entry point is used by types that we define under the covers
408 public static void RegisterBuilder (Type tb, Type [] ifaces)
411 builder_to_ifaces [tb] = ifaces;
414 public static void AddMethod (MethodBase builder, IMethodData method)
416 builder_to_method.Add (builder, method);
419 public static IMethodData GetMethod (MethodBase builder)
421 return (IMethodData) builder_to_method [builder];
425 /// Returns the DeclSpace whose Type is `t' or null if there is no
426 /// DeclSpace for `t' (ie, the Type comes from a library)
428 public static DeclSpace LookupDeclSpace (Type t)
430 return builder_to_declspace [t] as DeclSpace;
434 /// Returns the TypeContainer whose Type is `t' or null if there is no
435 /// TypeContainer for `t' (ie, the Type comes from a library)
437 public static TypeContainer LookupTypeContainer (Type t)
439 return builder_to_declspace [t] as TypeContainer;
442 public static MemberCache LookupMemberCache (Type t)
444 if (t is TypeBuilder) {
445 IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
446 if (container != null)
447 return container.MemberCache;
450 if (t is GenericTypeParameterBuilder) {
451 IMemberContainer container = builder_to_type_param [t] as IMemberContainer;
453 if (container != null)
454 return container.MemberCache;
457 return TypeHandle.GetMemberCache (t);
460 public static MemberCache LookupBaseInterfacesCache (Type t)
462 Type [] ifaces = t.GetInterfaces ();
464 if (ifaces != null && ifaces.Length == 1)
465 return LookupMemberCache (ifaces [0]);
467 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
468 MemberCache cache = builder_to_member_cache [t] as MemberCache;
472 cache = new MemberCache (ifaces);
473 builder_to_member_cache.Add (t, cache);
477 public static TypeContainer LookupInterface (Type t)
479 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
480 if ((tc == null) || (tc.Kind != Kind.Interface))
486 public static Delegate LookupDelegate (Type t)
488 return builder_to_declspace [t] as Delegate;
491 public static Class LookupClass (Type t)
493 return (Class) builder_to_declspace [t];
497 /// Registers an assembly to load types from.
499 public static void AddAssembly (Assembly a)
501 foreach (Assembly assembly in assemblies) {
506 int top = assemblies.Length;
507 Assembly [] n = new Assembly [top + 1];
509 assemblies.CopyTo (n, 0);
515 public static Assembly [] GetAssemblies ()
521 /// Registers a module builder to lookup types from
523 public static void AddModule (Module mb)
525 int top = modules != null ? modules.Length : 0;
526 Module [] n = new Module [top + 1];
529 modules.CopyTo (n, 0);
534 public static Module[] Modules {
541 // We use this hash for multiple kinds of constructed types:
543 // (T, "&") Given T, get T &
544 // (T, "*") Given T, get T *
545 // (T, "[]") Given T and a array dimension, get T []
546 // (T, X) Given a type T and a simple name X, get the type T+X
548 // Accessibility tests, if necessary, should be done by the user
550 static DoubleHash type_hash = new DoubleHash ();
553 // Gets the reference to T version of the Type (T&)
555 public static Type GetReferenceType (Type t)
557 return t.MakeByRefType ();
561 // Gets the pointer to T version of the Type (T*)
563 public static Type GetPointerType (Type t)
565 return GetConstructedType (t, "*");
568 public static Type GetConstructedType (Type t, string dim)
571 if (type_hash.Lookup (t, dim, out ret))
574 ret = t.Module.GetType (t.ToString () + dim);
576 type_hash.Insert (t, dim, ret);
581 ret = GetReferenceType (t);
582 type_hash.Insert (t, dim, ret);
586 if (t.IsGenericParameter || t.IsGenericInstance) {
589 while ((pos < dim.Length) && (dim [pos] == '[')) {
592 if (dim [pos] == ']') {
593 result = result.MakeArrayType ();
596 if (pos < dim.Length)
599 type_hash.Insert (t, dim, result);
604 while (dim [pos] == ',') {
608 if ((dim [pos] != ']') || (pos != dim.Length-1))
611 result = result.MakeArrayType (rank + 1);
612 type_hash.Insert (t, dim, result);
617 type_hash.Insert (t, dim, null);
621 public static Type GetNestedType (Type t, string name)
624 if (!type_hash.Lookup (t, name, out ret)) {
625 ret = t.GetNestedType (name,
626 BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
627 type_hash.Insert (t, name, ret);
632 public static Type LookupTypeReflection (string name, Location loc)
634 Type found_type = null;
636 foreach (Assembly a in assemblies) {
637 Type t = a.GetType (name);
642 throw new InternalErrorException ("Use GetPointerType() to get a pointer");
644 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
645 if (ta != TypeAttributes.NotPublic && ta != TypeAttributes.NestedPrivate &&
646 ta != TypeAttributes.NestedAssembly && ta != TypeAttributes.NestedFamANDAssem) {
647 if (found_type == null) {
652 Report.SymbolRelatedToPreviousError (found_type);
653 Report.SymbolRelatedToPreviousError (t);
654 Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
659 foreach (Module mb in modules) {
660 Type t = mb.GetType (name);
664 if (found_type == null) {
669 Report.SymbolRelatedToPreviousError (t);
670 Report.SymbolRelatedToPreviousError (found_type);
671 Report.Warning (436, 2, loc, "Ignoring imported type `{0}' since the current assembly already has a declaration with the same name",
672 TypeManager.CSharpName (t));
680 /// Computes the namespaces that we import from the assemblies we reference.
682 public static void ComputeNamespaces ()
684 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
686 Hashtable cache = null;
689 // First add the assembly namespaces
691 if (assembly_get_namespaces != null){
692 int count = assemblies.Length;
694 for (int i = 0; i < count; i++){
695 Assembly a = assemblies [i];
696 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
697 foreach (string ns in namespaces){
700 Namespace.LookupNamespace (ns, true);
704 cache = new Hashtable ();
705 cache.Add ("", null);
706 foreach (Assembly a in assemblies) {
707 foreach (Type t in a.GetExportedTypes ()) {
708 string ns = t.Namespace;
709 if (ns == null || cache.Contains (ns))
712 Namespace.LookupNamespace (ns, true);
713 cache.Add (ns, null);
719 // Then add module namespaces
721 foreach (Module m in modules) {
722 if (m == CodeGen.Module.Builder)
725 cache = new Hashtable ();
726 cache.Add ("", null);
728 foreach (Type t in m.GetTypes ()) {
729 string ns = t.Namespace;
730 if (ns == null || cache.Contains (ns))
732 Namespace.LookupNamespace (ns, true);
733 cache.Add (ns, null);
739 /// Fills static table with exported types from all referenced assemblies.
740 /// This information is required for CLS Compliance tests.
742 public static void LoadAllImportedTypes ()
744 AllClsTopLevelTypes = new Hashtable (1500);
745 foreach (Assembly a in assemblies) {
746 foreach (Type t in a.GetExportedTypes ()) {
747 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
752 public static bool NamespaceClash (string name, Location loc)
754 if (Namespace.LookupNamespace (name, false) == null)
757 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
762 /// Returns the C# name of a type if possible, or the full type name otherwise
764 static public string CSharpName (Type t)
766 string name = GetFullName (t);
768 return Regex.Replace (name,
770 @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
771 @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
772 @"Boolean|String|Void|Null)" +
774 new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
777 static public string CSharpName (Type[] types)
779 StringBuilder sb = new StringBuilder ();
780 foreach (Type t in types) {
781 sb.Append (CSharpName (t));
784 sb.Remove (sb.Length - 1, 1);
785 return sb.ToString ();
788 static String CSharpNameMatch (Match match)
790 string s = match.Groups [1].Captures [0].Value;
792 Replace ("int32", "int").
793 Replace ("uint32", "uint").
794 Replace ("int16", "short").
795 Replace ("uint16", "ushort").
796 Replace ("int64", "long").
797 Replace ("uint64", "ulong").
798 Replace ("single", "float").
799 Replace ("boolean", "bool")
800 + match.Groups [2].Captures [0].Value;
804 /// Returns the signature of the method with full namespace classification
806 static public string GetFullNameSignature (MemberInfo mi)
808 return (mi is MethodBase)
809 ? CSharpSignature (mi as MethodBase)
810 : CSharpName (mi.DeclaringType) + '.' + mi.Name;
813 private static void GetFullName_recursed (StringBuilder sb, Type t, Type original_type,
814 ref int pos, bool recursed)
816 if (t.IsGenericParameter) {
822 string ns = t.Namespace;
823 if ((ns != null) && (ns != "")) {
829 if (t.DeclaringType != null) {
830 GetFullName_recursed (sb, t.DeclaringType, t, ref pos, true);
834 sb.Append (SimpleName.RemoveGenericArity (t.Name));
836 Type[] args = GetTypeArguments (original_type);
837 Type[] this_args = GetTypeArguments (t);
839 if (this_args.Length > pos) {
841 for (int i = pos; i < this_args.Length; i++) {
844 sb.Append (GetFullName (args [i]));
849 pos += this_args.Length;
852 static public string GetFullName (Type t)
854 StringBuilder sb = new StringBuilder ();
856 GetFullName_recursed (sb, t, t, ref pos, false);
857 return sb.ToString ();
861 /// When we need to report accessors as well
863 static public string CSharpSignature (MethodBase mb)
865 return CSharpSignature (mb, false);
869 /// Returns the signature of the method
871 static public string CSharpSignature (MethodBase mb, bool show_accessor)
873 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
876 ParameterData iparams = GetParameterData (mb);
877 string parameters = iparams.GetSignatureForError ();
878 string accessor = "";
881 if (mb.IsSpecialName) {
882 Operator.OpType ot = Operator.GetOperatorType (mb.Name);
883 if (ot != Operator.OpType.TOP) {
884 sig.Append ("operator ");
885 sig.Append (Operator.GetName (ot));
886 sig.Append (parameters);
887 return sig.ToString ();
890 if (mb.Name.StartsWith ("get_") || mb.Name.StartsWith ("set_")) {
891 accessor = mb.Name.Substring (0, 3);
896 if (mb.IsSpecialName && !mb.IsConstructor) {
897 if (iparams.Count > 1) {
898 sig.Append ("this[");
900 sig.Append (parameters.Substring (1, parameters.Length - 2));
903 int before_ret_val = parameters.LastIndexOf (',');
904 sig.Append (parameters.Substring (1, before_ret_val - 1));
908 sig.Append (mb.Name.Substring (4));
911 if (mb.Name == ".ctor")
912 sig.Append (mb.DeclaringType.Name);
914 sig.Append (mb.Name);
916 sig.Append (parameters);
919 if (show_accessor && accessor.Length > 0) {
921 sig.Append (accessor);
924 return sig.ToString ();
927 public static string GetMethodName (MethodInfo m)
929 if (!IsGenericMethod (m))
932 return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
935 static public string CSharpSignature (EventInfo ei)
937 return CSharpName (ei.DeclaringType) + '.' + ei.Name;
941 /// Looks up a type, and aborts if it is not found. This is used
942 /// by types required by the compiler
944 static Type CoreLookupType (string ns_name, string name)
946 Namespace ns = Namespace.LookupNamespace (ns_name, true);
947 FullNamedExpression fne = ns.Lookup (RootContext.Tree.Types, name, Location.Null);
948 Type t = fne == null ? null : fne.Type;
950 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
955 /// Returns the MethodInfo for a method named `name' defined
956 /// in type `t' which takes arguments of types `args'
958 static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
962 BindingFlags flags = instance_and_static | BindingFlags.Public;
968 flags |= BindingFlags.NonPublic;
970 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
971 if (list.Count == 0) {
973 Report.Error (-19, "Can not find the core function `" + name + "'");
977 MethodInfo mi = list [0] as MethodInfo;
980 Report.Error (-19, "Can not find the core function `" + name + "'");
987 static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
989 return GetMethod (t, name, args, false, report_errors);
992 static MethodInfo GetMethod (Type t, string name, Type [] args)
994 return GetMethod (t, name, args, true);
998 /// Returns the PropertyInfo for a property named `name' defined
1001 static PropertyInfo GetProperty (Type t, string name)
1003 MemberList list = FindMembers (t, MemberTypes.Property, BindingFlags.Public |
1004 BindingFlags.Instance, Type.FilterName, name);
1005 if (list.Count == 0) {
1006 Report.Error (-19, "Can not find the core property `" + name + "'");
1010 PropertyInfo pi = list [0] as PropertyInfo;
1012 Report.Error (-19, "Can not find the core function `" + name + "'");
1020 /// Returns the ConstructorInfo for "args"
1022 public static ConstructorInfo GetConstructor (Type t, Type [] args)
1030 list = FindMembers (t, MemberTypes.Constructor,
1031 instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
1032 signature_filter, sig);
1033 if (list.Count == 0){
1034 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1038 ConstructorInfo ci = list [0] as ConstructorInfo;
1040 Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
1047 public static void InitEnumUnderlyingTypes ()
1050 int32_type = CoreLookupType ("System", "Int32");
1051 int64_type = CoreLookupType ("System", "Int64");
1052 uint32_type = CoreLookupType ("System", "UInt32");
1053 uint64_type = CoreLookupType ("System", "UInt64");
1054 byte_type = CoreLookupType ("System", "Byte");
1055 sbyte_type = CoreLookupType ("System", "SByte");
1056 short_type = CoreLookupType ("System", "Int16");
1057 ushort_type = CoreLookupType ("System", "UInt16");
1061 /// The types have to be initialized after the initial
1062 /// population of the type has happened (for example, to
1063 /// bootstrap the corlib.dll
1065 public static void InitCoreTypes ()
1067 object_type = CoreLookupType ("System", "Object");
1068 value_type = CoreLookupType ("System", "ValueType");
1070 InitEnumUnderlyingTypes ();
1072 char_type = CoreLookupType ("System", "Char");
1073 string_type = CoreLookupType ("System", "String");
1074 float_type = CoreLookupType ("System", "Single");
1075 double_type = CoreLookupType ("System", "Double");
1076 char_ptr_type = GetPointerType (char_type);
1077 decimal_type = CoreLookupType ("System", "Decimal");
1078 bool_type = CoreLookupType ("System", "Boolean");
1079 enum_type = CoreLookupType ("System", "Enum");
1081 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate");
1082 delegate_type = CoreLookupType ("System", "Delegate");
1084 array_type = CoreLookupType ("System", "Array");
1085 void_type = CoreLookupType ("System", "Void");
1086 type_type = CoreLookupType ("System", "Type");
1088 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle");
1089 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle");
1090 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers");
1091 default_member_type = CoreLookupType ("System.Reflection", "DefaultMemberAttribute");
1092 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle");
1093 asynccallback_type = CoreLookupType ("System", "AsyncCallback");
1094 iasyncresult_type = CoreLookupType ("System", "IAsyncResult");
1095 ienumerator_type = CoreLookupType ("System.Collections", "IEnumerator");
1096 ienumerable_type = CoreLookupType ("System.Collections", "IEnumerable");
1097 idisposable_type = CoreLookupType ("System", "IDisposable");
1098 icloneable_type = CoreLookupType ("System", "ICloneable");
1099 iconvertible_type = CoreLookupType ("System", "IConvertible");
1100 monitor_type = CoreLookupType ("System.Threading", "Monitor");
1101 intptr_type = CoreLookupType ("System", "IntPtr");
1103 attribute_type = CoreLookupType ("System", "Attribute");
1104 attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute");
1105 dllimport_type = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute");
1106 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute");
1107 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute");
1108 param_array_type = CoreLookupType ("System", "ParamArrayAttribute");
1109 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "InAttribute");
1110 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute");
1111 typed_reference_type = CoreLookupType ("System", "TypedReference");
1112 arg_iterator_type = CoreLookupType ("System", "ArgIterator");
1113 mbr_type = CoreLookupType ("System", "MarshalByRefObject");
1114 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
1116 unverifiable_code_type= CoreLookupType ("System.Security", "UnverifiableCodeAttribute");
1118 void_ptr_type = GetPointerType (void_type);
1120 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute");
1122 exception_type = CoreLookupType ("System", "Exception");
1123 invalid_operation_exception_type = CoreLookupType ("System", "InvalidOperationException");
1124 not_supported_exception_type = CoreLookupType ("System", "NotSupportedException");
1129 obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute");
1130 conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute");
1131 cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute");
1132 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute");
1133 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute");
1134 security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute");
1135 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute");
1136 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute");
1137 assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute");
1138 runtime_compatibility_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
1140 InitGenericCoreTypes ();
1145 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
1146 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute");
1147 default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
1149 // When compiling corlib, store the "real" types here.
1151 if (!RootContext.StdLib) {
1152 system_int32_type = typeof (System.Int32);
1153 system_array_type = typeof (System.Array);
1154 system_type_type = typeof (System.Type);
1155 system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1157 Type [] void_arg = { };
1158 system_int_array_get_length = GetMethod (
1159 system_array_type, "get_Length", void_arg);
1160 system_int_array_get_rank = GetMethod (
1161 system_array_type, "get_Rank", void_arg);
1162 system_object_array_clone = GetMethod (
1163 system_array_type, "Clone", void_arg);
1165 Type [] system_int_arg = { system_int32_type };
1166 system_int_array_get_length_int = GetMethod (
1167 system_array_type, "GetLength", system_int_arg);
1168 system_int_array_get_upper_bound_int = GetMethod (
1169 system_array_type, "GetUpperBound", system_int_arg);
1170 system_int_array_get_lower_bound_int = GetMethod (
1171 system_array_type, "GetLowerBound", system_int_arg);
1173 Type [] system_array_int_arg = { system_array_type, system_int32_type };
1174 system_void_array_copyto_array_int = GetMethod (
1175 system_array_type, "CopyTo", system_array_int_arg);
1177 Type [] system_3_type_arg = {
1178 system_type_type, system_type_type, system_type_type };
1179 Type [] system_4_type_arg = {
1180 system_type_type, system_type_type, system_type_type, system_type_type };
1182 MethodInfo set_corlib_type_builders = GetMethod (
1183 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1184 system_4_type_arg, true, false);
1186 if (set_corlib_type_builders != null) {
1187 object[] args = new object [4];
1188 args [0] = object_type;
1189 args [1] = value_type;
1190 args [2] = enum_type;
1191 args [3] = void_type;
1193 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1195 // Compatibility for an older version of the class libs.
1196 set_corlib_type_builders = GetMethod (
1197 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1198 system_3_type_arg, true, true);
1200 if (set_corlib_type_builders == null) {
1201 Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1205 object[] args = new object [3];
1206 args [0] = object_type;
1207 args [1] = value_type;
1208 args [2] = enum_type;
1210 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1214 system_object_expr.Type = object_type;
1215 system_string_expr.Type = string_type;
1216 system_boolean_expr.Type = bool_type;
1217 system_decimal_expr.Type = decimal_type;
1218 system_single_expr.Type = float_type;
1219 system_double_expr.Type = double_type;
1220 system_sbyte_expr.Type = sbyte_type;
1221 system_byte_expr.Type = byte_type;
1222 system_int16_expr.Type = short_type;
1223 system_uint16_expr.Type = ushort_type;
1224 system_int32_expr.Type = int32_type;
1225 system_uint32_expr.Type = uint32_type;
1226 system_int64_expr.Type = int64_type;
1227 system_uint64_expr.Type = uint64_type;
1228 system_char_expr.Type = char_type;
1229 system_void_expr.Type = void_type;
1230 system_asynccallback_expr.Type = asynccallback_type;
1231 system_iasyncresult_expr.Type = iasyncresult_type;
1232 system_valuetype_expr.Type = value_type;
1235 // These are only used for compare purposes
1237 anonymous_method_type = typeof (AnonymousMethod);
1238 null_type = typeof (NullType);
1242 // The helper methods that are used by the compiler
1244 public static void InitCodeHelpers ()
1247 // Now load the default methods that we use.
1249 Type [] string_string = { string_type, string_type };
1250 string_concat_string_string = GetMethod (
1251 string_type, "Concat", string_string);
1252 Type [] string_string_string = { string_type, string_type, string_type };
1253 string_concat_string_string_string = GetMethod (
1254 string_type, "Concat", string_string_string);
1255 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1256 string_concat_string_string_string_string = GetMethod (
1257 string_type, "Concat", string_string_string_string);
1258 Type[] params_string = { GetConstructedType (string_type, "[]") };
1259 string_concat_string_dot_dot_dot = GetMethod (
1260 string_type, "Concat", params_string);
1262 Type [] object_object = { object_type, object_type };
1263 string_concat_object_object = GetMethod (
1264 string_type, "Concat", object_object);
1265 Type [] object_object_object = { object_type, object_type, object_type };
1266 string_concat_object_object_object = GetMethod (
1267 string_type, "Concat", object_object_object);
1268 Type[] params_object = { GetConstructedType (object_type, "[]") };
1269 string_concat_object_dot_dot_dot = GetMethod (
1270 string_type, "Concat", params_object);
1272 Type [] string_ = { string_type };
1273 string_isinterneted_string = GetMethod (
1274 string_type, "IsInterned", string_);
1276 Type [] runtime_type_handle = { runtime_handle_type };
1277 system_type_get_type_from_handle = GetMethod (
1278 type_type, "GetTypeFromHandle", runtime_type_handle);
1280 Type [] delegate_delegate = { delegate_type, delegate_type };
1281 delegate_combine_delegate_delegate = GetMethod (
1282 delegate_type, "Combine", delegate_delegate);
1284 delegate_remove_delegate_delegate = GetMethod (
1285 delegate_type, "Remove", delegate_delegate);
1290 Type [] void_arg = { };
1291 ienumerator_getcurrent = GetProperty (
1292 ienumerator_type, "Current");
1293 bool_movenext_void = GetMethod (
1294 ienumerator_type, "MoveNext", void_arg);
1295 void_reset_void = GetMethod (
1296 ienumerator_type, "Reset", void_arg);
1297 void_dispose_void = GetMethod (
1298 idisposable_type, "Dispose", void_arg);
1299 int_get_offset_to_string_data = GetMethod (
1300 runtime_helpers_type, "get_OffsetToStringData", void_arg);
1301 int_array_get_length = GetMethod (
1302 array_type, "get_Length", void_arg);
1303 int_array_get_rank = GetMethod (
1304 array_type, "get_Rank", void_arg);
1305 ienumerable_getenumerator_void = GetMethod (
1306 ienumerable_type, "GetEnumerator", void_arg);
1311 Type [] int_arg = { int32_type };
1312 int_array_get_length_int = GetMethod (
1313 array_type, "GetLength", int_arg);
1314 int_array_get_upper_bound_int = GetMethod (
1315 array_type, "GetUpperBound", int_arg);
1316 int_array_get_lower_bound_int = GetMethod (
1317 array_type, "GetLowerBound", int_arg);
1320 // System.Array methods
1322 object_array_clone = GetMethod (
1323 array_type, "Clone", void_arg);
1324 Type [] array_int_arg = { array_type, int32_type };
1325 void_array_copyto_array_int = GetMethod (
1326 array_type, "CopyTo", array_int_arg);
1331 Type [] object_arg = { object_type };
1332 void_monitor_enter_object = GetMethod (
1333 monitor_type, "Enter", object_arg);
1334 void_monitor_exit_object = GetMethod (
1335 monitor_type, "Exit", object_arg);
1337 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1339 void_initializearray_array_fieldhandle = GetMethod (
1340 runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1345 int_getlength_int = GetMethod (
1346 array_type, "GetLength", int_arg);
1349 // Decimal constructors
1351 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1352 void_decimal_ctor_five_args = GetConstructor (
1353 decimal_type, dec_arg);
1355 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1360 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1361 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1362 default_member_ctor = GetConstructor (default_member_type, string_);
1364 Type[] short_arg = { short_type };
1365 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1367 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1368 { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1370 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1376 compiler_generated_attr = new CustomAttributeBuilder (
1377 GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1379 Type[] type_int_arg = { type_type, int32_type };
1380 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1383 object_ctor = GetConstructor (object_type, void_arg);
1385 InitGenericCodeHelpers ();
1388 const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1391 /// This is the "old", non-cache based FindMembers() function. We cannot use
1392 /// the cache here because there is no member name argument.
1394 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1395 MemberFilter filter, object criteria)
1397 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1400 // `builder_to_declspace' contains all dynamic types.
1404 Timer.StartTimer (TimerType.FindMembers);
1405 list = decl.FindMembers (mt, bf, filter, criteria);
1406 Timer.StopTimer (TimerType.FindMembers);
1411 // We have to take care of arrays specially, because GetType on
1412 // a TypeBuilder array will return a Type, not a TypeBuilder,
1413 // and we can not call FindMembers on this type.
1415 if (t.IsSubclassOf (TypeManager.array_type))
1416 return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1418 if (t is GenericTypeParameterBuilder) {
1419 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1421 Timer.StartTimer (TimerType.FindMembers);
1422 MemberList list = tparam.FindMembers (
1423 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1424 Timer.StopTimer (TimerType.FindMembers);
1429 // Since FindMembers will not lookup both static and instance
1430 // members, we emulate this behaviour here.
1432 if ((bf & instance_and_static) == instance_and_static){
1433 MemberInfo [] i_members = t.FindMembers (
1434 mt, bf & ~BindingFlags.Static, filter, criteria);
1436 int i_len = i_members.Length;
1438 MemberInfo one = i_members [0];
1441 // If any of these are present, we are done!
1443 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1444 return new MemberList (i_members);
1447 MemberInfo [] s_members = t.FindMembers (
1448 mt, bf & ~BindingFlags.Instance, filter, criteria);
1450 int s_len = s_members.Length;
1451 if (i_len > 0 || s_len > 0)
1452 return new MemberList (i_members, s_members);
1455 return new MemberList (i_members);
1457 return new MemberList (s_members);
1461 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1466 /// This method is only called from within MemberLookup. It tries to use the member
1467 /// cache if possible and falls back to the normal FindMembers if not. The `used_cache'
1468 /// flag tells the caller whether we used the cache or not. If we used the cache, then
1469 /// our return value will already contain all inherited members and the caller don't need
1470 /// to check base classes and interfaces anymore.
1472 private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1473 string name, out bool used_cache)
1478 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1479 // and we can ask the DeclSpace for the MemberCache.
1481 if (t is TypeBuilder) {
1482 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1483 cache = decl.MemberCache;
1486 // If this DeclSpace has a MemberCache, use it.
1489 if (cache != null) {
1491 return cache.FindMembers (
1492 mt, bf, name, FilterWithClosure_delegate, null);
1495 // If there is no MemberCache, we need to use the "normal" FindMembers.
1496 // Note, this is a VERY uncommon route!
1499 Timer.StartTimer (TimerType.FindMembers);
1500 list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1501 FilterWithClosure_delegate, name);
1502 Timer.StopTimer (TimerType.FindMembers);
1504 return (MemberInfo []) list;
1508 // We have to take care of arrays specially, because GetType on
1509 // a TypeBuilder array will return a Type, not a TypeBuilder,
1510 // and we can not call FindMembers on this type.
1512 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1514 return TypeHandle.ArrayType.MemberCache.FindMembers (
1515 mt, bf, name, FilterWithClosure_delegate, null);
1518 if (t is GenericTypeParameterBuilder) {
1519 TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1522 Timer.StartTimer (TimerType.FindMembers);
1523 list = tparam.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1524 FilterWithClosure_delegate, name);
1525 Timer.StopTimer (TimerType.FindMembers);
1527 return (MemberInfo []) list;
1530 if (t.IsGenericInstance && (mt == MemberTypes.NestedType)) {
1532 // This happens if we're resolving a class'es base class and interfaces
1533 // in TypeContainer.DefineType(). At this time, the types aren't
1534 // populated yet, so we can't use the cache.
1536 MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1537 FilterWithClosure_delegate, name);
1543 // This call will always succeed. There is exactly one TypeHandle instance per
1544 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1545 // the corresponding MemberCache.
1547 cache = TypeHandle.GetMemberCache (t);
1550 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1553 public static bool IsBuiltinType (Type t)
1555 t = TypeToCoreType (t);
1556 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1557 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1558 t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1559 t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1565 public static bool IsBuiltinType (TypeContainer tc)
1567 return IsBuiltinType (tc.TypeBuilder);
1571 // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1572 // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1574 public static bool IsPrimitiveType (Type t)
1576 return (t == int32_type || t == uint32_type ||
1577 t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1578 t == char_type || t == short_type || t == bool_type ||
1579 t == sbyte_type || t == byte_type || t == ushort_type);
1582 public static bool IsDelegateType (Type t)
1584 if (t.IsGenericInstance)
1585 t = t.GetGenericTypeDefinition ();
1587 if (t.IsSubclassOf (TypeManager.delegate_type))
1593 public static bool IsEnumType (Type t)
1595 if (builder_to_declspace [t] is Enum)
1601 public static bool IsBuiltinOrEnum (Type t)
1603 if (IsBuiltinType (t))
1612 public static bool IsNullType (Type t)
1614 return t == null_type;
1617 public static bool IsAttributeType (Type t)
1619 return (t == attribute_type) || t.IsSubclassOf (attribute_type);
1622 static Stack unmanaged_enclosing_types = new Stack (4);
1625 // Whether a type is unmanaged. This is used by the unsafe code (25.2)
1627 public static bool IsUnmanagedType (Type t)
1629 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1630 if (unmanaged_enclosing_types.Contains (t))
1633 // builtins that are not unmanaged types
1634 if (t == TypeManager.object_type || t == TypeManager.string_type)
1637 if (IsBuiltinOrEnum (t))
1640 // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it.
1644 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1648 if (!IsValueType (t))
1651 unmanaged_enclosing_types.Push (t);
1655 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1656 if (p.IsGenericTypeDefinition) {
1662 if (t is TypeBuilder && retval) {
1663 TypeContainer tc = LookupTypeContainer (t);
1664 if (tc.Fields != null){
1665 foreach (Field f in tc.Fields){
1666 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1667 if ((f.ModFlags & Modifiers.STATIC) != 0)
1669 if (f.MemberType == null)
1671 if (!IsUnmanagedType (f.MemberType)){
1672 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1677 } else if (retval) {
1678 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1680 foreach (FieldInfo f in fields){
1681 if (!IsUnmanagedType (f.FieldType)){
1682 Report.SymbolRelatedToPreviousError (f);
1688 unmanaged_enclosing_types.Pop ();
1693 public static bool IsValueType (Type t)
1695 return t.IsGenericParameter || t.IsValueType;
1698 public static bool IsInterfaceType (Type t)
1700 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1704 return tc.Kind == Kind.Interface;
1707 public static bool IsSubclassOf (Type type, Type base_type)
1709 TypeParameter tparam = LookupTypeParameter (type);
1710 TypeParameter pparam = LookupTypeParameter (base_type);
1712 if ((tparam != null) && (pparam != null)) {
1713 if (tparam == pparam)
1716 return tparam.IsSubclassOf (base_type);
1720 if (IsEqual (type, base_type))
1723 type = type.BaseType;
1724 } while (type != null);
1729 public static bool IsPrivateAccessible (Type type, Type parent)
1731 if (type.Equals (parent))
1734 if ((type is TypeBuilder) && type.IsGenericTypeDefinition && parent.IsGenericInstance) {
1736 // `a' is a generic type definition's TypeBuilder and `b' is a
1737 // generic instance of the same type.
1743 // void Test (Stack<T> stack) { }
1746 // The first argument of `Test' will be the generic instance
1747 // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
1750 // We hit this via Closure.Filter() for gen-82.cs.
1752 if (type != parent.GetGenericTypeDefinition ())
1758 if (type.IsGenericInstance && parent.IsGenericInstance) {
1759 if (type.GetGenericTypeDefinition () != parent.GetGenericTypeDefinition ())
1768 public static bool IsFamilyAccessible (Type type, Type parent)
1770 TypeParameter tparam = LookupTypeParameter (type);
1771 TypeParameter pparam = LookupTypeParameter (parent);
1773 if ((tparam != null) && (pparam != null)) {
1774 if (tparam == pparam)
1777 return tparam.IsSubclassOf (parent);
1781 if (IsInstantiationOfSameGenericType (type, parent))
1784 type = type.BaseType;
1785 } while (type != null);
1791 // Checks whether `type' is a subclass or nested child of `base_type'.
1793 public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1796 if (IsFamilyAccessible (type, base_type))
1799 // Handle nested types.
1800 type = type.DeclaringType;
1801 } while (type != null);
1807 // Checks whether `type' is a nested child of `parent'.
1809 public static bool IsNestedChildOf (Type type, Type parent)
1811 if (IsEqual (type, parent))
1814 type = type.DeclaringType;
1815 while (type != null) {
1816 if (IsEqual (type, parent))
1819 type = type.DeclaringType;
1826 // Do the right thing when returning the element type of an
1827 // array type based on whether we are compiling corlib or not
1829 public static Type GetElementType (Type t)
1831 if (RootContext.StdLib)
1832 return t.GetElementType ();
1834 return TypeToCoreType (t.GetElementType ());
1838 /// This method is not implemented by MS runtime for dynamic types
1840 public static bool HasElementType (Type t)
1842 return t.IsArray || t.IsPointer || t.IsByRef;
1846 /// Gigantic work around for missing features in System.Reflection.Emit follows.
1850 /// Since System.Reflection.Emit can not return MethodBase.GetParameters
1851 /// for anything which is dynamic, and we need this in a number of places,
1852 /// we register this information here, and use it afterwards.
1854 static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1859 method_arguments.Add (mb, args);
1860 method_params.Add (mb, ip);
1863 static public ParameterData GetParameterData (MethodBase mb)
1865 object pd = method_params [mb];
1867 if (mb is MethodBuilder || mb is ConstructorBuilder)
1868 throw new InternalErrorException ("Argument for Method not registered" + mb);
1870 method_params [mb] = pd = new ReflectionParameters (mb);
1873 return (ParameterData) pd;
1876 static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1878 if (method_overrides.Contains (override_method)) {
1879 if (method_overrides [override_method] != base_method)
1880 throw new InternalErrorException ("Override mismatch: " + override_method);
1883 method_overrides [override_method] = base_method;
1886 static public bool IsOverride (MethodBase m)
1888 return m.IsVirtual &&
1889 (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1890 (m is MethodBuilder || method_overrides.Contains (m));
1894 /// Returns the argument types for a method based on its methodbase
1896 /// For dynamic methods, we use the compiler provided types, for
1897 /// methods from existing assemblies we load them from GetParameters,
1898 /// and insert them into the cache
1900 static public Type [] GetArgumentTypes (MethodBase mb)
1902 object t = method_arguments [mb];
1906 ParameterInfo [] pi = mb.GetParameters ();
1913 types = new Type [c];
1914 for (int i = 0; i < c; i++)
1915 types [i] = pi [i].ParameterType;
1917 method_arguments.Add (mb, types);
1922 /// Returns the argument types for an indexer based on its PropertyInfo
1924 /// For dynamic indexers, we use the compiler provided types, for
1925 /// indexers from existing assemblies we load them from GetParameters,
1926 /// and insert them into the cache
1928 static public Type [] GetArgumentTypes (PropertyInfo indexer)
1930 if (indexer_arguments.Contains (indexer))
1931 return (Type []) indexer_arguments [indexer];
1932 else if (indexer is PropertyBuilder)
1933 // If we're a PropertyBuilder and not in the
1934 // `indexer_arguments' hash, then we're a property and
1938 ParameterInfo [] pi = indexer.GetIndexParameters ();
1939 // Property, not an indexer.
1943 Type [] types = new Type [c];
1945 for (int i = 0; i < c; i++)
1946 types [i] = pi [i].ParameterType;
1948 indexer_arguments.Add (indexer, types);
1953 public static void RegisterConstant (FieldInfo fb, IConstant ic)
1955 fields.Add (fb, ic);
1958 public static IConstant GetConstant (FieldInfo fb)
1963 return (IConstant)fields [fb];
1966 static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1968 if (fieldbuilders_to_fields.Contains (fb))
1971 fieldbuilders_to_fields.Add (fb, f);
1976 // The return value can be null; This will be the case for
1977 // auxiliary FieldBuilders created by the compiler that have no
1978 // real field being declared on the source code
1980 static public FieldBase GetField (FieldInfo fb)
1982 if (fb.DeclaringType.IsGenericInstance)
1983 fb = fb.Mono_GetGenericFieldDefinition ();
1985 return (FieldBase) fieldbuilders_to_fields [fb];
1988 static Hashtable events;
1990 static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1993 events = new Hashtable ();
1995 if (!events.Contains (eb)) {
1996 events.Add (eb, new Pair (add, remove));
2000 static public MethodInfo GetAddMethod (EventInfo ei)
2002 if (ei is MyEventBuilder) {
2003 Pair pair = (Pair) events [ei];
2005 return (MethodInfo) pair.First;
2007 return ei.GetAddMethod (true);
2010 static public MethodInfo GetRemoveMethod (EventInfo ei)
2012 if (ei is MyEventBuilder) {
2013 Pair pair = (Pair) events [ei];
2015 return (MethodInfo) pair.Second;
2017 return ei.GetRemoveMethod (true);
2020 static Hashtable priv_fields_events;
2022 static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
2024 if (priv_fields_events == null)
2025 priv_fields_events = new Hashtable ();
2027 if (priv_fields_events.Contains (einfo))
2030 priv_fields_events.Add (einfo, builder);
2035 static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
2037 if (priv_fields_events == null)
2040 return (MemberInfo) priv_fields_events [ei];
2043 static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
2044 MethodBase set, Type[] args)
2046 indexer_arguments.Add (pb, args);
2051 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
2053 Hashtable hash = new Hashtable ();
2054 return CheckStructCycles (tc, seen, hash);
2057 public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
2060 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
2064 // `seen' contains all types we've already visited.
2066 if (seen.Contains (tc))
2068 seen.Add (tc, null);
2070 if (tc.Fields == null)
2073 foreach (FieldMember field in tc.Fields) {
2074 if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
2077 Type ftype = field.FieldBuilder.FieldType;
2078 TypeContainer ftc = LookupTypeContainer (ftype);
2082 if (hash.Contains (ftc)) {
2083 Report.Error (523, tc.Location,
2084 "Struct member `{0}.{1}' of type `{2}' " +
2085 "causes a cycle in the struct layout",
2086 tc.Name, field.Name, ftc.Name);
2091 // `hash' contains all types in the current path.
2093 hash.Add (tc, null);
2095 bool ok = CheckStructCycles (ftc, seen, hash);
2102 if (!seen.Contains (ftc))
2103 seen.Add (ftc, null);
2110 /// Given an array of interface types, expand and eliminate repeated ocurrences
2111 /// of an interface.
2115 /// This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
2118 public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
2120 ArrayList new_ifaces = new ArrayList ();
2122 foreach (TypeExpr iface in base_interfaces){
2123 TypeExpr texpr = iface.ResolveAsTypeTerminal (ec);
2127 Type itype = texpr.ResolveType (ec);
2129 if (new_ifaces.Contains (itype))
2132 new_ifaces.Add (itype);
2134 Type [] implementing = itype.GetInterfaces ();
2136 foreach (Type imp in implementing){
2137 if (!new_ifaces.Contains (imp))
2138 new_ifaces.Add (imp);
2141 Type [] ret = new Type [new_ifaces.Count];
2142 new_ifaces.CopyTo (ret, 0);
2146 static PtrHashtable iface_cache = new PtrHashtable ();
2149 /// This function returns the interfaces in the type `t'. Works with
2150 /// both types and TypeBuilders.
2152 public static Type [] GetInterfaces (Type t)
2154 Type [] cached = iface_cache [t] as Type [];
2159 // The reason for catching the Array case is that Reflection.Emit
2160 // will not return a TypeBuilder for Array types of TypeBuilder types,
2161 // but will still throw an exception if we try to call GetInterfaces
2164 // Since the array interfaces are always constant, we return those for
2169 t = TypeManager.array_type;
2171 if ((t is TypeBuilder) || t.IsGenericInstance) {
2172 Type [] base_ifaces;
2174 if (t.BaseType == null)
2175 base_ifaces = NoTypes;
2177 base_ifaces = GetInterfaces (t.BaseType);
2179 if (t.IsGenericInstance)
2180 type_ifaces = t.GetInterfaces ();
2182 type_ifaces = (Type []) builder_to_ifaces [t];
2183 if (type_ifaces == null)
2184 type_ifaces = NoTypes;
2186 int base_count = base_ifaces.Length;
2187 Type [] result = new Type [base_count + type_ifaces.Length];
2188 base_ifaces.CopyTo (result, 0);
2189 type_ifaces.CopyTo (result, base_count);
2191 iface_cache [t] = result;
2193 } else if (t is GenericTypeParameterBuilder){
2194 Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2195 if (type_ifaces == null)
2196 type_ifaces = NoTypes;
2198 iface_cache [t] = type_ifaces;
2201 Type[] ifaces = t.GetInterfaces ();
2202 iface_cache [t] = ifaces;
2208 // gets the interfaces that are declared explicitly on t
2210 public static Type [] GetExplicitInterfaces (TypeBuilder t)
2212 return (Type []) builder_to_ifaces [t];
2216 /// The following is used to check if a given type implements an interface.
2217 /// The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2219 public static bool ImplementsInterface (Type t, Type iface)
2224 // FIXME OPTIMIZATION:
2225 // as soon as we hit a non-TypeBuiler in the interface
2226 // chain, we could return, as the `Type.GetInterfaces'
2227 // will return all the interfaces implement by the type
2231 interfaces = GetInterfaces (t);
2233 if (interfaces != null){
2234 foreach (Type i in interfaces){
2241 } while (t != null);
2246 static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2248 // This is a custom version of Convert.ChangeType() which works
2249 // with the TypeBuilder defined types when compiling corlib.
2250 public static object ChangeType (object value, Type conversionType, out bool error)
2252 IConvertible convert_value = value as IConvertible;
2254 if (convert_value == null){
2260 // We must use Type.Equals() here since `conversionType' is
2261 // the TypeBuilder created version of a system type and not
2262 // the system type itself. You cannot use Type.GetTypeCode()
2263 // on such a type - it'd always return TypeCode.Object.
2267 if (conversionType.Equals (typeof (Boolean)))
2268 return (object)(convert_value.ToBoolean (nf_provider));
2269 else if (conversionType.Equals (typeof (Byte)))
2270 return (object)(convert_value.ToByte (nf_provider));
2271 else if (conversionType.Equals (typeof (Char)))
2272 return (object)(convert_value.ToChar (nf_provider));
2273 else if (conversionType.Equals (typeof (DateTime)))
2274 return (object)(convert_value.ToDateTime (nf_provider));
2275 else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2276 return (object)(convert_value.ToDecimal (nf_provider));
2277 else if (conversionType.Equals (typeof (Double)))
2278 return (object)(convert_value.ToDouble (nf_provider));
2279 else if (conversionType.Equals (typeof (Int16)))
2280 return (object)(convert_value.ToInt16 (nf_provider));
2281 else if (conversionType.Equals (typeof (Int32)))
2282 return (object)(convert_value.ToInt32 (nf_provider));
2283 else if (conversionType.Equals (typeof (Int64)))
2284 return (object)(convert_value.ToInt64 (nf_provider));
2285 else if (conversionType.Equals (typeof (SByte)))
2286 return (object)(convert_value.ToSByte (nf_provider));
2287 else if (conversionType.Equals (typeof (Single)))
2288 return (object)(convert_value.ToSingle (nf_provider));
2289 else if (conversionType.Equals (typeof (String)))
2290 return (object)(convert_value.ToString (nf_provider));
2291 else if (conversionType.Equals (typeof (UInt16)))
2292 return (object)(convert_value.ToUInt16 (nf_provider));
2293 else if (conversionType.Equals (typeof (UInt32)))
2294 return (object)(convert_value.ToUInt32 (nf_provider));
2295 else if (conversionType.Equals (typeof (UInt64)))
2296 return (object)(convert_value.ToUInt64 (nf_provider));
2297 else if (conversionType.Equals (typeof (Object)))
2298 return (object)(value);
2308 // This is needed, because enumerations from assemblies
2309 // do not report their underlyingtype, but they report
2312 public static Type EnumToUnderlying (Type t)
2314 if (t == TypeManager.enum_type)
2317 t = t.UnderlyingSystemType;
2318 if (!TypeManager.IsEnumType (t))
2321 if (t is TypeBuilder) {
2322 // slow path needed to compile corlib
2323 if (t == TypeManager.bool_type ||
2324 t == TypeManager.byte_type ||
2325 t == TypeManager.sbyte_type ||
2326 t == TypeManager.char_type ||
2327 t == TypeManager.short_type ||
2328 t == TypeManager.ushort_type ||
2329 t == TypeManager.int32_type ||
2330 t == TypeManager.uint32_type ||
2331 t == TypeManager.int64_type ||
2332 t == TypeManager.uint64_type)
2335 TypeCode tc = Type.GetTypeCode (t);
2338 case TypeCode.Boolean:
2339 return TypeManager.bool_type;
2341 return TypeManager.byte_type;
2342 case TypeCode.SByte:
2343 return TypeManager.sbyte_type;
2345 return TypeManager.char_type;
2346 case TypeCode.Int16:
2347 return TypeManager.short_type;
2348 case TypeCode.UInt16:
2349 return TypeManager.ushort_type;
2350 case TypeCode.Int32:
2351 return TypeManager.int32_type;
2352 case TypeCode.UInt32:
2353 return TypeManager.uint32_type;
2354 case TypeCode.Int64:
2355 return TypeManager.int64_type;
2356 case TypeCode.UInt64:
2357 return TypeManager.uint64_type;
2359 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2363 // When compiling corlib and called with one of the core types, return
2364 // the corresponding typebuilder for that type.
2366 public static Type TypeToCoreType (Type t)
2368 if (RootContext.StdLib || (t is TypeBuilder))
2371 TypeCode tc = Type.GetTypeCode (t);
2374 case TypeCode.Boolean:
2375 return TypeManager.bool_type;
2377 return TypeManager.byte_type;
2378 case TypeCode.SByte:
2379 return TypeManager.sbyte_type;
2381 return TypeManager.char_type;
2382 case TypeCode.Int16:
2383 return TypeManager.short_type;
2384 case TypeCode.UInt16:
2385 return TypeManager.ushort_type;
2386 case TypeCode.Int32:
2387 return TypeManager.int32_type;
2388 case TypeCode.UInt32:
2389 return TypeManager.uint32_type;
2390 case TypeCode.Int64:
2391 return TypeManager.int64_type;
2392 case TypeCode.UInt64:
2393 return TypeManager.uint64_type;
2394 case TypeCode.Single:
2395 return TypeManager.float_type;
2396 case TypeCode.Double:
2397 return TypeManager.double_type;
2398 case TypeCode.String:
2399 return TypeManager.string_type;
2400 case TypeCode.Decimal:
2401 return TypeManager.decimal_type;
2403 if (t == typeof (void))
2404 return TypeManager.void_type;
2405 if (t == typeof (object))
2406 return TypeManager.object_type;
2407 if (t == typeof (System.Type))
2408 return TypeManager.type_type;
2409 if (t == typeof (System.IntPtr))
2410 return TypeManager.intptr_type;
2416 /// Utility function that can be used to probe whether a type
2417 /// is managed or not.
2419 public static bool VerifyUnManaged (Type t, Location loc)
2421 if (IsUnmanagedType (t))
2424 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2431 /// Returns the name of the indexer in a given type.
2434 /// The default is not always `Item'. The user can change this behaviour by
2435 /// using the IndexerNameAttribute in the container.
2437 /// For example, the String class indexer is named `Chars' not `Item'
2439 public static string IndexerPropertyName (Type t)
2441 if (t.IsGenericInstance)
2442 t = t.GetGenericTypeDefinition ();
2444 if (t is TypeBuilder) {
2445 TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2446 return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2449 System.Attribute attr = System.Attribute.GetCustomAttribute (
2450 t, TypeManager.default_member_type);
2452 DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2453 return dma.MemberName;
2456 return TypeContainer.DefaultIndexerName;
2459 static MethodInfo declare_local_method = null;
2461 public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2463 if (declare_local_method == null){
2464 declare_local_method = typeof (ILGenerator).GetMethod (
2466 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2468 new Type [] { typeof (Type), typeof (bool)},
2470 if (declare_local_method == null){
2471 Report.Warning (-30, new Location (-1),
2472 "This version of the runtime does not support making pinned local variables. " +
2473 "This code may cause errors on a runtime with a moving GC");
2474 return ig.DeclareLocal (t);
2477 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2481 // Returns whether the array of memberinfos contains the given method
2483 public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2485 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2487 foreach (MethodBase method in array) {
2488 if (method.Name != new_method.Name)
2491 if (method is MethodInfo && new_method is MethodInfo)
2492 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2496 Type [] old_args = TypeManager.GetArgumentTypes (method);
2497 int old_count = old_args.Length;
2500 if (new_args.Length != old_count)
2503 for (i = 0; i < old_count; i++){
2504 if (old_args [i] != new_args [i])
2517 // We copy methods from `new_members' into `target_list' if the signature
2518 // for the method from in the new list does not exist in the target_list
2520 // The name is assumed to be the same.
2522 public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2524 if (target_list == null){
2525 target_list = new ArrayList ();
2527 foreach (MemberInfo mi in new_members){
2528 if (mi is MethodBase)
2529 target_list.Add (mi);
2534 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2535 target_list.CopyTo (target_array, 0);
2537 foreach (MemberInfo mi in new_members){
2538 MethodBase new_method = (MethodBase) mi;
2540 if (!ArrayContainsMethod (target_array, new_method))
2541 target_list.Add (new_method);
2546 #region MemberLookup implementation
2549 // Whether we allow private members in the result (since FindMembers
2550 // uses NonPublic for both protected and private), we need to distinguish.
2553 static internal bool FilterNone (MemberInfo m, object filter_criteria)
2558 internal class Closure {
2559 internal bool private_ok;
2561 // Who is invoking us and which type is being queried currently.
2562 internal Type invocation_type;
2563 internal Type qualifier_type;
2565 // The assembly that defines the type is that is calling us
2566 internal Assembly invocation_assembly;
2567 internal IList almost_match;
2569 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2571 if (invocation_type == null)
2574 if (is_static && qualifier_type == null)
2575 // It resolved from a simple name, so it should be visible.
2578 // A nested class has access to all the protected members visible to its parent.
2579 if (qualifier_type != null && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2582 if (IsNestedFamilyAccessible (invocation_type, m.DeclaringType)) {
2583 // Although a derived class can access protected members of its base class
2584 // it cannot do so through an instance of the base class (CS1540).
2585 // => Ancestry should be: declaring_type ->* invocation_type ->* qualified_type
2587 qualifier_type == null ||
2588 IsInstantiationOfSameGenericType (invocation_type, qualifier_type) ||
2589 !IsFamilyAccessible (invocation_type, qualifier_type) ||
2590 IsNestedChildOf (invocation_type, qualifier_type))
2594 if (almost_match != null)
2595 almost_match.Add (m);
2601 // This filter filters by name + whether it is ok to include private
2602 // members in the search
2604 internal bool Filter (MemberInfo m, object filter_criteria)
2607 // Hack: we know that the filter criteria will always be in the
2608 // `closure' // fields.
2611 if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2614 if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2615 (invocation_type != null) &&
2616 IsPrivateAccessible (m.DeclaringType, invocation_type))
2620 // Ugly: we need to find out the type of `m', and depending
2621 // on this, tell whether we accept or not
2623 if (m is MethodBase){
2624 MethodBase mb = (MethodBase) m;
2625 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2627 if (ma == MethodAttributes.Private)
2628 return private_ok ||
2629 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2630 IsNestedChildOf (invocation_type, m.DeclaringType);
2632 if (invocation_assembly == mb.DeclaringType.Assembly) {
2633 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2636 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2640 if (ma == MethodAttributes.Family ||
2641 ma == MethodAttributes.FamANDAssem ||
2642 ma == MethodAttributes.FamORAssem)
2643 return CheckValidFamilyAccess (mb.IsStatic, m);
2649 if (m is FieldInfo){
2650 FieldInfo fi = (FieldInfo) m;
2651 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2653 if (fa == FieldAttributes.Private)
2654 return private_ok ||
2655 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2656 IsNestedChildOf (invocation_type, m.DeclaringType);
2658 if (invocation_assembly == fi.DeclaringType.Assembly) {
2659 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamORAssem)
2662 if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamANDAssem)
2666 if (fa == FieldAttributes.Family ||
2667 fa == FieldAttributes.FamANDAssem ||
2668 fa == FieldAttributes.FamORAssem)
2669 return CheckValidFamilyAccess (fi.IsStatic, m);
2676 // EventInfos and PropertyInfos, return true because they lack
2677 // permission information, so we need to check later on the methods.
2683 static Closure closure = new Closure ();
2684 static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2687 // Looks up a member called `name' in the `queried_type'. This lookup
2688 // is done by code that is contained in the definition for `invocation_type'
2689 // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2691 // `invocation_type' is used to check whether we're allowed to access the requested
2692 // member wrt its protection level.
2694 // When called from MemberAccess, `qualifier_type' is the type which is used to access
2695 // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2696 // is B and qualifier_type is A). This is used to do the CS1540 check.
2698 // When resolving a SimpleName, `qualifier_type' is null.
2700 // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2701 // the same than `queried_type' - except when we're being called from BaseAccess;
2702 // in this case, `invocation_type' is the current type and `queried_type' the base
2703 // type, so this'd normally trigger a CS1540.
2705 // The binding flags are `bf' and the kind of members being looked up are `mt'
2707 // The return value always includes private members which code in `invocation_type'
2708 // is allowed to access (using the specified `qualifier_type' if given); only use
2709 // BindingFlags.NonPublic to bypass the permission check.
2711 // The 'almost_match' argument is used for reporting error CS1540.
2713 // Returns an array of a single element for everything but Methods/Constructors
2714 // that might return multiple matches.
2716 public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2717 Type queried_type, MemberTypes mt,
2718 BindingFlags original_bf, string name, IList almost_match)
2720 Timer.StartTimer (TimerType.MemberLookup);
2722 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2723 queried_type, mt, original_bf, name, almost_match);
2725 Timer.StopTimer (TimerType.MemberLookup);
2730 static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2731 Type queried_type, MemberTypes mt,
2732 BindingFlags original_bf, string name, IList almost_match)
2734 BindingFlags bf = original_bf;
2736 ArrayList method_list = null;
2737 Type current_type = queried_type;
2738 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2739 bool skip_iface_check = true, used_cache = false;
2740 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2742 closure.invocation_type = invocation_type;
2743 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2744 closure.qualifier_type = qualifier_type;
2745 closure.almost_match = almost_match;
2747 // This is from the first time we find a method
2748 // in most cases, we do not actually find a method in the base class
2749 // so we can just ignore it, and save the arraylist allocation
2750 MemberInfo [] first_members_list = null;
2751 bool use_first_members_list = false;
2757 // `NonPublic' is lame, because it includes both protected and
2758 // private methods, so we need to control this behavior by
2759 // explicitly tracking if a private method is ok or not.
2761 // The possible cases are:
2762 // public, private and protected (internal does not come into the
2765 if ((invocation_type != null) &&
2766 ((invocation_type == current_type) ||
2767 IsNestedChildOf (invocation_type, current_type)) ||
2769 bf = original_bf | BindingFlags.NonPublic;
2773 closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2775 Timer.StopTimer (TimerType.MemberLookup);
2777 list = MemberLookup_FindMembers (
2778 current_type, mt, bf, name, out used_cache);
2780 Timer.StartTimer (TimerType.MemberLookup);
2783 // When queried for an interface type, the cache will automatically check all
2784 // inherited members, so we don't need to do this here. However, this only
2785 // works if we already used the cache in the first iteration of this loop.
2787 // If we used the cache in any further iteration, we can still terminate the
2788 // loop since the cache always looks in all base classes.
2794 skip_iface_check = false;
2796 if (current_type == TypeManager.object_type)
2799 current_type = current_type.BaseType;
2802 // This happens with interfaces, they have a null
2803 // basetype. Look members up in the Object class.
2805 if (current_type == null) {
2806 current_type = TypeManager.object_type;
2811 if (list.Length == 0)
2815 // Events and types are returned by both `static' and `instance'
2816 // searches, which means that our above FindMembers will
2817 // return two copies of the same.
2819 if (list.Length == 1 && !(list [0] is MethodBase)){
2824 // Multiple properties: we query those just to find out the indexer
2827 if (list [0] is PropertyInfo)
2831 // We found an event: the cache lookup returns both the event and
2832 // its private field.
2834 if (list [0] is EventInfo) {
2835 if ((list.Length == 2) && (list [1] is FieldInfo))
2836 return new MemberInfo [] { list [0] };
2843 // We found methods, turn the search into "method scan"
2847 if (first_members_list != null) {
2848 if (use_first_members_list) {
2849 method_list = CopyNewMethods (method_list, first_members_list);
2850 use_first_members_list = false;
2853 method_list = CopyNewMethods (method_list, list);
2855 first_members_list = list;
2856 use_first_members_list = true;
2858 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2860 } while (searching);
2862 if (use_first_members_list) {
2863 foreach (MemberInfo mi in first_members_list) {
2864 if (! (mi is MethodBase)) {
2865 method_list = CopyNewMethods (method_list, first_members_list);
2866 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2869 return (MemberInfo []) first_members_list;
2872 if (method_list != null && method_list.Count > 0) {
2873 return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2876 // This happens if we already used the cache in the first iteration, in this case
2877 // the cache already looked in all interfaces.
2879 if (skip_iface_check)
2883 // Interfaces do not list members they inherit, so we have to
2886 if (!queried_type.IsInterface)
2889 if (queried_type.IsArray)
2890 queried_type = TypeManager.array_type;
2892 Type [] ifaces = GetInterfaces (queried_type);
2896 foreach (Type itype in ifaces){
2899 x = MemberLookup (null, null, itype, mt, bf, name, null);
2907 // Tests whether external method is really special
2908 public static bool IsSpecialMethod (MethodBase mb)
2910 string name = mb.Name;
2911 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2912 return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2914 if (name.StartsWith ("add_"))
2915 return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2917 if (name.StartsWith ("remove_"))
2918 return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2920 if (name.StartsWith ("op_")){
2921 foreach (string oname in Unary.oper_names) {
2926 foreach (string oname in Binary.oper_names) {
2939 /// There is exactly one instance of this class per type.
2941 public sealed class TypeHandle : IMemberContainer {
2942 public readonly IMemberContainer BaseType;
2944 readonly int id = ++next_id;
2945 static int next_id = 0;
2947 static TypeHandle ()
2953 /// Lookup a TypeHandle instance for the given type. If the type doesn't have
2954 /// a TypeHandle yet, a new instance of it is created. This static method
2955 /// ensures that we'll only have one TypeHandle instance per type.
2957 private static TypeHandle GetTypeHandle (Type t)
2959 TypeHandle handle = (TypeHandle) type_hash [t];
2963 handle = new TypeHandle (t);
2964 type_hash.Add (t, handle);
2968 public static MemberCache GetMemberCache (Type t)
2970 return GetTypeHandle (t).MemberCache;
2973 public static void CleanUp ()
2978 public static void Reset ()
2980 type_hash = new PtrHashtable ();
2984 /// Returns the TypeHandle for TypeManager.object_type.
2986 public static IMemberContainer ObjectType {
2988 if (object_type != null)
2991 object_type = GetTypeHandle (TypeManager.object_type);
2998 /// Returns the TypeHandle for TypeManager.array_type.
3000 public static IMemberContainer ArrayType {
3002 if (array_type != null)
3005 array_type = GetTypeHandle (TypeManager.array_type);
3011 private static PtrHashtable type_hash;
3013 private static TypeHandle object_type = null;
3014 private static TypeHandle array_type = null;
3017 private string full_name;
3018 private bool is_interface;
3019 private MemberCache member_cache;
3020 private MemberCache base_cache;
3022 private TypeHandle (Type type)
3025 full_name = type.FullName != null ? type.FullName : type.Name;
3026 if (type.BaseType != null) {
3027 base_cache = TypeManager.LookupMemberCache (type.BaseType);
3028 BaseType = base_cache.Container;
3029 } else if (type.IsInterface)
3030 base_cache = TypeManager.LookupBaseInterfacesCache (type);
3031 this.is_interface = type.IsInterface || type.IsGenericParameter;
3032 this.member_cache = new MemberCache (this);
3035 // IMemberContainer methods
3037 public string Name {
3049 public MemberCache BaseCache {
3055 public bool IsInterface {
3057 return is_interface;
3061 public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3063 MemberInfo [] members;
3064 if (type is GenericTypeParameterBuilder)
3065 return MemberList.Empty;
3066 if (mt == MemberTypes.Event)
3067 members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3069 members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3071 Array.Reverse (members);
3073 return new MemberList (members);
3076 // IMemberFinder methods
3078 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3079 MemberFilter filter, object criteria)
3081 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3084 public MemberCache MemberCache {
3086 return member_cache;
3090 public override string ToString ()
3092 if (BaseType != null)
3093 return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3095 return "TypeHandle (" + id + "," + Name + ")";