* support-test-*.cs: Rename from test-*-p2.cs.
[mono.git] / mcs / mcs / typemanager.cs
1 //
2 // typemanager.cs: C# type manager
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //         Ravi Pratap     (ravi@ximian.com)
6 //         Marek Safar     (marek.safar@seznam.cz)
7 //
8 // Licensed under the terms of the GNU GPL
9 //
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
11 //
12 //
13
14 //
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.
18 //
19 #define SIMPLE_SPEEDUP
20
21 using System;
22 using System.IO;
23 using System.Globalization;
24 using System.Collections;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 using System.Text;
28 using System.Text.RegularExpressions;
29 using System.Runtime.CompilerServices;
30 using System.Diagnostics;
31
32 namespace Mono.CSharp {
33
34 public class TypeManager {
35         //
36         // A list of core types that the compiler requires or uses
37         //
38         static public Type object_type;
39         static public Type value_type;
40         static public Type string_type;
41         static public Type int32_type;
42         static public Type uint32_type;
43         static public Type int64_type;
44         static public Type uint64_type;
45         static public Type float_type;
46         static public Type double_type;
47         static public Type char_type;
48         static public Type char_ptr_type;
49         static public Type short_type;
50         static public Type decimal_type;
51         static public Type bool_type;
52         static public Type sbyte_type;
53         static public Type byte_type;
54         static public Type ushort_type;
55         static public Type enum_type;
56         static public Type delegate_type;
57         static public Type multicast_delegate_type;
58         static public Type void_type;
59         static public Type null_type;
60         static public Type enumeration_type;
61         static public Type array_type;
62         static public Type runtime_handle_type;
63         static public Type icloneable_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 iconvertible_type;
69         static public Type default_member_type;
70         static public Type iasyncresult_type;
71         static public Type asynccallback_type;
72         static public Type intptr_type;
73         static public Type monitor_type;
74         static public Type runtime_field_handle_type;
75         static public Type runtime_argument_handle_type;
76         static public Type attribute_type;
77         static public Type attribute_usage_type;
78         static public Type decimal_constant_attribute_type;
79         static public Type dllimport_type;
80         static public Type unverifiable_code_type;
81         static public Type methodimpl_attr_type;
82         static public Type marshal_as_attr_type;
83         static public Type param_array_type;
84         static public Type void_ptr_type;
85         static public Type indexer_name_type;
86         static public Type exception_type;
87         static public Type invalid_operation_exception_type;
88         static public Type not_supported_exception_type;
89         static public Type obsolete_attribute_type;
90         static public Type conditional_attribute_type;
91         static public Type in_attribute_type;
92         static public Type out_attribute_type;
93         static public Type anonymous_method_type;
94         static public Type cls_compliant_attribute_type;
95         static public Type typed_reference_type;
96         static public Type arg_iterator_type;
97         static public Type mbr_type;
98         static public Type struct_layout_attribute_type;
99         static public Type field_offset_attribute_type;
100         static public Type security_attr_type;
101         static public Type required_attr_type;
102         static public Type guid_attr_type;
103         static public Type assembly_culture_attribute_type;
104         static public Type coclass_attr_type;
105         static public Type comimport_attr_type;
106
107         /// 
108         /// .NET 2.0
109         ///
110 #if NET_2_0
111         static internal Type runtime_compatibility_attr_type;
112         static internal Type compiler_generated_attr_type;
113         static internal Type fixed_buffer_attr_type;
114         static internal Type default_charset_type;
115 #endif
116
117         //
118         // An empty array of types
119         //
120         static public Type [] NoTypes;
121         static public TypeExpr [] NoTypeExprs;
122
123
124         // 
125         // Expressions representing the internal types.  Used during declaration
126         // definition.
127         //
128         static public TypeExpr system_object_expr, system_string_expr; 
129         static public TypeExpr system_boolean_expr, system_decimal_expr;
130         static public TypeExpr system_single_expr, system_double_expr;
131         static public TypeExpr system_sbyte_expr, system_byte_expr;
132         static public TypeExpr system_int16_expr, system_uint16_expr;
133         static public TypeExpr system_int32_expr, system_uint32_expr;
134         static public TypeExpr system_int64_expr, system_uint64_expr;
135         static public TypeExpr system_char_expr, system_void_expr;
136         static public TypeExpr system_asynccallback_expr;
137         static public TypeExpr system_iasyncresult_expr;
138         static public TypeExpr system_valuetype_expr;
139         static public TypeExpr system_intptr_expr;
140
141         //
142         // This is only used when compiling corlib
143         //
144         static public Type system_int32_type;
145         static public Type system_array_type;
146         static public Type system_type_type;
147         static public Type system_assemblybuilder_type;
148         static public MethodInfo system_int_array_get_length;
149         static public MethodInfo system_int_array_get_rank;
150         static public MethodInfo system_object_array_clone;
151         static public MethodInfo system_int_array_get_length_int;
152         static public MethodInfo system_int_array_get_lower_bound_int;
153         static public MethodInfo system_int_array_get_upper_bound_int;
154         static public MethodInfo system_void_array_copyto_array_int;
155
156         
157         //
158         // Internal, not really used outside
159         //
160         static Type runtime_helpers_type;
161         
162         //
163         // These methods are called by code generated by the compiler
164         //
165         static public MethodInfo string_concat_string_string;
166         static public MethodInfo string_concat_string_string_string;
167         static public MethodInfo string_concat_string_string_string_string;
168         static public MethodInfo string_concat_string_dot_dot_dot;
169         static public MethodInfo string_concat_object_object;
170         static public MethodInfo string_concat_object_object_object;
171         static public MethodInfo string_concat_object_dot_dot_dot;
172         static public MethodInfo string_isinterneted_string;
173         static public MethodInfo system_type_get_type_from_handle;
174         static public MethodInfo bool_movenext_void;
175         static public MethodInfo ienumerable_getenumerator_void;
176         static public MethodInfo void_reset_void;
177         static public MethodInfo void_dispose_void;
178         static public MethodInfo void_monitor_enter_object;
179         static public MethodInfo void_monitor_exit_object;
180         static public MethodInfo void_initializearray_array_fieldhandle;
181         static public MethodInfo int_getlength_int;
182         static public MethodInfo delegate_combine_delegate_delegate;
183         static public MethodInfo delegate_remove_delegate_delegate;
184         static public MethodInfo int_get_offset_to_string_data;
185         static public MethodInfo int_array_get_length;
186         static public MethodInfo int_array_get_rank;
187         static public MethodInfo object_array_clone;
188         static public MethodInfo int_array_get_length_int;
189         static public MethodInfo int_array_get_lower_bound_int;
190         static public MethodInfo int_array_get_upper_bound_int;
191         static public MethodInfo void_array_copyto_array_int;
192         static public PropertyInfo ienumerator_getcurrent;
193         
194         //
195         // The attribute constructors.
196         //
197         static public ConstructorInfo object_ctor;
198         static public ConstructorInfo cons_param_array_attribute;
199         static public ConstructorInfo void_decimal_ctor_five_args;
200         static public ConstructorInfo void_decimal_ctor_int_arg;
201         static public ConstructorInfo unverifiable_code_ctor;
202         static public ConstructorInfo default_member_ctor;
203         static public ConstructorInfo decimal_constant_attribute_ctor;
204         static internal ConstructorInfo struct_layout_attribute_ctor;
205         static public ConstructorInfo field_offset_attribute_ctor;
206         
207         ///
208         /// A new in C# 2.0
209         /// 
210 #if NET_2_0
211         static internal CustomAttributeBuilder compiler_generated_attr;
212         static internal ConstructorInfo fixed_buffer_attr_ctor;
213 #endif
214
215         static PtrHashtable builder_to_declspace;
216
217         static PtrHashtable builder_to_member_cache;
218
219         // <remarks>
220         //   Tracks the interfaces implemented by typebuilders.  We only
221         //   enter those who do implement or or more interfaces
222         // </remarks>
223         static PtrHashtable builder_to_ifaces;
224
225         // <remarks>
226         //   Maps PropertyBuilder to a Type array that contains
227         //   the arguments to the indexer
228         // </remarks>
229         static Hashtable indexer_arguments;
230
231         // <remarks>
232         //   Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
233         // <remarks>
234         static Hashtable method_params;
235
236         // <remarks>
237         //  A hash table from override methods to their base virtual method.
238         // <remarks>
239         static Hashtable method_overrides;
240
241         // <remarks>
242         //  Keeps track of methods
243         // </remarks>
244
245         static Hashtable builder_to_method;
246
247         // <remarks>
248         //  Contains all public types from referenced assemblies.
249         //  This member is used only if CLS Compliance verification is required.
250         // </remarks>
251         public static Hashtable AllClsTopLevelTypes;
252
253         static Hashtable fieldbuilders_to_fields;
254         static Hashtable fields;
255
256         struct Signature {
257                 public string name;
258                 public Type [] args;
259         }
260         
261         public static void CleanUp ()
262         {
263                 // Lets get everything clean so that we can collect before generating code
264                 builder_to_declspace = null;
265                 builder_to_member_cache = null;
266                 builder_to_ifaces = null;
267                 indexer_arguments = null;
268                 method_params = null;
269                 builder_to_method = null;
270                 
271                 fields = null;
272                 fieldbuilders_to_fields = null;
273                 events = null;
274                 priv_fields_events = null;
275                 type_hash = null;
276                 
277                 TypeHandle.CleanUp ();
278         }
279
280         /// <summary>
281         ///   A filter for Findmembers that uses the Signature object to
282         ///   extract objects
283         /// </summary>
284         static bool SignatureFilter (MemberInfo mi, object criteria)
285         {
286                 Signature sig = (Signature) criteria;
287
288                 if (!(mi is MethodBase))
289                         return false;
290                 
291                 if (mi.Name != sig.name)
292                         return false;
293
294                 int count = sig.args.Length;
295                 
296                 if (mi is MethodBuilder || mi is ConstructorBuilder){
297                         Type [] candidate_args = GetParameterData ((MethodBase) mi).Types;
298
299                         if (candidate_args.Length != count)
300                                 return false;
301                         
302                         for (int i = 0; i < count; i++)
303                                 if (candidate_args [i] != sig.args [i])
304                                         return false;
305                         
306                         return true;
307                 } else {
308                         ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
309
310                         if (pars.Length != count)
311                                 return false;
312
313                         for (int i = 0; i < count; i++)
314                                 if (pars [i].ParameterType != sig.args [i])
315                                         return false;
316                         return true;
317                 }
318         }
319
320         // A delegate that points to the filter above.
321         static MemberFilter signature_filter;
322
323         //
324         // These are expressions that represent some of the internal data types, used
325         // elsewhere
326         //
327         static void InitExpressionTypes ()
328         {
329                 system_object_expr  = new TypeLookupExpression ("System.Object");
330                 system_string_expr  = new TypeLookupExpression ("System.String");
331                 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
332                 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
333                 system_single_expr  = new TypeLookupExpression ("System.Single");
334                 system_double_expr  = new TypeLookupExpression ("System.Double");
335                 system_sbyte_expr   = new TypeLookupExpression ("System.SByte");
336                 system_byte_expr    = new TypeLookupExpression ("System.Byte");
337                 system_int16_expr   = new TypeLookupExpression ("System.Int16");
338                 system_uint16_expr  = new TypeLookupExpression ("System.UInt16");
339                 system_int32_expr   = new TypeLookupExpression ("System.Int32");
340                 system_uint32_expr  = new TypeLookupExpression ("System.UInt32");
341                 system_int64_expr   = new TypeLookupExpression ("System.Int64");
342                 system_uint64_expr  = new TypeLookupExpression ("System.UInt64");
343                 system_char_expr    = new TypeLookupExpression ("System.Char");
344                 system_void_expr    = new TypeLookupExpression ("System.Void");
345                 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
346                 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
347                 system_valuetype_expr  = new TypeLookupExpression ("System.ValueType");
348                 system_intptr_expr  = new TypeLookupExpression ("System.IntPtr");
349         }
350
351         static TypeManager ()
352         {
353                 Reset ();
354
355                 signature_filter = new MemberFilter (SignatureFilter);
356                 InitExpressionTypes ();
357         }
358
359         static public void Reset ()
360         {
361                 builder_to_declspace = new PtrHashtable ();
362                 builder_to_member_cache = new PtrHashtable ();
363                 builder_to_method = new PtrHashtable ();
364                 method_params = new PtrHashtable ();
365                 method_overrides = new PtrHashtable ();
366                 indexer_arguments = new PtrHashtable ();
367                 builder_to_ifaces = new PtrHashtable ();
368                 
369                 NoTypes = new Type [0];
370                 NoTypeExprs = new TypeExpr [0];
371
372                 fieldbuilders_to_fields = new Hashtable ();
373                 fields = new Hashtable ();
374                 type_hash = new DoubleHash ();
375         }
376
377         public static void AddUserType (DeclSpace ds)
378         {
379                 builder_to_declspace.Add (ds.TypeBuilder, ds);
380         }
381
382         //
383         // This entry point is used by types that we define under the covers
384         // 
385         public static void RegisterBuilder (Type tb, Type [] ifaces)
386         {
387                 if (ifaces != null)
388                         builder_to_ifaces [tb] = ifaces;
389         }       
390
391         public static void AddMethod (MethodBase builder, IMethodData method)
392         {
393                 builder_to_method.Add (builder, method);
394                 method_params.Add (builder, method.ParameterInfo);
395         }
396
397         public static IMethodData GetMethod (MethodBase builder)
398         {
399                 return (IMethodData) builder_to_method [builder];
400         }
401
402         /// <summary>
403         ///   Returns the DeclSpace whose Type is `t' or null if there is no
404         ///   DeclSpace for `t' (ie, the Type comes from a library)
405         /// </summary>
406         public static DeclSpace LookupDeclSpace (Type t)
407         {
408                 return builder_to_declspace [t] as DeclSpace;
409         }
410
411         /// <summary>
412         ///   Returns the TypeContainer whose Type is `t' or null if there is no
413         ///   TypeContainer for `t' (ie, the Type comes from a library)
414         /// </summary>
415         public static TypeContainer LookupTypeContainer (Type t)
416         {
417                 return builder_to_declspace [t] as TypeContainer;
418         }
419
420         public static MemberCache LookupMemberCache (Type t)
421         {
422                 if (t is TypeBuilder) {
423                         IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
424                         if (container != null)
425                                 return container.MemberCache;
426                 }
427
428                 return TypeHandle.GetMemberCache (t);
429         }
430
431         public static MemberCache LookupBaseInterfacesCache (Type t)
432         {
433                 Type [] ifaces = t.GetInterfaces ();
434
435                 if (ifaces != null && ifaces.Length == 1)
436                         return LookupMemberCache (ifaces [0]);
437
438                 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
439                 MemberCache cache = builder_to_member_cache [t] as MemberCache;
440                 if (cache != null)
441                         return cache;
442
443                 cache = new MemberCache (ifaces);
444                 builder_to_member_cache.Add (t, cache);
445                 return cache;
446         }
447
448         public static TypeContainer LookupInterface (Type t)
449         {
450                 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
451                 if ((tc == null) || (tc.Kind != Kind.Interface))
452                         return null;
453
454                 return tc;
455         }
456
457         public static Delegate LookupDelegate (Type t)
458         {
459                 return builder_to_declspace [t] as Delegate;
460         }
461
462         public static Class LookupClass (Type t)
463         {
464                 return (Class) builder_to_declspace [t];
465         }
466
467         //
468         // We use this hash for multiple kinds of constructed types:
469         //
470         //    (T, "&")  Given T, get T &
471         //    (T, "*")  Given T, get T *
472         //    (T, "[]") Given T and a array dimension, get T []
473         //    (T, X)    Given a type T and a simple name X, get the type T+X
474         //
475         // Accessibility tests, if necessary, should be done by the user
476         //
477         static DoubleHash type_hash = new DoubleHash ();
478
479         //
480         // Gets the reference to T version of the Type (T&)
481         //
482         public static Type GetReferenceType (Type t)
483         {
484                 return GetConstructedType (t, "&");
485         }
486
487         //
488         // Gets the pointer to T version of the Type  (T*)
489         //
490         public static Type GetPointerType (Type t)
491         {
492                 return GetConstructedType (t, "*");
493         }
494
495         public static Type GetConstructedType (Type t, string dim)
496         {
497                 object ret = null;
498                 if (!type_hash.Lookup (t, dim, out ret)) {
499                         ret = t.Module.GetType (t.ToString () + dim);
500                         type_hash.Insert (t, dim, ret);
501                 }
502                 return (Type) ret;
503         }
504
505         public static Type GetNestedType (Type t, string name)
506         {
507                 object ret = null;
508                 if (!type_hash.Lookup (t, name, out ret)) {
509                         ret = t.GetNestedType (name,
510                                BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
511                         type_hash.Insert (t, name, ret);
512                 }
513                 return (Type) ret;
514         }
515
516         /// <summary>
517         /// Fills static table with exported types from all referenced assemblies.
518         /// This information is required for CLS Compliance tests.
519         /// </summary>
520         public static void LoadAllImportedTypes ()
521         {
522                 AllClsTopLevelTypes = new Hashtable (1500);
523                 foreach (Assembly a in RootNamespace.Global.Assemblies) {
524                         foreach (Type t in a.GetExportedTypes ()) {
525                                 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
526                         }
527                 }
528         }
529
530         public static bool NamespaceClash (string name, Location loc)
531         {
532                 if (! RootNamespace.Global.IsNamespace (name))
533                         return false;
534
535                 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
536                 return true;
537         }
538
539         /// <summary>
540         ///   Returns the C# name of a type if possible, or the full type name otherwise
541         /// </summary>
542         static public string CSharpName (Type t)
543         {
544                 return Regex.Replace (t.FullName, 
545                         @"^System\." +
546                         @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
547                         @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
548                         @"Boolean|String|Void|Null)" +
549                         @"(\W+|\b)", 
550                         new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
551         }       
552
553         static public string CSharpName (Type[] types)
554         {
555                 StringBuilder sb = new StringBuilder ();
556                 foreach (Type t in types) {
557                         sb.Append (CSharpName (t));
558                         sb.Append (',');
559                 }
560                 sb.Remove (sb.Length - 1, 1);
561                 return sb.ToString ();
562         }
563         
564         static String CSharpNameMatch (Match match) 
565         {
566                 string s = match.Groups [1].Captures [0].Value;
567                 return s.ToLower ().
568                 Replace ("int32", "int").
569                 Replace ("uint32", "uint").
570                 Replace ("int16", "short").
571                 Replace ("uint16", "ushort").
572                 Replace ("int64", "long").
573                 Replace ("uint64", "ulong").
574                 Replace ("single", "float").
575                 Replace ("boolean", "bool")
576                 + match.Groups [2].Captures [0].Value;
577         }
578
579         /// <summary>
580         ///  Returns the signature of the method with full namespace classification
581         /// </summary>
582         static public string GetFullNameSignature (MemberInfo mi)
583         {
584                 PropertyInfo pi = mi as PropertyInfo;
585                 if (pi != null) {
586                         MethodBase pmi = pi.GetGetMethod ();
587                         if (pmi == null)
588                                 pmi = pi.GetSetMethod ();
589                         if (GetParameterData (pmi).Count > 0)
590                                 mi = pmi;
591                 }
592                 return (mi is MethodBase)
593                         ? CSharpSignature (mi as MethodBase) 
594                         : CSharpName (mi.DeclaringType) + '.' + mi.Name;
595         }
596
597         /// <summary>
598         /// When we need to report accessors as well
599         /// </summary>
600         static public string CSharpSignature (MethodBase mb)
601         {
602                 return CSharpSignature (mb, false);
603         }
604
605         /// <summary>
606         ///   Returns the signature of the method
607         /// </summary>
608         static public string CSharpSignature (MethodBase mb, bool show_accessor)
609         {
610                 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
611                 sig.Append ('.');
612
613                 ParameterData iparams = GetParameterData (mb);
614                 string parameters = iparams.GetSignatureForError ();
615                 string accessor = "";
616
617                 // Is property
618                 if (mb.IsSpecialName) {
619                         Operator.OpType ot = Operator.GetOperatorType (mb.Name);
620                         if (ot != Operator.OpType.TOP) {
621                                 sig.Append ("operator ");
622                                 sig.Append (Operator.GetName (ot));
623                                 sig.Append (parameters);
624                                 return sig.ToString ();
625                         }
626
627                         if (mb.Name.StartsWith ("get_") || mb.Name.StartsWith ("set_")) {
628                                 accessor = mb.Name.Substring (0, 3);
629                         }
630                 }
631
632                 // Is indexer
633                 if (mb.IsSpecialName && !mb.IsConstructor) {
634                         if (iparams.Count > (mb.Name.StartsWith ("get_") ? 0 : 1)) {
635                                 sig.Append ("this[");
636                                 if (show_accessor) {
637                                         sig.Append (parameters.Substring (1, parameters.Length - 2));
638                                 }
639                                 else {
640                                         int before_ret_val = parameters.LastIndexOf (',');
641                                         if (before_ret_val < 0)
642                                                 sig.Append (parameters.Substring (1, parameters.Length - 2));
643                                         else
644                                                 sig.Append (parameters.Substring (1, before_ret_val - 1));
645                                 }
646                                 sig.Append (']');
647                         } else {
648                                 sig.Append (mb.Name.Substring (4));
649                         }
650                 } else {
651                         if (mb.Name == ".ctor")
652                                 sig.Append (mb.DeclaringType.Name);
653                         else
654                                 sig.Append (mb.Name);
655
656                         sig.Append (parameters);
657                 }
658
659                 if (show_accessor && accessor.Length > 0) {
660                         sig.Append ('.');
661                         sig.Append (accessor);
662                 }
663
664                 return sig.ToString ();
665         }
666
667         static public string CSharpSignature (EventInfo ei)
668         {
669                 return CSharpName (ei.DeclaringType) + '.' + ei.Name;
670         }
671
672         /// <summary>
673         ///   Looks up a type, and aborts if it is not found.  This is used
674         ///   by types required by the compiler
675         /// </summary>
676         static Type CoreLookupType (string ns_name, string name)
677         {
678                 Namespace ns = RootNamespace.Global.GetNamespace (ns_name, true);
679                 FullNamedExpression fne = ns.Lookup (RootContext.Tree.Types, name, Location.Null);
680                 Type t = fne == null ? null : fne.Type;
681                 if (t == null)
682                         Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
683                 return t;
684         }
685
686         /// <summary>
687         ///   Returns the MethodInfo for a method named `name' defined
688         ///   in type `t' which takes arguments of types `args'
689         /// </summary>
690         static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
691         {
692                 MemberList list;
693                 Signature sig;
694                 BindingFlags flags = instance_and_static | BindingFlags.Public;
695
696                 sig.name = name;
697                 sig.args = args;
698
699                 if (is_private)
700                         flags |= BindingFlags.NonPublic;
701
702                 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
703                 if (list.Count == 0) {
704                         if (report_errors)
705                                 Report.Error (-19, "Can not find the core function `" + name + "'");
706                         return null;
707                 }
708
709                 MethodInfo mi = list [0] as MethodInfo;
710                 if (mi == null) {
711                         if (report_errors)
712                                 Report.Error (-19, "Can not find the core function `" + name + "'");
713                         return null;
714                 }
715
716                 return mi;
717         }
718
719         static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
720         {
721                 return GetMethod (t, name, args, false, report_errors);
722         }
723
724         static MethodInfo GetMethod (Type t, string name, Type [] args)
725         {
726                 return GetMethod (t, name, args, true);
727         }
728
729         /// <summary>
730         ///   Returns the PropertyInfo for a property named `name' defined
731         ///   in type `t'
732         /// </summary>
733         static PropertyInfo GetProperty (Type t, string name)
734         {
735                 MemberList list = FindMembers (t, MemberTypes.Property, BindingFlags.Public |
736                                     BindingFlags.Instance, Type.FilterName, name);
737                 if (list.Count == 0) {
738                         Report.Error (-19, "Can not find the core property `" + name + "'");
739                         return null;
740                 }
741
742                 PropertyInfo pi = list [0] as PropertyInfo;
743                 if (pi == null) {
744                         Report.Error (-19, "Can not find the core function `" + name + "'");
745                         return null;
746                 }
747
748                 return pi;
749         }
750
751         /// <summary>
752         ///    Returns the ConstructorInfo for "args"
753         /// </summary>
754         public static ConstructorInfo GetConstructor (Type t, Type [] args)
755         {
756                 MemberList list;
757                 Signature sig;
758
759                 sig.name = ".ctor";
760                 sig.args = args;
761                 
762                 list = FindMembers (t, MemberTypes.Constructor,
763                                     instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
764                                     signature_filter, sig);
765                 if (list.Count == 0){
766                         Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
767                         return null;
768                 }
769
770                 ConstructorInfo ci = list [0] as ConstructorInfo;
771                 if (ci == null){
772                         Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
773                         return null;
774                 }
775
776                 return ci;
777         }
778
779         public static void InitEnumUnderlyingTypes ()
780         {
781
782                 int32_type    = CoreLookupType ("System", "Int32");
783                 int64_type    = CoreLookupType ("System", "Int64");
784                 uint32_type   = CoreLookupType ("System", "UInt32"); 
785                 uint64_type   = CoreLookupType ("System", "UInt64"); 
786                 byte_type     = CoreLookupType ("System", "Byte");
787                 sbyte_type    = CoreLookupType ("System", "SByte");
788                 short_type    = CoreLookupType ("System", "Int16");
789                 ushort_type   = CoreLookupType ("System", "UInt16");
790         }
791         
792         /// <remarks>
793         ///   The types have to be initialized after the initial
794         ///   population of the type has happened (for example, to
795         ///   bootstrap the corlib.dll
796         /// </remarks>
797         public static void InitCoreTypes ()
798         {
799                 object_type   = CoreLookupType ("System", "Object");
800                 value_type    = CoreLookupType ("System", "ValueType");
801
802                 InitEnumUnderlyingTypes ();
803
804                 char_type     = CoreLookupType ("System", "Char");
805                 string_type   = CoreLookupType ("System", "String");
806                 float_type    = CoreLookupType ("System", "Single");
807                 double_type   = CoreLookupType ("System", "Double");
808                 char_ptr_type = GetPointerType (char_type);
809                 decimal_type  = CoreLookupType ("System", "Decimal");
810                 bool_type     = CoreLookupType ("System", "Boolean");
811                 enum_type     = CoreLookupType ("System", "Enum");
812
813                 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate");
814                 delegate_type           = CoreLookupType ("System", "Delegate");
815
816                 array_type    = CoreLookupType ("System", "Array");
817                 void_type     = CoreLookupType ("System", "Void");
818                 type_type     = CoreLookupType ("System", "Type");
819
820                 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle");
821                 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle");
822                 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers");
823                 default_member_type  = CoreLookupType ("System.Reflection", "DefaultMemberAttribute");
824                 runtime_handle_type  = CoreLookupType ("System", "RuntimeTypeHandle");
825                 asynccallback_type   = CoreLookupType ("System", "AsyncCallback");
826                 iasyncresult_type    = CoreLookupType ("System", "IAsyncResult");
827                 ienumerator_type     = CoreLookupType ("System.Collections", "IEnumerator");
828                 ienumerable_type     = CoreLookupType ("System.Collections", "IEnumerable");
829                 idisposable_type     = CoreLookupType ("System", "IDisposable");
830                 icloneable_type      = CoreLookupType ("System", "ICloneable");
831                 iconvertible_type    = CoreLookupType ("System", "IConvertible");
832                 monitor_type         = CoreLookupType ("System.Threading", "Monitor");
833                 intptr_type          = CoreLookupType ("System", "IntPtr");
834
835                 attribute_type       = CoreLookupType ("System", "Attribute");
836                 attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute");
837                 dllimport_type       = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute");
838                 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute");
839                 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute");
840                 param_array_type     = CoreLookupType ("System", "ParamArrayAttribute");
841                 in_attribute_type    = CoreLookupType ("System.Runtime.InteropServices", "InAttribute");
842                 out_attribute_type   = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute");
843                 typed_reference_type = CoreLookupType ("System", "TypedReference");
844                 arg_iterator_type    = CoreLookupType ("System", "ArgIterator");
845                 mbr_type             = CoreLookupType ("System", "MarshalByRefObject");
846                 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
847
848                 unverifiable_code_type= CoreLookupType ("System.Security", "UnverifiableCodeAttribute");
849
850                 void_ptr_type         = GetPointerType (void_type);
851
852                 indexer_name_type     = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute");
853
854                 exception_type        = CoreLookupType ("System", "Exception");
855                 invalid_operation_exception_type = CoreLookupType ("System", "InvalidOperationException");
856                 not_supported_exception_type = CoreLookupType ("System", "NotSupportedException");
857
858                 //
859                 // Attribute types
860                 //
861                 obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute");
862                 conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute");
863                 cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute");
864                 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute");
865                 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute");
866                 security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute");
867                 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute");
868                 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute");
869                 assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute");
870                 comimport_attr_type = CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute");
871                 coclass_attr_type = CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute");
872
873                 //
874                 // .NET 2.0
875                 //
876 #if NET_2_0
877                 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
878                 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute");
879                 default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
880                 runtime_compatibility_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
881 #endif
882                 //
883                 // When compiling corlib, store the "real" types here.
884                 //
885                 if (!RootContext.StdLib) {
886                         system_int32_type = typeof (System.Int32);
887                         system_array_type = typeof (System.Array);
888                         system_type_type = typeof (System.Type);
889                         system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
890
891                         Type [] void_arg = {  };
892                         system_int_array_get_length = GetMethod (
893                                 system_array_type, "get_Length", void_arg);
894                         system_int_array_get_rank = GetMethod (
895                                 system_array_type, "get_Rank", void_arg);
896                         system_object_array_clone = GetMethod (
897                                 system_array_type, "Clone", void_arg);
898
899                         Type [] system_int_arg = { system_int32_type };
900                         system_int_array_get_length_int = GetMethod (
901                                 system_array_type, "GetLength", system_int_arg);
902                         system_int_array_get_upper_bound_int = GetMethod (
903                                 system_array_type, "GetUpperBound", system_int_arg);
904                         system_int_array_get_lower_bound_int = GetMethod (
905                                 system_array_type, "GetLowerBound", system_int_arg);
906
907                         Type [] system_array_int_arg = { system_array_type, system_int32_type };
908                         system_void_array_copyto_array_int = GetMethod (
909                                 system_array_type, "CopyTo", system_array_int_arg);
910
911                         Type [] system_3_type_arg = {
912                                 system_type_type, system_type_type, system_type_type };
913                         Type [] system_4_type_arg = {
914                                 system_type_type, system_type_type, system_type_type, system_type_type };
915
916                         MethodInfo set_corlib_type_builders = GetMethod (
917                                 system_assemblybuilder_type, "SetCorlibTypeBuilders",
918                                 system_4_type_arg, true, false);
919
920                         if (set_corlib_type_builders != null) {
921                                 object[] args = new object [4];
922                                 args [0] = object_type;
923                                 args [1] = value_type;
924                                 args [2] = enum_type;
925                                 args [3] = void_type;
926                                 
927                                 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
928                         } else {
929                                 // Compatibility for an older version of the class libs.
930                                 set_corlib_type_builders = GetMethod (
931                                         system_assemblybuilder_type, "SetCorlibTypeBuilders",
932                                         system_3_type_arg, true, true);
933
934                                 if (set_corlib_type_builders == null) {
935                                         Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
936                                         return;
937                                 }
938
939                                 object[] args = new object [3];
940                                 args [0] = object_type;
941                                 args [1] = value_type;
942                                 args [2] = enum_type;
943                                 
944                                 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
945                         }
946                 }
947
948                 system_object_expr.Type = object_type;
949                 system_string_expr.Type = string_type;
950                 system_boolean_expr.Type = bool_type;
951                 system_decimal_expr.Type = decimal_type;
952                 system_single_expr.Type = float_type;
953                 system_double_expr.Type = double_type;
954                 system_sbyte_expr.Type = sbyte_type;
955                 system_byte_expr.Type = byte_type;
956                 system_int16_expr.Type = short_type;
957                 system_uint16_expr.Type = ushort_type;
958                 system_int32_expr.Type = int32_type;
959                 system_uint32_expr.Type = uint32_type;
960                 system_int64_expr.Type = int64_type;
961                 system_uint64_expr.Type = uint64_type;
962                 system_char_expr.Type = char_type;
963                 system_void_expr.Type = void_type;
964                 system_asynccallback_expr.Type = asynccallback_type;
965                 system_iasyncresult_expr.Type = iasyncresult_type;
966                 system_valuetype_expr.Type = value_type;
967
968                 //
969                 // These are only used for compare purposes
970                 //
971                 anonymous_method_type = typeof (AnonymousMethod);
972                 null_type = typeof (NullType);
973         }
974
975         //
976         // The helper methods that are used by the compiler
977         //
978         public static void InitCodeHelpers ()
979         {
980                 //
981                 // Now load the default methods that we use.
982                 //
983                 Type [] string_string = { string_type, string_type };
984                 string_concat_string_string = GetMethod (
985                         string_type, "Concat", string_string);
986                 Type [] string_string_string = { string_type, string_type, string_type };
987                 string_concat_string_string_string = GetMethod (
988                         string_type, "Concat", string_string_string);
989                 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
990                 string_concat_string_string_string_string = GetMethod (
991                         string_type, "Concat", string_string_string_string);
992                 Type[] params_string = { GetConstructedType (string_type, "[]") };
993                 string_concat_string_dot_dot_dot = GetMethod (
994                         string_type, "Concat", params_string);
995
996                 Type [] object_object = { object_type, object_type };
997                 string_concat_object_object = GetMethod (
998                         string_type, "Concat", object_object);
999                 Type [] object_object_object = { object_type, object_type, object_type };
1000                 string_concat_object_object_object = GetMethod (
1001                         string_type, "Concat", object_object_object);
1002                 Type[] params_object = { GetConstructedType (object_type, "[]") };
1003                 string_concat_object_dot_dot_dot = GetMethod (
1004                         string_type, "Concat", params_object);
1005
1006                 Type [] string_ = { string_type };
1007                 string_isinterneted_string = GetMethod (
1008                         string_type, "IsInterned", string_);
1009                 
1010                 Type [] runtime_type_handle = { runtime_handle_type };
1011                 system_type_get_type_from_handle = GetMethod (
1012                         type_type, "GetTypeFromHandle", runtime_type_handle);
1013
1014                 Type [] delegate_delegate = { delegate_type, delegate_type };
1015                 delegate_combine_delegate_delegate = GetMethod (
1016                                 delegate_type, "Combine", delegate_delegate);
1017
1018                 delegate_remove_delegate_delegate = GetMethod (
1019                                 delegate_type, "Remove", delegate_delegate);
1020
1021                 //
1022                 // Void arguments
1023                 //
1024                 Type [] void_arg = {  };
1025                 ienumerator_getcurrent = GetProperty (
1026                         ienumerator_type, "Current");
1027                 bool_movenext_void = GetMethod (
1028                         ienumerator_type, "MoveNext", void_arg);
1029                 void_reset_void = GetMethod (
1030                         ienumerator_type, "Reset", void_arg);
1031                 void_dispose_void = GetMethod (
1032                         idisposable_type, "Dispose", void_arg);
1033                 int_get_offset_to_string_data = GetMethod (
1034                         runtime_helpers_type, "get_OffsetToStringData", void_arg);
1035                 int_array_get_length = GetMethod (
1036                         array_type, "get_Length", void_arg);
1037                 int_array_get_rank = GetMethod (
1038                         array_type, "get_Rank", void_arg);
1039                 ienumerable_getenumerator_void = GetMethod (
1040                         ienumerable_type, "GetEnumerator", void_arg);
1041                 
1042                 //
1043                 // Int32 arguments
1044                 //
1045                 Type [] int_arg = { int32_type };
1046                 int_array_get_length_int = GetMethod (
1047                         array_type, "GetLength", int_arg);
1048                 int_array_get_upper_bound_int = GetMethod (
1049                         array_type, "GetUpperBound", int_arg);
1050                 int_array_get_lower_bound_int = GetMethod (
1051                         array_type, "GetLowerBound", int_arg);
1052
1053                 //
1054                 // System.Array methods
1055                 //
1056                 object_array_clone = GetMethod (
1057                         array_type, "Clone", void_arg);
1058                 Type [] array_int_arg = { array_type, int32_type };
1059                 void_array_copyto_array_int = GetMethod (
1060                         array_type, "CopyTo", array_int_arg);
1061                 
1062                 //
1063                 // object arguments
1064                 //
1065                 Type [] object_arg = { object_type };
1066                 void_monitor_enter_object = GetMethod (
1067                         monitor_type, "Enter", object_arg);
1068                 void_monitor_exit_object = GetMethod (
1069                         monitor_type, "Exit", object_arg);
1070
1071                 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1072                 
1073                 void_initializearray_array_fieldhandle = GetMethod (
1074                         runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1075
1076                 //
1077                 // Array functions
1078                 //
1079                 int_getlength_int = GetMethod (
1080                         array_type, "GetLength", int_arg);
1081
1082                 //
1083                 // Decimal constructors
1084                 //
1085                 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1086                 void_decimal_ctor_five_args = GetConstructor (
1087                         decimal_type, dec_arg);
1088                 
1089                 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1090
1091                 //
1092                 // Attributes
1093                 //
1094                 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1095                 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1096                 default_member_ctor = GetConstructor (default_member_type, string_);
1097
1098                 Type[] short_arg = { short_type };
1099                 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1100
1101                 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1102                         { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1103
1104                 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1105                         { int32_type });
1106
1107                 //
1108                 // .NET 2.0 types
1109                 //
1110 #if NET_2_0
1111                 compiler_generated_attr = new CustomAttributeBuilder (
1112                         GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1113
1114                 Type[] type_int_arg = { type_type, int32_type };
1115                 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1116 #endif
1117
1118                 // Object
1119                 object_ctor = GetConstructor (object_type, void_arg);
1120
1121         }
1122
1123         const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1124
1125         /// <remarks>
1126         ///   This is the "old", non-cache based FindMembers() function.  We cannot use
1127         ///   the cache here because there is no member name argument.
1128         /// </remarks>
1129         public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1130                                               MemberFilter filter, object criteria)
1131         {
1132                 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1133
1134                 //
1135                 // `builder_to_declspace' contains all dynamic types.
1136                 //
1137                 if (decl != null) {
1138                         MemberList list;
1139                         Timer.StartTimer (TimerType.FindMembers);
1140                         list = decl.FindMembers (mt, bf, filter, criteria);
1141                         Timer.StopTimer (TimerType.FindMembers);
1142                         return list;
1143                 }
1144
1145                 //
1146                 // We have to take care of arrays specially, because GetType on
1147                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1148                 // and we can not call FindMembers on this type.
1149                 //
1150                 if (TypeManager.IsSubclassOf (t, TypeManager.array_type))
1151                         return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1152
1153                 //
1154                 // Since FindMembers will not lookup both static and instance
1155                 // members, we emulate this behaviour here.
1156                 //
1157                 if ((bf & instance_and_static) == instance_and_static){
1158                         MemberInfo [] i_members = t.FindMembers (
1159                                 mt, bf & ~BindingFlags.Static, filter, criteria);
1160
1161                         int i_len = i_members.Length;
1162                         if (i_len == 1){
1163                                 MemberInfo one = i_members [0];
1164
1165                                 //
1166                                 // If any of these are present, we are done!
1167                                 //
1168                                 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1169                                         return new MemberList (i_members);
1170                         }
1171                                 
1172                         MemberInfo [] s_members = t.FindMembers (
1173                                 mt, bf & ~BindingFlags.Instance, filter, criteria);
1174
1175                         int s_len = s_members.Length;
1176                         if (i_len > 0 || s_len > 0)
1177                                 return new MemberList (i_members, s_members);
1178                         else {
1179                                 if (i_len > 0)
1180                                         return new MemberList (i_members);
1181                                 else
1182                                         return new MemberList (s_members);
1183                         }
1184                 }
1185
1186                 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1187         }
1188
1189
1190         /// <summary>
1191         ///   This method is only called from within MemberLookup.  It tries to use the member
1192         ///   cache if possible and falls back to the normal FindMembers if not.  The `used_cache'
1193         ///   flag tells the caller whether we used the cache or not.  If we used the cache, then
1194         ///   our return value will already contain all inherited members and the caller don't need
1195         ///   to check base classes and interfaces anymore.
1196         /// </summary>
1197         private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1198                                                             string name, out bool used_cache)
1199         {
1200                 MemberCache cache;
1201
1202                 //
1203                 // We have to take care of arrays specially, because GetType on
1204                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1205                 // and we can not call FindMembers on this type.
1206                 //
1207                 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1208                         used_cache = true;
1209                         return TypeHandle.ArrayType.MemberCache.FindMembers (
1210                                 mt, bf, name, FilterWithClosure_delegate, null);
1211                 }
1212
1213                 //
1214                 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1215                 // and we can ask the DeclSpace for the MemberCache.
1216                 //
1217                 if (t is TypeBuilder) {
1218                         DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1219                         cache = decl.MemberCache;
1220
1221                         //
1222                         // If this DeclSpace has a MemberCache, use it.
1223                         //
1224
1225                         if (cache != null) {
1226                                 used_cache = true;
1227                                 return cache.FindMembers (
1228                                         mt, bf, name, FilterWithClosure_delegate, null);
1229                         }
1230
1231                         // If there is no MemberCache, we need to use the "normal" FindMembers.
1232                         // Note, this is a VERY uncommon route!
1233                         
1234                         MemberList list;
1235                         Timer.StartTimer (TimerType.FindMembers);
1236                         list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1237                                                  FilterWithClosure_delegate, name);
1238                         Timer.StopTimer (TimerType.FindMembers);
1239                         used_cache = false;
1240                         
1241                         return (MemberInfo []) list;
1242                 }
1243
1244                 //
1245                 // This call will always succeed.  There is exactly one TypeHandle instance per
1246                 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1247                 // the corresponding MemberCache.
1248                 //
1249                 cache = TypeHandle.GetMemberCache (t);
1250
1251                 used_cache = true;
1252                 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1253         }
1254
1255         public static bool IsBuiltinType (Type t)
1256         {
1257                 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1258                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1259                     t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1260                     t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1261                         return true;
1262                 else
1263                         return false;
1264         }
1265
1266         public static bool IsBuiltinType (TypeContainer tc)
1267         {
1268                 return IsBuiltinType (tc.TypeBuilder);
1269         }
1270
1271         //
1272         // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1273         // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1274         // 
1275         public static bool IsPrimitiveType (Type t)
1276         {
1277                 return (t == int32_type || t == uint32_type ||
1278                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1279                     t == char_type || t == short_type || t == bool_type ||
1280                     t == sbyte_type || t == byte_type || t == ushort_type);
1281         }
1282
1283         public static bool IsDelegateType (Type t)
1284         {
1285                 if (t.IsSubclassOf (TypeManager.delegate_type))
1286                         return true;
1287                 else
1288                         return false;
1289         }
1290         
1291         public static bool IsEnumType (Type t)
1292         {
1293                 if (builder_to_declspace [t] is Enum)
1294                         return true;
1295
1296                 return t.IsEnum;
1297         }
1298
1299         public static bool IsBuiltinOrEnum (Type t)
1300         {
1301                 if (IsBuiltinType (t))
1302                         return true;
1303                 
1304                 if (IsEnumType (t))
1305                         return true;
1306
1307                 return false;
1308         }
1309
1310         static Stack unmanaged_enclosing_types = new Stack (4);
1311
1312         //
1313         // Whether a type is unmanaged.  This is used by the unsafe code (25.2)
1314         //
1315         public static bool IsUnmanagedType (Type t)
1316         {
1317                 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1318                 if (unmanaged_enclosing_types.Contains (t))
1319                         return true;
1320
1321                 // builtins that are not unmanaged types
1322                 if (t == TypeManager.object_type || t == TypeManager.string_type)
1323                         return false;
1324
1325                 if (IsBuiltinOrEnum (t))
1326                         return true;
1327
1328                 // Someone did the work of checking if the ElementType of t is unmanaged.  Let's not repeat it.
1329                 if (t.IsPointer)
1330                         return true;
1331
1332                 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1333                 if (t.IsArray)
1334                         return false;
1335
1336                 if (!IsValueType (t))
1337                         return false;
1338
1339                 unmanaged_enclosing_types.Push (t);
1340
1341                 bool retval = true;
1342
1343                 if (t is TypeBuilder){
1344                         TypeContainer tc = LookupTypeContainer (t);
1345                         if (tc.Fields != null){
1346                                 foreach (FieldMember f in tc.Fields){
1347                                         // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1348                                         if ((f.ModFlags & Modifiers.STATIC) != 0)
1349                                                 continue;
1350                                         if (f.MemberType == null)
1351                                                 continue;
1352                                         if (!IsUnmanagedType (f.MemberType)){
1353                                                 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1354                                                 retval = false;
1355                                         }
1356                                 }
1357                         }
1358                 } else {
1359                         FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1360                         
1361                         foreach (FieldInfo f in fields){
1362                                 if (!IsUnmanagedType (f.FieldType)){
1363                                         Report.SymbolRelatedToPreviousError (f);
1364                                         retval = false;
1365                                 }
1366                         }
1367                 }
1368
1369                 unmanaged_enclosing_types.Pop ();
1370
1371                 return retval;
1372         }
1373                 
1374         public static bool IsValueType (Type t)
1375         {
1376                 if (t.IsSubclassOf (TypeManager.value_type) && (t != TypeManager.enum_type))
1377                         return true;
1378                 else
1379                         return false;
1380         }
1381         
1382         public static bool IsInterfaceType (Type t)
1383         {
1384                 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1385                 if (tc == null)
1386                         return false;
1387
1388                 return tc.Kind == Kind.Interface;
1389         }
1390
1391         public static bool IsSubclassOf (Type type, Type base_type)
1392         {
1393                 do {
1394                         if (type.Equals (base_type))
1395                                 return true;
1396
1397                         type = type.BaseType;
1398                 } while (type != null);
1399
1400                 return false;
1401         }
1402
1403         public static bool IsFamilyAccessible (Type type, Type base_type)
1404         {
1405                 return IsSubclassOf (type, base_type);
1406         }
1407
1408         //
1409         // Checks whether `type' is a subclass or nested child of `base_type'.
1410         //
1411         public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1412         {
1413                 do {
1414                         if ((type == base_type) || type.IsSubclassOf (base_type))
1415                                 return true;
1416
1417                         // Handle nested types.
1418                         type = type.DeclaringType;
1419                 } while (type != null);
1420
1421                 return false;
1422         }
1423
1424         //
1425         // Checks whether `type' is a nested child of `parent'.
1426         //
1427         public static bool IsNestedChildOf (Type type, Type parent)
1428         {
1429                 if (type == parent)
1430                         return false;
1431
1432                 type = type.DeclaringType;
1433                 while (type != null) {
1434                         if (type == parent)
1435                                 return true;
1436
1437                         type = type.DeclaringType;
1438                 }
1439
1440                 return false;
1441         }
1442
1443         //
1444         // Do the right thing when returning the element type of an
1445         // array type based on whether we are compiling corlib or not
1446         //
1447         public static Type GetElementType (Type t)
1448         {
1449                 if (RootContext.StdLib)
1450                         return t.GetElementType ();
1451                 else
1452                         return TypeToCoreType (t.GetElementType ());
1453         }
1454
1455         /// <summary>
1456         /// This method is not implemented by MS runtime for dynamic types
1457         /// </summary>
1458         public static bool HasElementType (Type t)
1459         {
1460                 return t.IsArray || t.IsPointer || t.IsByRef;
1461         }
1462         
1463         /// <summary>
1464         ///   Gigantic work around for missing features in System.Reflection.Emit follows.
1465         /// </summary>
1466         ///
1467         /// <remarks>
1468         ///   Since System.Reflection.Emit can not return MethodBase.GetParameters
1469         ///   for anything which is dynamic, and we need this in a number of places,
1470         ///   we register this information here, and use it afterwards.
1471         /// </remarks>
1472         static public void RegisterMethod (MethodBase mb, Parameters ip)
1473         {
1474                 method_params.Add (mb, ip);
1475         }
1476         
1477         static public ParameterData GetParameterData (MethodBase mb)
1478         {
1479                 ParameterData pd = (ParameterData)method_params [mb];
1480                 if (pd == null) {
1481                         if (mb is MethodBuilder || mb is ConstructorBuilder)
1482                                 throw new InternalErrorException ("Argument for Method not registered" + mb);
1483
1484                         pd = new ReflectionParameters (mb);
1485                         method_params.Add (mb, pd);
1486                 }
1487                 return pd;
1488         }
1489
1490         static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1491         {
1492                 if (!method_overrides.Contains (override_method))
1493                         method_overrides [override_method] = base_method;
1494                 if (method_overrides [override_method] != base_method)
1495                         throw new InternalErrorException ("Override mismatch: " + override_method);
1496         }
1497
1498         static public bool IsOverride (MethodBase m)
1499         {
1500                 return m.IsVirtual &&
1501                         (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1502                         (m is MethodBuilder || method_overrides.Contains (m));
1503         }
1504
1505         static public MethodBase TryGetBaseDefinition (MethodBase m)
1506         {
1507                 return (MethodBase) method_overrides [m];
1508         }
1509
1510         /// <summary>
1511         ///    Returns the argument types for an indexer based on its PropertyInfo
1512         ///
1513         ///    For dynamic indexers, we use the compiler provided types, for
1514         ///    indexers from existing assemblies we load them from GetParameters,
1515         ///    and insert them into the cache
1516         /// </summary>
1517         static public Type [] GetArgumentTypes (PropertyInfo indexer)
1518         {
1519                 if (indexer_arguments.Contains (indexer))
1520                         return (Type []) indexer_arguments [indexer];
1521                 else if (indexer is PropertyBuilder)
1522                         // If we're a PropertyBuilder and not in the
1523                         // `indexer_arguments' hash, then we're a property and
1524                         // not an indexer.
1525                         return NoTypes;
1526                 else {
1527                         ParameterInfo [] pi = indexer.GetIndexParameters ();
1528                         // Property, not an indexer.
1529                         if (pi == null)
1530                                 return NoTypes;
1531                         int c = pi.Length;
1532                         Type [] types = new Type [c];
1533                         
1534                         for (int i = 0; i < c; i++)
1535                                 types [i] = pi [i].ParameterType;
1536
1537                         indexer_arguments.Add (indexer, types);
1538                         return types;
1539                 }
1540         }
1541         
1542         public static void RegisterConstant (FieldInfo fb, IConstant ic)
1543         {
1544                 fields.Add (fb, ic);
1545         }
1546
1547         public static IConstant GetConstant (FieldInfo fb)
1548         {
1549                 if (fb == null)
1550                         return null;
1551
1552                 return (IConstant)fields [fb];
1553         }
1554
1555         static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1556         {
1557                 if (fieldbuilders_to_fields.Contains (fb))
1558                         return false;
1559
1560                 fieldbuilders_to_fields.Add (fb, f);
1561                 return true;
1562         }
1563
1564         //
1565         // The return value can be null;  This will be the case for
1566         // auxiliary FieldBuilders created by the compiler that have no
1567         // real field being declared on the source code
1568         //
1569         static public FieldBase GetField (FieldInfo fb)
1570         {
1571                 return (FieldBase) fieldbuilders_to_fields [fb];
1572         }
1573         
1574         static Hashtable events;
1575
1576         static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1577         {
1578                 if (events == null)
1579                         events = new Hashtable ();
1580
1581                 if (!events.Contains (eb)) {
1582                         events.Add (eb, new Pair (add, remove));
1583                 }
1584         }
1585
1586         static public MethodInfo GetAddMethod (EventInfo ei)
1587         {
1588                 if (ei is MyEventBuilder) {
1589                         Pair pair = (Pair) events [ei];
1590
1591                         return (MethodInfo) pair.First;
1592                 }
1593                 return ei.GetAddMethod (true);
1594         }
1595
1596         static public MethodInfo GetRemoveMethod (EventInfo ei)
1597         {
1598                 if (ei is MyEventBuilder) {
1599                         Pair pair = (Pair) events [ei];
1600
1601                         return (MethodInfo) pair.Second;
1602                 }
1603                 return ei.GetRemoveMethod (true);
1604         }
1605
1606         static Hashtable priv_fields_events;
1607
1608         static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1609         {
1610                 if (priv_fields_events == null)
1611                         priv_fields_events = new Hashtable ();
1612
1613                 if (priv_fields_events.Contains (einfo))
1614                         return false;
1615
1616                 priv_fields_events.Add (einfo, builder);
1617
1618                 return true;
1619         }
1620
1621         static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1622         {
1623                 if (priv_fields_events == null)
1624                         return null;
1625                 else
1626                         return (MemberInfo) priv_fields_events [ei];
1627         }
1628                 
1629         static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1630                                             MethodBase set, Type[] args)
1631         {
1632                 indexer_arguments.Add (pb, args);
1633
1634                 return true;
1635         }
1636
1637         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1638         {
1639                 Hashtable hash = new Hashtable ();
1640                 return CheckStructCycles (tc, seen, hash);
1641         }
1642
1643         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1644                                               Hashtable hash)
1645         {
1646                 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1647                         return true;
1648
1649                 //
1650                 // `seen' contains all types we've already visited.
1651                 //
1652                 if (seen.Contains (tc))
1653                         return true;
1654                 seen.Add (tc, null);
1655
1656                 if (tc.Fields == null)
1657                         return true;
1658
1659                 foreach (FieldMember field in tc.Fields) {
1660                         if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1661                                 continue;
1662
1663                         Type ftype = field.FieldBuilder.FieldType;
1664                         TypeContainer ftc = LookupTypeContainer (ftype);
1665                         if (ftc == null)
1666                                 continue;
1667
1668                         if (hash.Contains (ftc)) {
1669                                 Report.Error (523, tc.Location,
1670                                               "Struct member `{0}.{1}' of type `{2}' " +
1671                                               "causes a cycle in the struct layout",
1672                                               tc.Name, field.Name, ftc.Name);
1673                                 return false;
1674                         }
1675
1676                         //
1677                         // `hash' contains all types in the current path.
1678                         //
1679                         hash.Add (tc, null);
1680
1681                         bool ok = CheckStructCycles (ftc, seen, hash);
1682
1683                         hash.Remove (tc);
1684
1685                         if (!ok)
1686                                 return false;
1687
1688                         if (!seen.Contains (ftc))
1689                                 seen.Add (ftc, null);
1690                 }
1691
1692                 return true;
1693         }
1694
1695         /// <summary>
1696         ///   Given an array of interface types, expand and eliminate repeated ocurrences
1697         ///   of an interface.  
1698         /// </summary>
1699         ///
1700         /// <remarks>
1701         ///   This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1702         ///   be IA, IB, IC.
1703         /// </remarks>
1704         public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
1705         {
1706                 ArrayList new_ifaces = new ArrayList ();
1707
1708                 foreach (TypeExpr iface in base_interfaces){
1709                         Type itype = iface.ResolveType (ec);
1710                         if (itype == null)
1711                                 return null;
1712
1713                         if (!new_ifaces.Contains (itype))
1714                                 new_ifaces.Add (itype);
1715                         
1716                         Type [] implementing = itype.GetInterfaces ();
1717                         
1718                         foreach (Type imp in implementing){
1719                                 if (!new_ifaces.Contains (imp))
1720                                         new_ifaces.Add (imp);
1721                         }
1722                 }
1723                 Type [] ret = new Type [new_ifaces.Count];
1724                 new_ifaces.CopyTo (ret, 0);
1725                 return ret;
1726         }
1727         
1728         static PtrHashtable iface_cache = new PtrHashtable ();
1729                 
1730         /// <summary>
1731         ///   This function returns the interfaces in the type `t'.  Works with
1732         ///   both types and TypeBuilders.
1733         /// </summary>
1734         public static Type [] GetInterfaces (Type t)
1735         {
1736                 
1737                 Type [] cached = iface_cache [t] as Type [];
1738                 if (cached != null)
1739                         return cached;
1740                 
1741                 //
1742                 // The reason for catching the Array case is that Reflection.Emit
1743                 // will not return a TypeBuilder for Array types of TypeBuilder types,
1744                 // but will still throw an exception if we try to call GetInterfaces
1745                 // on the type.
1746                 //
1747                 // Since the array interfaces are always constant, we return those for
1748                 // the System.Array
1749                 //
1750                 
1751                 if (t.IsArray)
1752                         t = TypeManager.array_type;
1753                 
1754                 if (t is TypeBuilder){
1755                         Type [] base_ifaces;
1756                         
1757                         if (t.BaseType == null)
1758                                 base_ifaces = NoTypes;
1759                         else
1760                                 base_ifaces = GetInterfaces (t.BaseType);
1761                         Type [] type_ifaces = (Type []) builder_to_ifaces [t];
1762                         if (type_ifaces == null)
1763                                 type_ifaces = NoTypes;
1764
1765                         int base_count = base_ifaces.Length;
1766                         Type [] result = new Type [base_count + type_ifaces.Length];
1767                         base_ifaces.CopyTo (result, 0);
1768                         type_ifaces.CopyTo (result, base_count);
1769
1770                         iface_cache [t] = result;
1771                         return result;
1772                 } else {
1773                         Type[] ifaces = t.GetInterfaces ();
1774                         iface_cache [t] = ifaces;
1775                         return ifaces;
1776                 }
1777         }
1778         
1779         //
1780         // gets the interfaces that are declared explicitly on t
1781         //
1782         public static Type [] GetExplicitInterfaces (TypeBuilder t)
1783         {
1784                 return (Type []) builder_to_ifaces [t];
1785         }
1786         
1787         /// <remarks>
1788         ///  The following is used to check if a given type implements an interface.
1789         ///  The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1790         /// </remarks>
1791         public static bool ImplementsInterface (Type t, Type iface)
1792         {
1793                 Type [] interfaces;
1794
1795                 //
1796                 // FIXME OPTIMIZATION:
1797                 // as soon as we hit a non-TypeBuiler in the interface
1798                 // chain, we could return, as the `Type.GetInterfaces'
1799                 // will return all the interfaces implement by the type
1800                 // or its bases.
1801                 //
1802                 do {
1803                         interfaces = GetInterfaces (t);
1804
1805                         if (interfaces != null){
1806                                 foreach (Type i in interfaces){
1807                                         if (i == iface)
1808                                                 return true;
1809                                 }
1810                         }
1811                         
1812                         t = t.BaseType;
1813                 } while (t != null);
1814                 
1815                 return false;
1816         }
1817
1818         static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
1819
1820         // This is a custom version of Convert.ChangeType() which works
1821         // with the TypeBuilder defined types when compiling corlib.
1822         public static object ChangeType (object value, Type conversionType, out bool error)
1823         {
1824                 IConvertible convert_value = value as IConvertible;
1825                 
1826                 if (convert_value == null){
1827                         error = true;
1828                         return null;
1829                 }
1830                 
1831                 //
1832                 // We must use Type.Equals() here since `conversionType' is
1833                 // the TypeBuilder created version of a system type and not
1834                 // the system type itself.  You cannot use Type.GetTypeCode()
1835                 // on such a type - it'd always return TypeCode.Object.
1836                 //
1837                 error = false;
1838                 try {
1839                         if (conversionType.Equals (typeof (Boolean)))
1840                                 return (object)(convert_value.ToBoolean (nf_provider));
1841                         else if (conversionType.Equals (typeof (Byte)))
1842                                 return (object)(convert_value.ToByte (nf_provider));
1843                         else if (conversionType.Equals (typeof (Char)))
1844                                 return (object)(convert_value.ToChar (nf_provider));
1845                         else if (conversionType.Equals (typeof (DateTime)))
1846                                 return (object)(convert_value.ToDateTime (nf_provider));
1847                         else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
1848                                 return (object)(convert_value.ToDecimal (nf_provider));
1849                         else if (conversionType.Equals (typeof (Double)))
1850                                 return (object)(convert_value.ToDouble (nf_provider));
1851                         else if (conversionType.Equals (typeof (Int16)))
1852                                 return (object)(convert_value.ToInt16 (nf_provider));
1853                         else if (conversionType.Equals (typeof (Int32)))
1854                                 return (object)(convert_value.ToInt32 (nf_provider));
1855                         else if (conversionType.Equals (typeof (Int64)))
1856                                 return (object)(convert_value.ToInt64 (nf_provider));
1857                         else if (conversionType.Equals (typeof (SByte)))
1858                                 return (object)(convert_value.ToSByte (nf_provider));
1859                         else if (conversionType.Equals (typeof (Single)))
1860                                 return (object)(convert_value.ToSingle (nf_provider));
1861                         else if (conversionType.Equals (typeof (String)))
1862                                 return (object)(convert_value.ToString (nf_provider));
1863                         else if (conversionType.Equals (typeof (UInt16)))
1864                                 return (object)(convert_value.ToUInt16 (nf_provider));
1865                         else if (conversionType.Equals (typeof (UInt32)))
1866                                 return (object)(convert_value.ToUInt32 (nf_provider));
1867                         else if (conversionType.Equals (typeof (UInt64)))
1868                                 return (object)(convert_value.ToUInt64 (nf_provider));
1869                         else if (conversionType.Equals (typeof (Object)))
1870                                 return (object)(value);
1871                         else 
1872                                 error = true;
1873                 } catch {
1874                         error = true;
1875                 }
1876                 return null;
1877         }
1878
1879         //
1880         // This is needed, because enumerations from assemblies
1881         // do not report their underlyingtype, but they report
1882         // themselves
1883         //
1884         public static Type EnumToUnderlying (Type t)
1885         {
1886                 if (t == TypeManager.enum_type)
1887                         return t;
1888
1889                 t = t.UnderlyingSystemType;
1890                 if (!TypeManager.IsEnumType (t))
1891                         return t;
1892         
1893                 if (t is TypeBuilder) {
1894                         // slow path needed to compile corlib
1895                         if (t == TypeManager.bool_type ||
1896                             t == TypeManager.byte_type ||
1897                             t == TypeManager.sbyte_type ||
1898                             t == TypeManager.char_type ||
1899                             t == TypeManager.short_type ||
1900                             t == TypeManager.ushort_type ||
1901                             t == TypeManager.int32_type ||
1902                             t == TypeManager.uint32_type ||
1903                             t == TypeManager.int64_type ||
1904                             t == TypeManager.uint64_type)
1905                                 return t;
1906                 }
1907                 TypeCode tc = Type.GetTypeCode (t);
1908
1909                 switch (tc){
1910                 case TypeCode.Boolean:
1911                         return TypeManager.bool_type;
1912                 case TypeCode.Byte:
1913                         return TypeManager.byte_type;
1914                 case TypeCode.SByte:
1915                         return TypeManager.sbyte_type;
1916                 case TypeCode.Char:
1917                         return TypeManager.char_type;
1918                 case TypeCode.Int16:
1919                         return TypeManager.short_type;
1920                 case TypeCode.UInt16:
1921                         return TypeManager.ushort_type;
1922                 case TypeCode.Int32:
1923                         return TypeManager.int32_type;
1924                 case TypeCode.UInt32:
1925                         return TypeManager.uint32_type;
1926                 case TypeCode.Int64:
1927                         return TypeManager.int64_type;
1928                 case TypeCode.UInt64:
1929                         return TypeManager.uint64_type;
1930                 }
1931                 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
1932         }
1933
1934         //
1935         // When compiling corlib and called with one of the core types, return
1936         // the corresponding typebuilder for that type.
1937         //
1938         public static Type TypeToCoreType (Type t)
1939         {
1940                 if (RootContext.StdLib || (t is TypeBuilder))
1941                         return t;
1942
1943                 TypeCode tc = Type.GetTypeCode (t);
1944
1945                 switch (tc){
1946                 case TypeCode.Boolean:
1947                         return TypeManager.bool_type;
1948                 case TypeCode.Byte:
1949                         return TypeManager.byte_type;
1950                 case TypeCode.SByte:
1951                         return TypeManager.sbyte_type;
1952                 case TypeCode.Char:
1953                         return TypeManager.char_type;
1954                 case TypeCode.Int16:
1955                         return TypeManager.short_type;
1956                 case TypeCode.UInt16:
1957                         return TypeManager.ushort_type;
1958                 case TypeCode.Int32:
1959                         return TypeManager.int32_type;
1960                 case TypeCode.UInt32:
1961                         return TypeManager.uint32_type;
1962                 case TypeCode.Int64:
1963                         return TypeManager.int64_type;
1964                 case TypeCode.UInt64:
1965                         return TypeManager.uint64_type;
1966                 case TypeCode.Single:
1967                         return TypeManager.float_type;
1968                 case TypeCode.Double:
1969                         return TypeManager.double_type;
1970                 case TypeCode.String:
1971                         return TypeManager.string_type;
1972                 case TypeCode.Decimal:
1973                         return TypeManager.decimal_type;
1974                 default:
1975                         if (t == typeof (void))
1976                                 return TypeManager.void_type;
1977                         if (t == typeof (object))
1978                                 return TypeManager.object_type;
1979                         if (t == typeof (System.Type))
1980                                 return TypeManager.type_type;
1981                         if (t == typeof (System.IntPtr))
1982                                 return TypeManager.intptr_type;
1983                         return t;
1984                 }
1985         }
1986
1987         /// <summary>
1988         ///   Utility function that can be used to probe whether a type
1989         ///   is managed or not.  
1990         /// </summary>
1991         public static bool VerifyUnManaged (Type t, Location loc)
1992         {
1993                 if (IsUnmanagedType (t))
1994                         return true;
1995
1996                 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
1997                         CSharpName (t));
1998
1999                 return false;   
2000         }
2001         
2002         /// <summary>
2003         ///   Returns the name of the indexer in a given type.
2004         /// </summary>
2005         /// <remarks>
2006         ///   The default is not always `Item'.  The user can change this behaviour by
2007         ///   using the IndexerNameAttribute in the container.
2008         ///   For example, the String class indexer is named `Chars' not `Item' 
2009         /// </remarks>
2010         public static string IndexerPropertyName (Type t)
2011         {
2012                 if (t is TypeBuilder) {
2013                         TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2014                         return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2015                 }
2016                 
2017                 System.Attribute attr = System.Attribute.GetCustomAttribute (
2018                         t, TypeManager.default_member_type);
2019                 if (attr != null){
2020                         DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2021                         return dma.MemberName;
2022                 }
2023
2024                 return TypeContainer.DefaultIndexerName;
2025         }
2026
2027         static MethodInfo declare_local_method = null;
2028         
2029         public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2030         {
2031                 if (declare_local_method == null){
2032                         declare_local_method = typeof (ILGenerator).GetMethod (
2033                                 "DeclareLocal",
2034                                 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2035                                 null, 
2036                                 new Type [] { typeof (Type), typeof (bool)},
2037                                 null);
2038                         if (declare_local_method == null){
2039                                 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2040                                 return ig.DeclareLocal (t);
2041                         }
2042                 }
2043                 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2044         }
2045         
2046         //
2047         // Returns whether the array of memberinfos contains the given method
2048         //
2049         public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2050         {
2051                 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2052                 
2053                 foreach (MethodBase method in array) {
2054                         if (method.Name != new_method.Name)
2055                                 continue;
2056
2057                         if (method is MethodInfo && new_method is MethodInfo)
2058                                 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2059                                         continue;
2060
2061                         
2062                         Type [] old_args = TypeManager.GetParameterData (method).Types;
2063                         int old_count = old_args.Length;
2064                         int i;
2065                         
2066                         if (new_args.Length != old_count)
2067                                 continue;
2068                         
2069                         for (i = 0; i < old_count; i++){
2070                                 if (old_args [i] != new_args [i])
2071                                         break;
2072                         }
2073                         if (i != old_count)
2074                                 continue;
2075
2076                         return true;
2077                 }
2078                 
2079                 return false;
2080         }
2081         
2082         //
2083         // We copy methods from `new_members' into `target_list' if the signature
2084         // for the method from in the new list does not exist in the target_list
2085         //
2086         // The name is assumed to be the same.
2087         //
2088         public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2089         {
2090                 if (target_list == null){
2091                         target_list = new ArrayList ();
2092
2093                         foreach (MemberInfo mi in new_members){
2094                                 if (mi is MethodBase)
2095                                         target_list.Add (mi);
2096                         }
2097                         return target_list;
2098                 }
2099                 
2100                 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2101                 target_list.CopyTo (target_array, 0);
2102                 
2103                 foreach (MemberInfo mi in new_members){
2104                         MethodBase new_method = (MethodBase) mi;
2105                         
2106                         if (!ArrayContainsMethod (target_array, new_method))
2107                                 target_list.Add (new_method);
2108                 }
2109                 return target_list;
2110         }
2111
2112
2113         // This method always return false for non-generic compiler,
2114         // while Type.IsGenericParameter is returned if it is supported.
2115         public static bool IsGenericParameter (Type type)
2116         {
2117                 return false;
2118         }
2119
2120         public static int GenericParameterPosition (Type type)
2121         {
2122                 throw new InternalErrorException ("should not be called");
2123         }
2124
2125 #region MemberLookup implementation
2126         
2127         //
2128         // Whether we allow private members in the result (since FindMembers
2129         // uses NonPublic for both protected and private), we need to distinguish.
2130         //
2131
2132         static internal bool FilterNone (MemberInfo m, object filter_criteria)
2133         {
2134                 return true;
2135         }
2136
2137         internal class Closure {
2138                 internal bool     private_ok;
2139
2140                 // Who is invoking us and which type is being queried currently.
2141                 internal Type     invocation_type;
2142                 internal Type     qualifier_type;
2143
2144                 // The assembly that defines the type is that is calling us
2145                 internal Assembly invocation_assembly;
2146                 internal IList almost_match;
2147
2148                 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2149                 {
2150                         if (invocation_type == null)
2151                                 return false;
2152
2153                         if (is_static && qualifier_type == null)
2154                                 // It resolved from a simple name, so it should be visible.
2155                                 return true;
2156
2157                         // A nested class has access to all the protected members visible to its parent.
2158                         if (qualifier_type != null && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2159                                 return true;
2160
2161                         if (invocation_type == m.DeclaringType || invocation_type.IsSubclassOf (m.DeclaringType)) {
2162                                 // Although a derived class can access protected members of its base class
2163                                 // it cannot do so through an instance of the base class (CS1540).
2164                                 // => Ancestry should be: declaring_type ->* invocation_type ->*  qualified_type
2165                                 if (is_static ||
2166                                     qualifier_type == null ||
2167                                     qualifier_type == invocation_type ||
2168                                     qualifier_type.IsSubclassOf (invocation_type))
2169                                         return true;
2170                         }
2171
2172                         if (almost_match != null)
2173                                 almost_match.Add (m);
2174
2175                         return false;
2176                 }
2177                 
2178                 //
2179                 // This filter filters by name + whether it is ok to include private
2180                 // members in the search
2181                 //
2182                 internal bool Filter (MemberInfo m, object filter_criteria)
2183                 {
2184                         //
2185                         // Hack: we know that the filter criteria will always be in the `closure'
2186                         // fields. 
2187                         //
2188
2189                         if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2190                                 return false;
2191                         
2192                         if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2193                             (m.DeclaringType == invocation_type))
2194                                 return true;
2195                         
2196                         //
2197                         // Ugly: we need to find out the type of `m', and depending
2198                         // on this, tell whether we accept or not
2199                         //
2200                         if (m is MethodBase){
2201                                 MethodBase mb = (MethodBase) m;
2202                                 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2203
2204                                 if (ma == MethodAttributes.Private)
2205                                         return private_ok || invocation_type == m.DeclaringType ||
2206                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2207
2208                                 if (invocation_assembly == mb.DeclaringType.Assembly) {
2209                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2210                                                 return true;
2211                                 } else {
2212                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2213                                                 return false;
2214                                 }
2215
2216                                 if (ma == MethodAttributes.Family ||
2217                                     ma == MethodAttributes.FamANDAssem ||
2218                                     ma == MethodAttributes.FamORAssem)
2219                                         return CheckValidFamilyAccess (mb.IsStatic, m);
2220                                 
2221                                 // Public.
2222                                 return true;
2223                         }
2224                         
2225                         if (m is FieldInfo){
2226                                 FieldInfo fi = (FieldInfo) m;
2227                                 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2228                                 
2229                                 if (fa == FieldAttributes.Private)
2230                                         return private_ok || (invocation_type == m.DeclaringType) ||
2231                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2232
2233                                 if (invocation_assembly == fi.DeclaringType.Assembly) {
2234                                         if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamORAssem)
2235                                                 return true;
2236                                 } else {
2237                                         if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamANDAssem)
2238                                                 return false;
2239                                 }
2240
2241                                 if (fa == FieldAttributes.Family ||
2242                                     fa == FieldAttributes.FamANDAssem ||
2243                                     fa == FieldAttributes.FamORAssem)
2244                                         return CheckValidFamilyAccess (fi.IsStatic, m);
2245                                 
2246                                 // Public.
2247                                 return true;
2248                         }
2249                         
2250                         //
2251                         // EventInfos and PropertyInfos, return true because they lack permission
2252                         // information, so we need to check later on the methods.
2253                         //
2254                         return true;
2255                 }
2256         }
2257
2258         static Closure closure = new Closure ();
2259         static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2260
2261         //
2262         // Looks up a member called `name' in the `queried_type'.  This lookup
2263         // is done by code that is contained in the definition for `invocation_type'
2264         // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2265         //
2266         // `invocation_type' is used to check whether we're allowed to access the requested
2267         // member wrt its protection level.
2268         //
2269         // When called from MemberAccess, `qualifier_type' is the type which is used to access
2270         // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2271         // is B and qualifier_type is A).  This is used to do the CS1540 check.
2272         //
2273         // When resolving a SimpleName, `qualifier_type' is null.
2274         //
2275         // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2276         // the same than `queried_type' - except when we're being called from BaseAccess;
2277         // in this case, `invocation_type' is the current type and `queried_type' the base
2278         // type, so this'd normally trigger a CS1540.
2279         //
2280         // The binding flags are `bf' and the kind of members being looked up are `mt'
2281         //
2282         // The return value always includes private members which code in `invocation_type'
2283         // is allowed to access (using the specified `qualifier_type' if given); only use
2284         // BindingFlags.NonPublic to bypass the permission check.
2285         //
2286         // The 'almost_match' argument is used for reporting error CS1540.
2287         //
2288         // Returns an array of a single element for everything but Methods/Constructors
2289         // that might return multiple matches.
2290         //
2291         public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2292                                                   Type queried_type,  MemberTypes mt,
2293                                                   BindingFlags original_bf, string name, IList almost_match)
2294         {
2295                 Timer.StartTimer (TimerType.MemberLookup);
2296
2297                 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2298                                                         queried_type, mt, original_bf, name, almost_match);
2299
2300                 Timer.StopTimer (TimerType.MemberLookup);
2301
2302                 return retval;
2303         }
2304
2305         static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2306                                                Type queried_type, MemberTypes mt,
2307                                                BindingFlags original_bf, string name, IList almost_match)
2308         {
2309                 BindingFlags bf = original_bf;
2310                 
2311                 ArrayList method_list = null;
2312                 Type current_type = queried_type;
2313                 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2314                 bool skip_iface_check = true, used_cache = false;
2315                 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2316
2317                 closure.invocation_type = invocation_type;
2318                 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2319                 closure.qualifier_type = qualifier_type;
2320                 closure.almost_match = almost_match;
2321                 
2322                 // This is from the first time we find a method
2323                 // in most cases, we do not actually find a method in the base class
2324                 // so we can just ignore it, and save the arraylist allocation
2325                 MemberInfo [] first_members_list = null;
2326                 bool use_first_members_list = false;
2327                 
2328                 do {
2329                         MemberInfo [] list;
2330
2331                         //
2332                         // `NonPublic' is lame, because it includes both protected and
2333                         // private methods, so we need to control this behavior by
2334                         // explicitly tracking if a private method is ok or not.
2335                         //
2336                         // The possible cases are:
2337                         //    public, private and protected (internal does not come into the
2338                         //    equation)
2339                         //
2340                         if ((invocation_type != null) &&
2341                             ((invocation_type == current_type) ||
2342                              IsNestedChildOf (invocation_type, current_type)) ||
2343                             always_ok_flag)
2344                                 bf = original_bf | BindingFlags.NonPublic;
2345                         else
2346                                 bf = original_bf;
2347
2348                         closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2349
2350                         Timer.StopTimer (TimerType.MemberLookup);
2351
2352                         list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2353
2354                         Timer.StartTimer (TimerType.MemberLookup);
2355
2356                         //
2357                         // When queried for an interface type, the cache will automatically check all
2358                         // inherited members, so we don't need to do this here.  However, this only
2359                         // works if we already used the cache in the first iteration of this loop.
2360                         //
2361                         // If we used the cache in any further iteration, we can still terminate the
2362                         // loop since the cache always looks in all base classes.
2363                         //
2364
2365                         if (used_cache)
2366                                 searching = false;
2367                         else
2368                                 skip_iface_check = false;
2369
2370                         if (current_type == TypeManager.object_type)
2371                                 searching = false;
2372                         else {
2373                                 current_type = current_type.BaseType;
2374                                 
2375                                 //
2376                                 // This happens with interfaces, they have a null
2377                                 // basetype.  Look members up in the Object class.
2378                                 //
2379                                 if (current_type == null) {
2380                                         current_type = TypeManager.object_type;
2381                                         searching = true;
2382                                 }
2383                         }
2384                         
2385                         if (list.Length == 0)
2386                                 continue;
2387
2388                         //
2389                         // Events and types are returned by both `static' and `instance'
2390                         // searches, which means that our above FindMembers will
2391                         // return two copies of the same.
2392                         //
2393                         if (list.Length == 1 && !(list [0] is MethodBase)){
2394                                 return list;
2395                         }
2396
2397                         //
2398                         // Multiple properties: we query those just to find out the indexer
2399                         // name
2400                         //
2401                         if (list [0] is PropertyInfo)
2402                                 return list;
2403
2404                         //
2405                         // We found an event: the cache lookup returns both the event and
2406                         // its private field.
2407                         //
2408                         if (list [0] is EventInfo) {
2409                                 if ((list.Length == 2) && (list [1] is FieldInfo))
2410                                         return new MemberInfo [] { list [0] };
2411
2412                                 // Oooops
2413                                 return null;
2414                         }
2415
2416                         //
2417                         // We found methods, turn the search into "method scan"
2418                         // mode.
2419                         //
2420
2421                         if (first_members_list != null) {
2422                                 if (use_first_members_list) {
2423                                         method_list = CopyNewMethods (method_list, first_members_list);
2424                                         use_first_members_list = false;
2425                                 }
2426                                 
2427                                 method_list = CopyNewMethods (method_list, list);
2428                         } else {
2429                                 first_members_list = list;
2430                                 use_first_members_list = true;
2431                                 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2432                         }
2433                 } while (searching);
2434                 
2435                 if (use_first_members_list) {
2436                         foreach (MemberInfo mi in first_members_list) {
2437                                 if (! (mi is MethodBase)) {
2438                                         method_list = CopyNewMethods (method_list, first_members_list);
2439                                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2440                                 }
2441                         }
2442                         return (MemberInfo []) first_members_list;
2443                 }
2444
2445                 if (method_list != null && method_list.Count > 0)
2446                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2447                 
2448                 //
2449                 // This happens if we already used the cache in the first iteration, in this case
2450                 // the cache already looked in all interfaces.
2451                 //
2452                 if (skip_iface_check)
2453                         return null;
2454
2455                 //
2456                 // Interfaces do not list members they inherit, so we have to
2457                 // scan those.
2458                 // 
2459                 if (!queried_type.IsInterface)
2460                         return null;
2461
2462                 if (queried_type.IsArray)
2463                         queried_type = TypeManager.array_type;
2464                 
2465                 Type [] ifaces = GetInterfaces (queried_type);
2466                 if (ifaces == null)
2467                         return null;
2468                 
2469                 foreach (Type itype in ifaces){
2470                         MemberInfo [] x;
2471
2472                         x = MemberLookup (null, null, itype, mt, bf, name, null);
2473                         if (x != null)
2474                                 return x;
2475                 }
2476                                         
2477                 return null;
2478         }
2479
2480         // Tests whether external method is really special
2481         public static bool IsSpecialMethod (MethodBase mb)
2482         {
2483                 string name = mb.Name;
2484                 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2485                         return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2486
2487                 if (name.StartsWith ("add_"))
2488                         return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2489
2490                 if (name.StartsWith ("remove_"))
2491                         return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2492
2493                 if (name.StartsWith ("op_")){
2494                         foreach (string oname in Unary.oper_names) {
2495                                 if (oname == name)
2496                                         return true;
2497                         }
2498                 
2499                         foreach (string oname in Binary.oper_names) {
2500                                 if (oname == name)
2501                                         return true;
2502                         }
2503                 }
2504                 return false;
2505         }
2506                 
2507 #endregion
2508         
2509 }
2510
2511 /// <summary>
2512 ///   There is exactly one instance of this class per type.
2513 /// </summary>
2514 public sealed class TypeHandle : IMemberContainer {
2515         public readonly IMemberContainer BaseType;
2516
2517         readonly int id = ++next_id;
2518         static int next_id = 0;
2519
2520         static TypeHandle ()
2521         {
2522                 Reset ();
2523         }
2524
2525         /// <summary>
2526         ///   Lookup a TypeHandle instance for the given type.  If the type doesn't have
2527         ///   a TypeHandle yet, a new instance of it is created.  This static method
2528         ///   ensures that we'll only have one TypeHandle instance per type.
2529         /// </summary>
2530         private static TypeHandle GetTypeHandle (Type t)
2531         {
2532                 TypeHandle handle = (TypeHandle) type_hash [t];
2533                 if (handle != null)
2534                         return handle;
2535
2536                 handle = new TypeHandle (t);
2537                 type_hash.Add (t, handle);
2538                 return handle;
2539         }
2540
2541         public static MemberCache GetMemberCache (Type t)
2542         {
2543                 return GetTypeHandle (t).MemberCache;
2544         }
2545         
2546         public static void CleanUp ()
2547         {
2548                 type_hash = null;
2549         }
2550
2551         public static void Reset ()
2552         {
2553                 type_hash = new PtrHashtable ();
2554         }
2555
2556         /// <summary>
2557         ///   Returns the TypeHandle for TypeManager.object_type.
2558         /// </summary>
2559         public static IMemberContainer ObjectType {
2560                 get {
2561                         if (object_type != null)
2562                                 return object_type;
2563
2564                         object_type = GetTypeHandle (TypeManager.object_type);
2565
2566                         return object_type;
2567                 }
2568         }
2569
2570         /// <summary>
2571         ///   Returns the TypeHandle for TypeManager.array_type.
2572         /// </summary>
2573         public static IMemberContainer ArrayType {
2574                 get {
2575                         if (array_type != null)
2576                                 return array_type;
2577
2578                         array_type = GetTypeHandle (TypeManager.array_type);
2579
2580                         return array_type;
2581                 }
2582         }
2583
2584         private static PtrHashtable type_hash;
2585
2586         private static TypeHandle object_type = null;
2587         private static TypeHandle array_type = null;
2588
2589         private Type type;
2590         private bool is_interface;
2591         private MemberCache member_cache;
2592         private MemberCache base_cache;
2593
2594         private TypeHandle (Type type)
2595         {
2596                 this.type = type;
2597                 if (type.BaseType != null) {
2598                         base_cache = TypeManager.LookupMemberCache (type.BaseType);
2599                         BaseType = base_cache.Container;
2600                 } else if (type.IsInterface)
2601                         base_cache = TypeManager.LookupBaseInterfacesCache (type);
2602                 this.is_interface = type.IsInterface;
2603                 this.member_cache = new MemberCache (this);
2604         }
2605
2606         // IMemberContainer methods
2607
2608         public string Name {
2609                 get {
2610                         return type.FullName;
2611                 }
2612         }
2613
2614         public Type Type {
2615                 get {
2616                         return type;
2617                 }
2618         }
2619
2620         public MemberCache BaseCache {
2621                 get {
2622                         return base_cache;
2623                 }
2624         }
2625
2626         public bool IsInterface {
2627                 get {
2628                         return is_interface;
2629                 }
2630         }
2631
2632         public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2633         {
2634                 MemberInfo [] members;
2635                 if (mt == MemberTypes.Event)
2636                         members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2637                 else
2638                         members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2639                                                     null, null);
2640                 Array.Reverse (members);
2641
2642                 return new MemberList (members);
2643         }
2644
2645         // IMemberFinder methods
2646
2647         public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2648                                        MemberFilter filter, object criteria)
2649         {
2650                 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2651         }
2652
2653         public MemberCache MemberCache {
2654                 get {
2655                         return member_cache;
2656                 }
2657         }
2658
2659         public override string ToString ()
2660         {
2661                 if (BaseType != null)
2662                         return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2663                 else
2664                         return "TypeHandle (" + id + "," + Name + ")";
2665         }
2666 }
2667
2668 }