2002-12-19 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / mcs / typemanager.cs
index f74138768965b0cc147e91f017ac1d236088af72..f6fda8ca320dbd3b11d7622987e266f067667623 100755 (executable)
@@ -9,7 +9,16 @@
 // (C) 2001 Ximian, Inc (http://www.ximian.com)
 //
 //
+
+//
+// We will eventually remove the SIMPLE_SPEEDUP, and should never change 
+// the behavior of the compilation.  This can be removed if we rework
+// the code to get a list of namespaces available.
+//
+#define SIMPLE_SPEEDUP
+
 using System;
+using System.IO;
 using System.Globalization;
 using System.Collections;
 using System.Reflection;
@@ -65,6 +74,7 @@ public class TypeManager {
        static public Type methodimpl_attr_type;
        static public Type marshal_as_attr_type;
        static public Type param_array_type;
+       static public Type guid_attr_type;
        static public Type void_ptr_type;
        static public Type indexer_name_type;
        static public Type exception_type;
@@ -118,6 +128,8 @@ public class TypeManager {
        // These methods are called by code generated by the compiler
        //
        static public MethodInfo string_concat_string_string;
+       static public MethodInfo string_concat_string_string_string;
+       static public MethodInfo string_concat_string_string_string_string;
        static public MethodInfo string_concat_object_object;
        static public MethodInfo string_isinterneted_string;
        static public MethodInfo system_type_get_type_from_handle;
@@ -478,6 +490,8 @@ public class TypeManager {
                return null;
        }
 
+       static Hashtable negative_hits = new Hashtable ();
+       
        //
        // This function is used when you want to avoid the lookups, and want to go
        // directly to the source.  This will use the cache.
@@ -517,6 +531,11 @@ public class TypeManager {
                if (t != null)
                        return t;
 
+#if SIMPLE_SPEEDUP
+               if (negative_hits.Contains (name))
+                       return null;
+#endif
+               
                //
                // Optimization: ComposedCast will work with an existing type, and might already have the
                // full name of the type, so the full system lookup can probably be avoided.
@@ -539,6 +558,13 @@ public class TypeManager {
                                types [name] = t;
                                return t;
                        } 
+
+                       //
+                       // We know that System.Object does not have children, and since its the parent of 
+                       // all the objects, it always gets probbed for inner classes. 
+                       //
+                       if (top_level_type == "System.Object")
+                               return null;
                        
                        string newt = top_level_type + "+" + String.Join ("+", elements, n, count - n);
                        t = LookupTypeDirect (newt);
@@ -546,37 +572,168 @@ public class TypeManager {
                                types [newt] = t;
                        return t;
                }
+
+#if SIMPLE_SPEEDUP
+               negative_hits [name] = true;
+#endif
                return null;
        }
 
+       static Hashtable assemblies_namespaces = new Hashtable ();
+       
        //
        // Returns a list of all namespaces in the assemblies and types loaded.
        //
-       public static Hashtable GetNamespaces ()
+       static Hashtable ExtractAssemblyNamespaces ()
        {
-               Hashtable namespaces = new Hashtable ();
-
                foreach (Assembly a in assemblies){
                        foreach (Type t in a.GetTypes ()){
                                string ns = t.Namespace;
 
-                               if (namespaces.Contains (ns))
+                               if (assemblies_namespaces.Contains (ns))
                                        continue;
-                               namespaces [ns] = ns;
+                               assemblies_namespaces [ns] = ns;
                        }
                }
 
+               return assemblies_namespaces;
+       }
+
+       static Hashtable AddModuleNamespaces (Hashtable h)
+       {
                foreach (ModuleBuilder mb in modules){
                        foreach (Type t in mb.GetTypes ()){
                                string ns = t.Namespace;
 
-                               if (namespaces.Contains (ns))
+                               if (h.Contains (ns))
                                        continue;
-                               namespaces [ns] = ns;
+                               h [ns] = ns;
+                       }
+               }
+               return h;
+       }
+       
+       
+       /// <summary>
+       ///   Returns the list of namespaces that are active for this executable
+       /// </summary>
+       public static Hashtable GetAssemblyNamespaces (string executable_name)
+       {
+               string cache_name = executable_name + ".nsc";
+               Hashtable cached_namespaces = LoadCache (cache_name);
+
+               if (cached_namespaces != null)
+                       assemblies_namespaces = cached_namespaces;
+               else {
+                       Console.WriteLine ("rebuilding namespace cache");
+                       assemblies_namespaces = ExtractAssemblyNamespaces ();
+                       SaveCache (cache_name);
+               }
+
+               return assemblies_namespaces;
+       }
+
+       public static Hashtable GetNamespaces ()
+       {
+               if (assemblies_namespaces == null)
+                       assemblies_namespaces = ExtractAssemblyNamespaces ();
+
+               Hashtable nh = (Hashtable) assemblies_namespaces.Clone ();
+
+               return AddModuleNamespaces (nh);
+       }
+       
+       //
+       // Loads the namespace cache for the given executable name
+       //
+       static Hashtable LoadCache (string cache_file)
+       {
+               if (!File.Exists (cache_file)){
+                       Console.WriteLine ("Cache not found");
+                       return null;
+               }
+               
+
+               Hashtable cached_module_list, cached_namespaces;
+               try {
+                       using (FileStream fs = File.OpenRead (cache_file)){
+                               StreamReader reader = new StreamReader (fs);
+                               
+                               int assembly_count = Int32.Parse (reader.ReadLine ());
+
+                               if (assembly_count != assemblies.Length){
+                                       Console.WriteLine ("Assembly missmatch ({0}, {1})", assembly_count, assemblies.Length);
+                                       return null;
+                               }
+                               
+                               int namespace_count = Int32.Parse (reader.ReadLine ());
+                               
+                               cached_module_list = new Hashtable (assembly_count);
+                               for (int i = 0; i < assembly_count; i++)
+                                       cached_module_list [reader.ReadLine ()] = true;
+
+                               cached_namespaces = new Hashtable (namespace_count);
+                               for (int i = 0; i < namespace_count; i++){
+                                       string s = reader.ReadLine ();
+                                       cached_namespaces [s] = s;
+                               }
+                       }
+
+                       //
+                       // Now, check that the cache is still valid
+                       //
+                       
+                       foreach (Assembly a in assemblies)
+                               if (cached_module_list [a.CodeBase] == null){
+                                       Console.WriteLine ("assembly not found in cache: " + a.CodeBase);
+                                       return null;
+                               }
+
+                       return cached_namespaces;
+               } catch {
+               }
+               return null;
+       }
+
+       static void SaveCache (string cache_file)
+       {
+               try {
+                       using (FileStream fs = File.OpenWrite (cache_file)){
+                               StreamWriter writer = new StreamWriter (fs);
+
+                               writer.WriteLine (assemblies.Length);
+                               writer.WriteLine (assemblies_namespaces.Count);
+
+                               foreach (Assembly a in assemblies)
+                                       writer.WriteLine (a.CodeBase);
+
+                               foreach (DictionaryEntry de in assemblies_namespaces){
+                                       writer.WriteLine ((string) de.Key);
+                               }
+
+                               writer.Flush ();
+                               fs.Flush ();
+                       }
+               } catch (Exception e) {
+                       Console.WriteLine ("Failed: " + e);
+               }
+       }
+       
+       public static void GetAllTypes ()
+       {
+               Hashtable namespaces = new Hashtable ();
+
+               foreach (Assembly a in assemblies){
+                       foreach (Type t in a.GetTypes ()){
+                       }
+               }
+
+               foreach (ModuleBuilder mb in modules){
+                       foreach (Type t in mb.GetTypes ()){
                        }
                }
-               return namespaces;
        }
+
        
        /// <summary>
        ///   Returns the C# name of a type if possible, or the full type name otherwise
@@ -768,6 +925,14 @@ public class TypeManager {
                marshal_as_attr_type  = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
                param_array_type      = CoreLookupType ("System.ParamArrayAttribute");
 
+               //
+               // Temporary while people upgrade their corlibs
+               //
+               //
+               // Change from LookupType to CoreLookupType before release
+               //
+               guid_attr_type        = LookupType ("System.Runtime.InteropServices.GuidAttribute");
+
                unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
 
                void_ptr_type         = CoreLookupType ("System.Void*");
@@ -841,6 +1006,12 @@ public class TypeManager {
                Type [] string_string = { string_type, string_type };
                string_concat_string_string = GetMethod (
                        string_type, "Concat", string_string);
+               Type [] string_string_string = { string_type, string_type, string_type };
+               string_concat_string_string_string = GetMethod (
+                       string_type, "Concat", string_string_string);
+               Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
+               string_concat_string_string_string_string = GetMethod (
+                       string_type, "Concat", string_string_string_string);
 
                Type [] object_object = { object_type, object_type };
                string_concat_object_object = GetMethod (
@@ -1077,6 +1248,21 @@ public class TypeManager {
                        return false;
        }
 
+       //
+       // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
+       // the pieces in the code where we use IsBuiltinType and special case decimal_type.
+       // 
+       public static bool IsCLRType (Type t)
+       {
+               if (t == object_type || t == int32_type || t == uint32_type ||
+                   t == int64_type || t == uint64_type || t == float_type || t == double_type ||
+                   t == char_type || t == short_type || t == bool_type ||
+                   t == sbyte_type || t == byte_type || t == ushort_type)
+                       return true;
+               else
+                       return false;
+       }
+
        public static bool IsDelegateType (Type t)
        {
                if (t.IsSubclassOf (TypeManager.delegate_type))
@@ -1193,6 +1379,38 @@ public class TypeManager {
                }
        }
 
+       static Hashtable attr_to_allowmult;
+
+       public static void RegisterAttributeAllowMultiple (Type attr_type, bool allow)
+       {
+               if (attr_to_allowmult == null)
+                       attr_to_allowmult = new PtrHashtable ();
+
+               if (attr_to_allowmult.Contains (attr_type))
+                       return;
+
+               attr_to_allowmult.Add (attr_type, allow);
+                              
+       }
+
+       public static bool AreMultipleAllowed (Type attr_type)
+       {
+               if (!(attr_type is TypeBuilder)) {
+                       System.Attribute [] attrs = System.Attribute.GetCustomAttributes (attr_type);
+
+                       foreach (System.Attribute tmp in attrs)
+                               if (tmp is AttributeUsageAttribute)
+                                       return ((AttributeUsageAttribute) tmp).AllowMultiple;
+
+                       return false;
+               }
+               
+               if (attr_to_allowmult == null)
+                       return false;
+
+               return (bool) attr_to_allowmult [attr_type];
+       }
+
        static Hashtable builder_to_constant;
 
        public static void RegisterConstant (FieldBuilder fb, Const c)
@@ -1368,7 +1586,7 @@ public class TypeManager {
 
                        return (MethodInfo) pair.Second;
                } else
-                       return ei.GetAddMethod ();
+                       return ei.GetRemoveMethod ();
        }
 
        static Hashtable priv_fields_events;
@@ -1518,11 +1736,13 @@ public class TypeManager {
 
        // This is a custom version of Convert.ChangeType() which works
        // with the TypeBuilder defined types when compiling corlib.
-       public static object ChangeType (object value, Type conversionType)
+       public static object ChangeType (object value, Type conversionType, out bool error)
        {
-               if (!(value is IConvertible))
-                       throw new ArgumentException ();
-
+               if (!(value is IConvertible)){
+                       error = true;
+                       return null;
+               }
+               
                IConvertible convertValue = (IConvertible) value;
                CultureInfo ci = CultureInfo.CurrentCulture;
                NumberFormatInfo provider = ci.NumberFormat;
@@ -1533,6 +1753,7 @@ public class TypeManager {
                // the system type itself.  You cannot use Type.GetTypeCode()
                // on such a type - it'd always return TypeCode.Object.
                //
+               error = false;
                if (conversionType.Equals (typeof (Boolean)))
                        return (object)(convertValue.ToBoolean (provider));
                else if (conversionType.Equals (typeof (Byte)))
@@ -1566,7 +1787,8 @@ public class TypeManager {
                else if (conversionType.Equals (typeof (Object)))
                        return (object)(value);
                else 
-                       throw new InvalidCastException ();
+                       error = true;
+               return null;
        }
 
        //
@@ -1889,7 +2111,7 @@ public class TypeManager {
        //
        static Type     closure_invocation_type;
        static Type     closure_queried_type;
-       static Type     closure_start_type;
+       static Type     closure_qualifier_type;
 
        //
        // The assembly that defines the type is that is calling us
@@ -1908,9 +2130,9 @@ public class TypeManager {
                //
 
                if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
-                               return false;
+                       return false;
 
-               if ((closure_start_type == closure_invocation_type) &&
+               if (((closure_qualifier_type == null) || (closure_qualifier_type == closure_invocation_type)) &&
                    (m.DeclaringType == closure_invocation_type))
                        return true;
 
@@ -1952,6 +2174,13 @@ public class TypeManager {
                                if (!IsSubclassOrNestedChildOf (closure_invocation_type, mb.DeclaringType))
                                        return false;
 
+                               // Although a derived class can access protected members of its base class
+                               // it cannot do so through an instance of the base class (CS1540).
+                               if (!mb.IsStatic && (closure_invocation_type != closure_qualifier_type) &&
+                                   (closure_qualifier_type != null) &&
+                                   closure_invocation_type.IsSubclassOf (closure_qualifier_type))
+                                       return false;
+
                                return true;
                        }
 
@@ -1995,8 +2224,9 @@ public class TypeManager {
 
                                // Although a derived class can access protected members of its base class
                                // it cannot do so through an instance of the base class (CS1540).
-                               if ((closure_invocation_type != closure_start_type) &&
-                                   closure_invocation_type.IsSubclassOf (closure_start_type))
+                               if (!fi.IsStatic && (closure_invocation_type != closure_qualifier_type) &&
+                                   (closure_qualifier_type != null) &&
+                                   closure_invocation_type.IsSubclassOf (closure_qualifier_type))
                                        return false;
 
                                return true;
@@ -2007,7 +2237,8 @@ public class TypeManager {
                }
 
                //
-               // EventInfos and PropertyInfos, return true
+               // EventInfos and PropertyInfos, return true because they lack permission
+               // informaiton, so we need to check later on the methods.
                //
                return true;
        }
@@ -2016,42 +2247,62 @@ public class TypeManager {
 
        //
        // Looks up a member called `name' in the `queried_type'.  This lookup
-       // is done by code that is contained in the definition for `invocation_type'.
+       // is done by code that is contained in the definition for `invocation_type'
+       // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
+       //
+       // `invocation_type' is used to check whether we're allowed to access the requested
+       // member wrt its protection level.
+       //
+       // When called from MemberAccess, `qualifier_type' is the type which is used to access
+       // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
+       // is B and qualifier_type is A).  This is used to do the CS1540 check.
+       //
+       // When resolving a SimpleName, `qualifier_type' is null.
+       //
+       // The `qualifier_type' is used for the CS1540 check; it's normally either null or
+       // the same than `queried_type' - except when we're being called from BaseAccess;
+       // in this case, `invocation_type' is the current type and `queried_type' the base
+       // type, so this'd normally trigger a CS1540.
        //
        // The binding flags are `bf' and the kind of members being looked up are `mt'
        //
+       // The return value always includes private members which code in `invocation_type'
+       // is allowed to access (using the specified `qualifier_type' if given); only use
+       // BindingFlags.NonPublic to bypass the permission check.
+       //
        // Returns an array of a single element for everything but Methods/Constructors
        // that might return multiple matches.
        //
-       public static MemberInfo [] MemberLookup (Type invocation_type, Type queried_type, 
-                                                 MemberTypes mt, BindingFlags original_bf, string name)
+       public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
+                                                 Type queried_type,  MemberTypes mt,
+                                                 BindingFlags original_bf, string name)
        {
                Timer.StartTimer (TimerType.MemberLookup);
 
-               MemberInfo[] retval = RealMemberLookup (invocation_type, queried_type,
-                                                       mt, original_bf, name);
+               MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
+                                                       queried_type, mt, original_bf, name);
 
                Timer.StopTimer (TimerType.MemberLookup);
 
                return retval;
        }
 
-       static MemberInfo [] RealMemberLookup (Type invocation_type, Type queried_type, 
-                                              MemberTypes mt, BindingFlags original_bf, string name)
+       static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
+                                              Type queried_type, MemberTypes mt,
+                                              BindingFlags original_bf, string name)
        {
                BindingFlags bf = original_bf;
                
                ArrayList method_list = null;
                Type current_type = queried_type;
                bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
-               bool private_ok;
-               bool always_ok_flag = false;
                bool skip_iface_check = true, used_cache = false;
+               bool always_ok_flag = false;
 
                closure_name = name;
                closure_invocation_type = invocation_type;
                closure_invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
-               closure_start_type = queried_type;
+               closure_qualifier_type = qualifier_type;
 
                //
                // If we are a nested class, we always have access to our container
@@ -2062,7 +2313,7 @@ public class TypeManager {
                        if (invocation_name.IndexOf ('+') != -1){
                                string container = queried_type.FullName + "+";
                                int container_length = container.Length;
-                               
+
                                if (invocation_name.Length > container_length){
                                        string shared = invocation_name.Substring (0, container_length);
                                
@@ -2084,23 +2335,15 @@ public class TypeManager {
                        //    public, private and protected (internal does not come into the
                        //    equation)
                        //
-                       if (invocation_type != null){
-                               if (invocation_type == current_type){
-                                       private_ok = (bf & BindingFlags.NonPublic) != 0;
-                               } else
-                                       private_ok = always_ok_flag;
-
-                               if (invocation_type.IsSubclassOf (current_type))
-                                       private_ok = true;
-                               
-                               if (private_ok)
-                                       bf = original_bf | BindingFlags.NonPublic;
-                       } else {
-                               private_ok = false;
-                               bf = original_bf & ~BindingFlags.NonPublic;
-                       }
+                       if ((invocation_type != null) &&
+                           ((invocation_type == current_type) ||
+                            IsNestedChildOf (invocation_type, current_type)) ||
+                           always_ok_flag)
+                               bf = original_bf | BindingFlags.NonPublic;
+                       else
+                               bf = original_bf;
 
-                       closure_private_ok = private_ok;
+                       closure_private_ok = (bf & BindingFlags.NonPublic) != 0;
                        closure_queried_type = current_type;
 
                        Timer.StopTimer (TimerType.MemberLookup);
@@ -2191,7 +2434,7 @@ public class TypeManager {
                foreach (Type itype in ifaces){
                        MemberInfo [] x;
 
-                       x = MemberLookup (null, itype, mt, bf, name);
+                       x = MemberLookup (null, null, itype, mt, bf, name);
                        if (x != null)
                                return x;
                }