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