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