merge -r 58060:58217
[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                         if (method_overrides [override_method] != base_method)
1494                                 throw new InternalErrorException ("Override mismatch: " + override_method);
1495                         return;
1496                 }
1497                 method_overrides [override_method] = base_method;
1498         }
1499
1500         static public bool IsOverride (MethodBase m)
1501         {
1502                 return m.IsVirtual &&
1503                         (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1504                         (m is MethodBuilder || method_overrides.Contains (m));
1505         }
1506
1507         /// <summary>
1508         ///    Returns the argument types for an indexer based on its PropertyInfo
1509         ///
1510         ///    For dynamic indexers, we use the compiler provided types, for
1511         ///    indexers from existing assemblies we load them from GetParameters,
1512         ///    and insert them into the cache
1513         /// </summary>
1514         static public Type [] GetArgumentTypes (PropertyInfo indexer)
1515         {
1516                 if (indexer_arguments.Contains (indexer))
1517                         return (Type []) indexer_arguments [indexer];
1518                 else if (indexer is PropertyBuilder)
1519                         // If we're a PropertyBuilder and not in the
1520                         // `indexer_arguments' hash, then we're a property and
1521                         // not an indexer.
1522                         return NoTypes;
1523                 else {
1524                         ParameterInfo [] pi = indexer.GetIndexParameters ();
1525                         // Property, not an indexer.
1526                         if (pi == null)
1527                                 return NoTypes;
1528                         int c = pi.Length;
1529                         Type [] types = new Type [c];
1530                         
1531                         for (int i = 0; i < c; i++)
1532                                 types [i] = pi [i].ParameterType;
1533
1534                         indexer_arguments.Add (indexer, types);
1535                         return types;
1536                 }
1537         }
1538         
1539         public static void RegisterConstant (FieldInfo fb, IConstant ic)
1540         {
1541                 fields.Add (fb, ic);
1542         }
1543
1544         public static IConstant GetConstant (FieldInfo fb)
1545         {
1546                 if (fb == null)
1547                         return null;
1548
1549                 return (IConstant)fields [fb];
1550         }
1551
1552         static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1553         {
1554                 if (fieldbuilders_to_fields.Contains (fb))
1555                         return false;
1556
1557                 fieldbuilders_to_fields.Add (fb, f);
1558                 return true;
1559         }
1560
1561         //
1562         // The return value can be null;  This will be the case for
1563         // auxiliary FieldBuilders created by the compiler that have no
1564         // real field being declared on the source code
1565         //
1566         static public FieldBase GetField (FieldInfo fb)
1567         {
1568                 return (FieldBase) fieldbuilders_to_fields [fb];
1569         }
1570         
1571         static Hashtable events;
1572
1573         static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1574         {
1575                 if (events == null)
1576                         events = new Hashtable ();
1577
1578                 if (!events.Contains (eb)) {
1579                         events.Add (eb, new Pair (add, remove));
1580                 }
1581         }
1582
1583         static public MethodInfo GetAddMethod (EventInfo ei)
1584         {
1585                 if (ei is MyEventBuilder) {
1586                         Pair pair = (Pair) events [ei];
1587
1588                         return (MethodInfo) pair.First;
1589                 }
1590                 return ei.GetAddMethod (true);
1591         }
1592
1593         static public MethodInfo GetRemoveMethod (EventInfo ei)
1594         {
1595                 if (ei is MyEventBuilder) {
1596                         Pair pair = (Pair) events [ei];
1597
1598                         return (MethodInfo) pair.Second;
1599                 }
1600                 return ei.GetRemoveMethod (true);
1601         }
1602
1603         static Hashtable priv_fields_events;
1604
1605         static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1606         {
1607                 if (priv_fields_events == null)
1608                         priv_fields_events = new Hashtable ();
1609
1610                 if (priv_fields_events.Contains (einfo))
1611                         return false;
1612
1613                 priv_fields_events.Add (einfo, builder);
1614
1615                 return true;
1616         }
1617
1618         static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1619         {
1620                 if (priv_fields_events == null)
1621                         return null;
1622                 else
1623                         return (MemberInfo) priv_fields_events [ei];
1624         }
1625                 
1626         static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1627                                             MethodBase set, Type[] args)
1628         {
1629                 indexer_arguments.Add (pb, args);
1630
1631                 return true;
1632         }
1633
1634         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1635         {
1636                 Hashtable hash = new Hashtable ();
1637                 return CheckStructCycles (tc, seen, hash);
1638         }
1639
1640         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1641                                               Hashtable hash)
1642         {
1643                 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1644                         return true;
1645
1646                 //
1647                 // `seen' contains all types we've already visited.
1648                 //
1649                 if (seen.Contains (tc))
1650                         return true;
1651                 seen.Add (tc, null);
1652
1653                 if (tc.Fields == null)
1654                         return true;
1655
1656                 foreach (FieldMember field in tc.Fields) {
1657                         if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1658                                 continue;
1659
1660                         Type ftype = field.FieldBuilder.FieldType;
1661                         TypeContainer ftc = LookupTypeContainer (ftype);
1662                         if (ftc == null)
1663                                 continue;
1664
1665                         if (hash.Contains (ftc)) {
1666                                 Report.Error (523, tc.Location,
1667                                               "Struct member `{0}.{1}' of type `{2}' " +
1668                                               "causes a cycle in the struct layout",
1669                                               tc.Name, field.Name, ftc.Name);
1670                                 return false;
1671                         }
1672
1673                         //
1674                         // `hash' contains all types in the current path.
1675                         //
1676                         hash.Add (tc, null);
1677
1678                         bool ok = CheckStructCycles (ftc, seen, hash);
1679
1680                         hash.Remove (tc);
1681
1682                         if (!ok)
1683                                 return false;
1684
1685                         if (!seen.Contains (ftc))
1686                                 seen.Add (ftc, null);
1687                 }
1688
1689                 return true;
1690         }
1691
1692         /// <summary>
1693         ///   Given an array of interface types, expand and eliminate repeated ocurrences
1694         ///   of an interface.  
1695         /// </summary>
1696         ///
1697         /// <remarks>
1698         ///   This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1699         ///   be IA, IB, IC.
1700         /// </remarks>
1701         public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
1702         {
1703                 ArrayList new_ifaces = new ArrayList ();
1704
1705                 foreach (TypeExpr iface in base_interfaces){
1706                         Type itype = iface.ResolveType (ec);
1707                         if (itype == null)
1708                                 return null;
1709
1710                         if (!new_ifaces.Contains (itype))
1711                                 new_ifaces.Add (itype);
1712                         
1713                         Type [] implementing = itype.GetInterfaces ();
1714                         
1715                         foreach (Type imp in implementing){
1716                                 if (!new_ifaces.Contains (imp))
1717                                         new_ifaces.Add (imp);
1718                         }
1719                 }
1720                 Type [] ret = new Type [new_ifaces.Count];
1721                 new_ifaces.CopyTo (ret, 0);
1722                 return ret;
1723         }
1724         
1725         static PtrHashtable iface_cache = new PtrHashtable ();
1726                 
1727         /// <summary>
1728         ///   This function returns the interfaces in the type `t'.  Works with
1729         ///   both types and TypeBuilders.
1730         /// </summary>
1731         public static Type [] GetInterfaces (Type t)
1732         {
1733                 
1734                 Type [] cached = iface_cache [t] as Type [];
1735                 if (cached != null)
1736                         return cached;
1737                 
1738                 //
1739                 // The reason for catching the Array case is that Reflection.Emit
1740                 // will not return a TypeBuilder for Array types of TypeBuilder types,
1741                 // but will still throw an exception if we try to call GetInterfaces
1742                 // on the type.
1743                 //
1744                 // Since the array interfaces are always constant, we return those for
1745                 // the System.Array
1746                 //
1747                 
1748                 if (t.IsArray)
1749                         t = TypeManager.array_type;
1750                 
1751                 if (t is TypeBuilder){
1752                         Type [] base_ifaces;
1753                         
1754                         if (t.BaseType == null)
1755                                 base_ifaces = NoTypes;
1756                         else
1757                                 base_ifaces = GetInterfaces (t.BaseType);
1758                         Type [] type_ifaces = (Type []) builder_to_ifaces [t];
1759                         if (type_ifaces == null)
1760                                 type_ifaces = NoTypes;
1761
1762                         int base_count = base_ifaces.Length;
1763                         Type [] result = new Type [base_count + type_ifaces.Length];
1764                         base_ifaces.CopyTo (result, 0);
1765                         type_ifaces.CopyTo (result, base_count);
1766
1767                         iface_cache [t] = result;
1768                         return result;
1769                 } else {
1770                         Type[] ifaces = t.GetInterfaces ();
1771                         iface_cache [t] = ifaces;
1772                         return ifaces;
1773                 }
1774         }
1775         
1776         //
1777         // gets the interfaces that are declared explicitly on t
1778         //
1779         public static Type [] GetExplicitInterfaces (TypeBuilder t)
1780         {
1781                 return (Type []) builder_to_ifaces [t];
1782         }
1783         
1784         /// <remarks>
1785         ///  The following is used to check if a given type implements an interface.
1786         ///  The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
1787         /// </remarks>
1788         public static bool ImplementsInterface (Type t, Type iface)
1789         {
1790                 Type [] interfaces;
1791
1792                 //
1793                 // FIXME OPTIMIZATION:
1794                 // as soon as we hit a non-TypeBuiler in the interface
1795                 // chain, we could return, as the `Type.GetInterfaces'
1796                 // will return all the interfaces implement by the type
1797                 // or its bases.
1798                 //
1799                 do {
1800                         interfaces = GetInterfaces (t);
1801
1802                         if (interfaces != null){
1803                                 foreach (Type i in interfaces){
1804                                         if (i == iface)
1805                                                 return true;
1806                                 }
1807                         }
1808                         
1809                         t = t.BaseType;
1810                 } while (t != null);
1811                 
1812                 return false;
1813         }
1814
1815         static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
1816
1817         // This is a custom version of Convert.ChangeType() which works
1818         // with the TypeBuilder defined types when compiling corlib.
1819         public static object ChangeType (object value, Type conversionType, out bool error)
1820         {
1821                 IConvertible convert_value = value as IConvertible;
1822                 
1823                 if (convert_value == null){
1824                         error = true;
1825                         return null;
1826                 }
1827                 
1828                 //
1829                 // We must use Type.Equals() here since `conversionType' is
1830                 // the TypeBuilder created version of a system type and not
1831                 // the system type itself.  You cannot use Type.GetTypeCode()
1832                 // on such a type - it'd always return TypeCode.Object.
1833                 //
1834                 error = false;
1835                 try {
1836                         if (conversionType.Equals (typeof (Boolean)))
1837                                 return (object)(convert_value.ToBoolean (nf_provider));
1838                         else if (conversionType.Equals (typeof (Byte)))
1839                                 return (object)(convert_value.ToByte (nf_provider));
1840                         else if (conversionType.Equals (typeof (Char)))
1841                                 return (object)(convert_value.ToChar (nf_provider));
1842                         else if (conversionType.Equals (typeof (DateTime)))
1843                                 return (object)(convert_value.ToDateTime (nf_provider));
1844                         else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
1845                                 return (object)(convert_value.ToDecimal (nf_provider));
1846                         else if (conversionType.Equals (typeof (Double)))
1847                                 return (object)(convert_value.ToDouble (nf_provider));
1848                         else if (conversionType.Equals (typeof (Int16)))
1849                                 return (object)(convert_value.ToInt16 (nf_provider));
1850                         else if (conversionType.Equals (typeof (Int32)))
1851                                 return (object)(convert_value.ToInt32 (nf_provider));
1852                         else if (conversionType.Equals (typeof (Int64)))
1853                                 return (object)(convert_value.ToInt64 (nf_provider));
1854                         else if (conversionType.Equals (typeof (SByte)))
1855                                 return (object)(convert_value.ToSByte (nf_provider));
1856                         else if (conversionType.Equals (typeof (Single)))
1857                                 return (object)(convert_value.ToSingle (nf_provider));
1858                         else if (conversionType.Equals (typeof (String)))
1859                                 return (object)(convert_value.ToString (nf_provider));
1860                         else if (conversionType.Equals (typeof (UInt16)))
1861                                 return (object)(convert_value.ToUInt16 (nf_provider));
1862                         else if (conversionType.Equals (typeof (UInt32)))
1863                                 return (object)(convert_value.ToUInt32 (nf_provider));
1864                         else if (conversionType.Equals (typeof (UInt64)))
1865                                 return (object)(convert_value.ToUInt64 (nf_provider));
1866                         else if (conversionType.Equals (typeof (Object)))
1867                                 return (object)(value);
1868                         else 
1869                                 error = true;
1870                 } catch {
1871                         error = true;
1872                 }
1873                 return null;
1874         }
1875
1876         //
1877         // This is needed, because enumerations from assemblies
1878         // do not report their underlyingtype, but they report
1879         // themselves
1880         //
1881         public static Type EnumToUnderlying (Type t)
1882         {
1883                 if (t == TypeManager.enum_type)
1884                         return t;
1885
1886                 t = t.UnderlyingSystemType;
1887                 if (!TypeManager.IsEnumType (t))
1888                         return t;
1889         
1890                 if (t is TypeBuilder) {
1891                         // slow path needed to compile corlib
1892                         if (t == TypeManager.bool_type ||
1893                             t == TypeManager.byte_type ||
1894                             t == TypeManager.sbyte_type ||
1895                             t == TypeManager.char_type ||
1896                             t == TypeManager.short_type ||
1897                             t == TypeManager.ushort_type ||
1898                             t == TypeManager.int32_type ||
1899                             t == TypeManager.uint32_type ||
1900                             t == TypeManager.int64_type ||
1901                             t == TypeManager.uint64_type)
1902                                 return t;
1903                 }
1904                 TypeCode tc = Type.GetTypeCode (t);
1905
1906                 switch (tc){
1907                 case TypeCode.Boolean:
1908                         return TypeManager.bool_type;
1909                 case TypeCode.Byte:
1910                         return TypeManager.byte_type;
1911                 case TypeCode.SByte:
1912                         return TypeManager.sbyte_type;
1913                 case TypeCode.Char:
1914                         return TypeManager.char_type;
1915                 case TypeCode.Int16:
1916                         return TypeManager.short_type;
1917                 case TypeCode.UInt16:
1918                         return TypeManager.ushort_type;
1919                 case TypeCode.Int32:
1920                         return TypeManager.int32_type;
1921                 case TypeCode.UInt32:
1922                         return TypeManager.uint32_type;
1923                 case TypeCode.Int64:
1924                         return TypeManager.int64_type;
1925                 case TypeCode.UInt64:
1926                         return TypeManager.uint64_type;
1927                 }
1928                 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
1929         }
1930
1931         //
1932         // When compiling corlib and called with one of the core types, return
1933         // the corresponding typebuilder for that type.
1934         //
1935         public static Type TypeToCoreType (Type t)
1936         {
1937                 if (RootContext.StdLib || (t is TypeBuilder))
1938                         return t;
1939
1940                 TypeCode tc = Type.GetTypeCode (t);
1941
1942                 switch (tc){
1943                 case TypeCode.Boolean:
1944                         return TypeManager.bool_type;
1945                 case TypeCode.Byte:
1946                         return TypeManager.byte_type;
1947                 case TypeCode.SByte:
1948                         return TypeManager.sbyte_type;
1949                 case TypeCode.Char:
1950                         return TypeManager.char_type;
1951                 case TypeCode.Int16:
1952                         return TypeManager.short_type;
1953                 case TypeCode.UInt16:
1954                         return TypeManager.ushort_type;
1955                 case TypeCode.Int32:
1956                         return TypeManager.int32_type;
1957                 case TypeCode.UInt32:
1958                         return TypeManager.uint32_type;
1959                 case TypeCode.Int64:
1960                         return TypeManager.int64_type;
1961                 case TypeCode.UInt64:
1962                         return TypeManager.uint64_type;
1963                 case TypeCode.Single:
1964                         return TypeManager.float_type;
1965                 case TypeCode.Double:
1966                         return TypeManager.double_type;
1967                 case TypeCode.String:
1968                         return TypeManager.string_type;
1969                 case TypeCode.Decimal:
1970                         return TypeManager.decimal_type;
1971                 default:
1972                         if (t == typeof (void))
1973                                 return TypeManager.void_type;
1974                         if (t == typeof (object))
1975                                 return TypeManager.object_type;
1976                         if (t == typeof (System.Type))
1977                                 return TypeManager.type_type;
1978                         if (t == typeof (System.IntPtr))
1979                                 return TypeManager.intptr_type;
1980                         return t;
1981                 }
1982         }
1983
1984         /// <summary>
1985         ///   Utility function that can be used to probe whether a type
1986         ///   is managed or not.  
1987         /// </summary>
1988         public static bool VerifyUnManaged (Type t, Location loc)
1989         {
1990                 if (IsUnmanagedType (t))
1991                         return true;
1992
1993                 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
1994                         CSharpName (t));
1995
1996                 return false;   
1997         }
1998         
1999         /// <summary>
2000         ///   Returns the name of the indexer in a given type.
2001         /// </summary>
2002         /// <remarks>
2003         ///   The default is not always `Item'.  The user can change this behaviour by
2004         ///   using the IndexerNameAttribute in the container.
2005         ///   For example, the String class indexer is named `Chars' not `Item' 
2006         /// </remarks>
2007         public static string IndexerPropertyName (Type t)
2008         {
2009                 if (t is TypeBuilder) {
2010                         TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2011                         return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2012                 }
2013                 
2014                 System.Attribute attr = System.Attribute.GetCustomAttribute (
2015                         t, TypeManager.default_member_type);
2016                 if (attr != null){
2017                         DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2018                         return dma.MemberName;
2019                 }
2020
2021                 return TypeContainer.DefaultIndexerName;
2022         }
2023
2024         static MethodInfo declare_local_method = null;
2025         
2026         public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2027         {
2028                 if (declare_local_method == null){
2029                         declare_local_method = typeof (ILGenerator).GetMethod (
2030                                 "DeclareLocal",
2031                                 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2032                                 null, 
2033                                 new Type [] { typeof (Type), typeof (bool)},
2034                                 null);
2035                         if (declare_local_method == null){
2036                                 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2037                                 return ig.DeclareLocal (t);
2038                         }
2039                 }
2040                 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2041         }
2042         
2043         //
2044         // Returns whether the array of memberinfos contains the given method
2045         //
2046         public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2047         {
2048                 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2049                 
2050                 foreach (MethodBase method in array) {
2051                         if (method.Name != new_method.Name)
2052                                 continue;
2053
2054                         if (method is MethodInfo && new_method is MethodInfo)
2055                                 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2056                                         continue;
2057
2058                         
2059                         Type [] old_args = TypeManager.GetParameterData (method).Types;
2060                         int old_count = old_args.Length;
2061                         int i;
2062                         
2063                         if (new_args.Length != old_count)
2064                                 continue;
2065                         
2066                         for (i = 0; i < old_count; i++){
2067                                 if (old_args [i] != new_args [i])
2068                                         break;
2069                         }
2070                         if (i != old_count)
2071                                 continue;
2072
2073                         return true;
2074                 }
2075                 
2076                 return false;
2077         }
2078         
2079         //
2080         // We copy methods from `new_members' into `target_list' if the signature
2081         // for the method from in the new list does not exist in the target_list
2082         //
2083         // The name is assumed to be the same.
2084         //
2085         public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2086         {
2087                 if (target_list == null){
2088                         target_list = new ArrayList ();
2089
2090                         foreach (MemberInfo mi in new_members){
2091                                 if (mi is MethodBase)
2092                                         target_list.Add (mi);
2093                         }
2094                         return target_list;
2095                 }
2096                 
2097                 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2098                 target_list.CopyTo (target_array, 0);
2099                 
2100                 foreach (MemberInfo mi in new_members){
2101                         MethodBase new_method = (MethodBase) mi;
2102                         
2103                         if (!ArrayContainsMethod (target_array, new_method))
2104                                 target_list.Add (new_method);
2105                 }
2106                 return target_list;
2107         }
2108
2109
2110 #region MemberLookup implementation
2111         
2112         //
2113         // Whether we allow private members in the result (since FindMembers
2114         // uses NonPublic for both protected and private), we need to distinguish.
2115         //
2116
2117         static internal bool FilterNone (MemberInfo m, object filter_criteria)
2118         {
2119                 return true;
2120         }
2121
2122         internal class Closure {
2123                 internal bool     private_ok;
2124
2125                 // Who is invoking us and which type is being queried currently.
2126                 internal Type     invocation_type;
2127                 internal Type     qualifier_type;
2128
2129                 // The assembly that defines the type is that is calling us
2130                 internal Assembly invocation_assembly;
2131                 internal IList almost_match;
2132
2133                 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2134                 {
2135                         if (invocation_type == null)
2136                                 return false;
2137
2138                         if (is_static && qualifier_type == null)
2139                                 // It resolved from a simple name, so it should be visible.
2140                                 return true;
2141
2142                         // A nested class has access to all the protected members visible to its parent.
2143                         if (qualifier_type != null && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2144                                 return true;
2145
2146                         if (invocation_type == m.DeclaringType || invocation_type.IsSubclassOf (m.DeclaringType)) {
2147                                 // Although a derived class can access protected members of its base class
2148                                 // it cannot do so through an instance of the base class (CS1540).
2149                                 // => Ancestry should be: declaring_type ->* invocation_type ->*  qualified_type
2150                                 if (is_static ||
2151                                     qualifier_type == null ||
2152                                     qualifier_type == invocation_type ||
2153                                     qualifier_type.IsSubclassOf (invocation_type))
2154                                         return true;
2155                         }
2156
2157                         if (almost_match != null)
2158                                 almost_match.Add (m);
2159
2160                         return false;
2161                 }
2162                 
2163                 //
2164                 // This filter filters by name + whether it is ok to include private
2165                 // members in the search
2166                 //
2167                 internal bool Filter (MemberInfo m, object filter_criteria)
2168                 {
2169                         //
2170                         // Hack: we know that the filter criteria will always be in the `closure'
2171                         // fields. 
2172                         //
2173
2174                         if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2175                                 return false;
2176                         
2177                         if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2178                             (m.DeclaringType == invocation_type))
2179                                 return true;
2180                         
2181                         //
2182                         // Ugly: we need to find out the type of `m', and depending
2183                         // on this, tell whether we accept or not
2184                         //
2185                         if (m is MethodBase){
2186                                 MethodBase mb = (MethodBase) m;
2187                                 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2188
2189                                 if (ma == MethodAttributes.Private)
2190                                         return private_ok || invocation_type == m.DeclaringType ||
2191                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2192
2193                                 if (invocation_assembly == mb.DeclaringType.Assembly) {
2194                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2195                                                 return true;
2196                                 } else {
2197                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2198                                                 return false;
2199                                 }
2200
2201                                 if (ma == MethodAttributes.Family ||
2202                                     ma == MethodAttributes.FamANDAssem ||
2203                                     ma == MethodAttributes.FamORAssem)
2204                                         return CheckValidFamilyAccess (mb.IsStatic, m);
2205                                 
2206                                 // Public.
2207                                 return true;
2208                         }
2209                         
2210                         if (m is FieldInfo){
2211                                 FieldInfo fi = (FieldInfo) m;
2212                                 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2213                                 
2214                                 if (fa == FieldAttributes.Private)
2215                                         return private_ok || (invocation_type == m.DeclaringType) ||
2216                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2217
2218                                 if (invocation_assembly == fi.DeclaringType.Assembly) {
2219                                         if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamORAssem)
2220                                                 return true;
2221                                 } else {
2222                                         if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamANDAssem)
2223                                                 return false;
2224                                 }
2225
2226                                 if (fa == FieldAttributes.Family ||
2227                                     fa == FieldAttributes.FamANDAssem ||
2228                                     fa == FieldAttributes.FamORAssem)
2229                                         return CheckValidFamilyAccess (fi.IsStatic, m);
2230                                 
2231                                 // Public.
2232                                 return true;
2233                         }
2234                         
2235                         //
2236                         // EventInfos and PropertyInfos, return true because they lack permission
2237                         // information, so we need to check later on the methods.
2238                         //
2239                         return true;
2240                 }
2241         }
2242
2243         static Closure closure = new Closure ();
2244         static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2245
2246         //
2247         // Looks up a member called `name' in the `queried_type'.  This lookup
2248         // is done by code that is contained in the definition for `invocation_type'
2249         // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2250         //
2251         // `invocation_type' is used to check whether we're allowed to access the requested
2252         // member wrt its protection level.
2253         //
2254         // When called from MemberAccess, `qualifier_type' is the type which is used to access
2255         // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2256         // is B and qualifier_type is A).  This is used to do the CS1540 check.
2257         //
2258         // When resolving a SimpleName, `qualifier_type' is null.
2259         //
2260         // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2261         // the same than `queried_type' - except when we're being called from BaseAccess;
2262         // in this case, `invocation_type' is the current type and `queried_type' the base
2263         // type, so this'd normally trigger a CS1540.
2264         //
2265         // The binding flags are `bf' and the kind of members being looked up are `mt'
2266         //
2267         // The return value always includes private members which code in `invocation_type'
2268         // is allowed to access (using the specified `qualifier_type' if given); only use
2269         // BindingFlags.NonPublic to bypass the permission check.
2270         //
2271         // The 'almost_match' argument is used for reporting error CS1540.
2272         //
2273         // Returns an array of a single element for everything but Methods/Constructors
2274         // that might return multiple matches.
2275         //
2276         public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2277                                                   Type queried_type,  MemberTypes mt,
2278                                                   BindingFlags original_bf, string name, IList almost_match)
2279         {
2280                 Timer.StartTimer (TimerType.MemberLookup);
2281
2282                 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2283                                                         queried_type, mt, original_bf, name, almost_match);
2284
2285                 Timer.StopTimer (TimerType.MemberLookup);
2286
2287                 return retval;
2288         }
2289
2290         static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2291                                                Type queried_type, MemberTypes mt,
2292                                                BindingFlags original_bf, string name, IList almost_match)
2293         {
2294                 BindingFlags bf = original_bf;
2295                 
2296                 ArrayList method_list = null;
2297                 Type current_type = queried_type;
2298                 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2299                 bool skip_iface_check = true, used_cache = false;
2300                 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
2301
2302                 closure.invocation_type = invocation_type;
2303                 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2304                 closure.qualifier_type = qualifier_type;
2305                 closure.almost_match = almost_match;
2306                 
2307                 // This is from the first time we find a method
2308                 // in most cases, we do not actually find a method in the base class
2309                 // so we can just ignore it, and save the arraylist allocation
2310                 MemberInfo [] first_members_list = null;
2311                 bool use_first_members_list = false;
2312                 
2313                 do {
2314                         MemberInfo [] list;
2315
2316                         //
2317                         // `NonPublic' is lame, because it includes both protected and
2318                         // private methods, so we need to control this behavior by
2319                         // explicitly tracking if a private method is ok or not.
2320                         //
2321                         // The possible cases are:
2322                         //    public, private and protected (internal does not come into the
2323                         //    equation)
2324                         //
2325                         if ((invocation_type != null) &&
2326                             ((invocation_type == current_type) ||
2327                              IsNestedChildOf (invocation_type, current_type)) ||
2328                             always_ok_flag)
2329                                 bf = original_bf | BindingFlags.NonPublic;
2330                         else
2331                                 bf = original_bf;
2332
2333                         closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2334
2335                         Timer.StopTimer (TimerType.MemberLookup);
2336
2337                         list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2338
2339                         Timer.StartTimer (TimerType.MemberLookup);
2340
2341                         //
2342                         // When queried for an interface type, the cache will automatically check all
2343                         // inherited members, so we don't need to do this here.  However, this only
2344                         // works if we already used the cache in the first iteration of this loop.
2345                         //
2346                         // If we used the cache in any further iteration, we can still terminate the
2347                         // loop since the cache always looks in all base classes.
2348                         //
2349
2350                         if (used_cache)
2351                                 searching = false;
2352                         else
2353                                 skip_iface_check = false;
2354
2355                         if (current_type == TypeManager.object_type)
2356                                 searching = false;
2357                         else {
2358                                 current_type = current_type.BaseType;
2359                                 
2360                                 //
2361                                 // This happens with interfaces, they have a null
2362                                 // basetype.  Look members up in the Object class.
2363                                 //
2364                                 if (current_type == null) {
2365                                         current_type = TypeManager.object_type;
2366                                         searching = true;
2367                                 }
2368                         }
2369                         
2370                         if (list.Length == 0)
2371                                 continue;
2372
2373                         //
2374                         // Events and types are returned by both `static' and `instance'
2375                         // searches, which means that our above FindMembers will
2376                         // return two copies of the same.
2377                         //
2378                         if (list.Length == 1 && !(list [0] is MethodBase)){
2379                                 return list;
2380                         }
2381
2382                         //
2383                         // Multiple properties: we query those just to find out the indexer
2384                         // name
2385                         //
2386                         if (list [0] is PropertyInfo)
2387                                 return list;
2388
2389                         //
2390                         // We found an event: the cache lookup returns both the event and
2391                         // its private field.
2392                         //
2393                         if (list [0] is EventInfo) {
2394                                 if ((list.Length == 2) && (list [1] is FieldInfo))
2395                                         return new MemberInfo [] { list [0] };
2396
2397                                 // Oooops
2398                                 return null;
2399                         }
2400
2401                         //
2402                         // We found methods, turn the search into "method scan"
2403                         // mode.
2404                         //
2405
2406                         if (first_members_list != null) {
2407                                 if (use_first_members_list) {
2408                                         method_list = CopyNewMethods (method_list, first_members_list);
2409                                         use_first_members_list = false;
2410                                 }
2411                                 
2412                                 method_list = CopyNewMethods (method_list, list);
2413                         } else {
2414                                 first_members_list = list;
2415                                 use_first_members_list = true;
2416                                 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2417                         }
2418                 } while (searching);
2419                 
2420                 if (use_first_members_list) {
2421                         foreach (MemberInfo mi in first_members_list) {
2422                                 if (! (mi is MethodBase)) {
2423                                         method_list = CopyNewMethods (method_list, first_members_list);
2424                                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2425                                 }
2426                         }
2427                         return (MemberInfo []) first_members_list;
2428                 }
2429
2430                 if (method_list != null && method_list.Count > 0)
2431                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2432                 
2433                 //
2434                 // This happens if we already used the cache in the first iteration, in this case
2435                 // the cache already looked in all interfaces.
2436                 //
2437                 if (skip_iface_check)
2438                         return null;
2439
2440                 //
2441                 // Interfaces do not list members they inherit, so we have to
2442                 // scan those.
2443                 // 
2444                 if (!queried_type.IsInterface)
2445                         return null;
2446
2447                 if (queried_type.IsArray)
2448                         queried_type = TypeManager.array_type;
2449                 
2450                 Type [] ifaces = GetInterfaces (queried_type);
2451                 if (ifaces == null)
2452                         return null;
2453                 
2454                 foreach (Type itype in ifaces){
2455                         MemberInfo [] x;
2456
2457                         x = MemberLookup (null, null, itype, mt, bf, name, null);
2458                         if (x != null)
2459                                 return x;
2460                 }
2461                                         
2462                 return null;
2463         }
2464
2465         // Tests whether external method is really special
2466         public static bool IsSpecialMethod (MethodBase mb)
2467         {
2468                 string name = mb.Name;
2469                 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2470                         return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2471
2472                 if (name.StartsWith ("add_"))
2473                         return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2474
2475                 if (name.StartsWith ("remove_"))
2476                         return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2477
2478                 if (name.StartsWith ("op_")){
2479                         foreach (string oname in Unary.oper_names) {
2480                                 if (oname == name)
2481                                         return true;
2482                         }
2483                 
2484                         foreach (string oname in Binary.oper_names) {
2485                                 if (oname == name)
2486                                         return true;
2487                         }
2488                 }
2489                 return false;
2490         }
2491                 
2492 #endregion
2493         
2494 }
2495
2496 /// <summary>
2497 ///   There is exactly one instance of this class per type.
2498 /// </summary>
2499 public sealed class TypeHandle : IMemberContainer {
2500         public readonly IMemberContainer BaseType;
2501
2502         readonly int id = ++next_id;
2503         static int next_id = 0;
2504
2505         static TypeHandle ()
2506         {
2507                 Reset ();
2508         }
2509
2510         /// <summary>
2511         ///   Lookup a TypeHandle instance for the given type.  If the type doesn't have
2512         ///   a TypeHandle yet, a new instance of it is created.  This static method
2513         ///   ensures that we'll only have one TypeHandle instance per type.
2514         /// </summary>
2515         private static TypeHandle GetTypeHandle (Type t)
2516         {
2517                 TypeHandle handle = (TypeHandle) type_hash [t];
2518                 if (handle != null)
2519                         return handle;
2520
2521                 handle = new TypeHandle (t);
2522                 type_hash.Add (t, handle);
2523                 return handle;
2524         }
2525
2526         public static MemberCache GetMemberCache (Type t)
2527         {
2528                 return GetTypeHandle (t).MemberCache;
2529         }
2530         
2531         public static void CleanUp ()
2532         {
2533                 type_hash = null;
2534         }
2535
2536         public static void Reset ()
2537         {
2538                 type_hash = new PtrHashtable ();
2539         }
2540
2541         /// <summary>
2542         ///   Returns the TypeHandle for TypeManager.object_type.
2543         /// </summary>
2544         public static IMemberContainer ObjectType {
2545                 get {
2546                         if (object_type != null)
2547                                 return object_type;
2548
2549                         object_type = GetTypeHandle (TypeManager.object_type);
2550
2551                         return object_type;
2552                 }
2553         }
2554
2555         /// <summary>
2556         ///   Returns the TypeHandle for TypeManager.array_type.
2557         /// </summary>
2558         public static IMemberContainer ArrayType {
2559                 get {
2560                         if (array_type != null)
2561                                 return array_type;
2562
2563                         array_type = GetTypeHandle (TypeManager.array_type);
2564
2565                         return array_type;
2566                 }
2567         }
2568
2569         private static PtrHashtable type_hash;
2570
2571         private static TypeHandle object_type = null;
2572         private static TypeHandle array_type = null;
2573
2574         private Type type;
2575         private bool is_interface;
2576         private MemberCache member_cache;
2577         private MemberCache base_cache;
2578
2579         private TypeHandle (Type type)
2580         {
2581                 this.type = type;
2582                 if (type.BaseType != null) {
2583                         base_cache = TypeManager.LookupMemberCache (type.BaseType);
2584                         BaseType = base_cache.Container;
2585                 } else if (type.IsInterface)
2586                         base_cache = TypeManager.LookupBaseInterfacesCache (type);
2587                 this.is_interface = type.IsInterface;
2588                 this.member_cache = new MemberCache (this);
2589         }
2590
2591         // IMemberContainer methods
2592
2593         public string Name {
2594                 get {
2595                         return type.FullName;
2596                 }
2597         }
2598
2599         public Type Type {
2600                 get {
2601                         return type;
2602                 }
2603         }
2604
2605         public MemberCache BaseCache {
2606                 get {
2607                         return base_cache;
2608                 }
2609         }
2610
2611         public bool IsInterface {
2612                 get {
2613                         return is_interface;
2614                 }
2615         }
2616
2617         public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2618         {
2619                 MemberInfo [] members;
2620                 if (mt == MemberTypes.Event)
2621                         members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2622                 else
2623                         members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2624                                                     null, null);
2625                 Array.Reverse (members);
2626
2627                 return new MemberList (members);
2628         }
2629
2630         // IMemberFinder methods
2631
2632         public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2633                                        MemberFilter filter, object criteria)
2634         {
2635                 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2636         }
2637
2638         public MemberCache MemberCache {
2639                 get {
2640                         return member_cache;
2641                 }
2642         }
2643
2644         public override string ToString ()
2645         {
2646                 if (BaseType != null)
2647                         return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2648                 else
2649                         return "TypeHandle (" + id + "," + Name + ")";
2650         }
2651 }
2652
2653 }