2004-06-13 Atsushi Enomoto <atsushi@ximian.com>
[mono.git] / mcs / mcs / typemanager.cs
index 6e008bc32255a75943f6b7dee8032cd22b99f354..53f2a4036bafdfe49d045860be24d1a7470cb3d3 100755 (executable)
@@ -63,12 +63,14 @@ public class TypeManager {
        static public Type ienumerator_type;
        static public Type ienumerable_type;
        static public Type idisposable_type;
+       static public Type iconvertible_type;
        static public Type default_member_type;
        static public Type iasyncresult_type;
        static public Type asynccallback_type;
        static public Type intptr_type;
        static public Type monitor_type;
        static public Type runtime_field_handle_type;
+       static public Type runtime_argument_handle_type;
        static public Type attribute_type;
        static public Type attribute_usage_type;
        static public Type dllimport_type;
@@ -81,9 +83,15 @@ public class TypeManager {
        static public Type indexer_name_type;
        static public Type exception_type;
        static public Type invalid_operation_exception_type;
-       static public object obsolete_attribute_type;
-       static public object conditional_attribute_type;
+       static public Type obsolete_attribute_type;
+       static public Type conditional_attribute_type;
        static public Type in_attribute_type;
+       static public Type cls_compliant_attribute_type;
+       static public Type typed_reference_type;
+       static public Type arg_iterator_type;
+       static public Type mbr_type;
+       static public Type struct_layout_attribute_type;
+       static public Type field_offset_attribute_type;
 
        //
        // An empty array of types
@@ -135,7 +143,10 @@ public class TypeManager {
        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_string_dot_dot_dot;
        static public MethodInfo string_concat_object_object;
+       static public MethodInfo string_concat_object_object_object;
+       static public MethodInfo string_concat_object_dot_dot_dot;
        static public MethodInfo string_isinterneted_string;
        static public MethodInfo system_type_get_type_from_handle;
        static public MethodInfo object_getcurrent_void;
@@ -225,16 +236,16 @@ public class TypeManager {
        static Hashtable method_internal_params;
 
        // <remarks>
-       //  Keeps track of attribute types
+       //  Keeps track of methods
        // </remarks>
 
-       static Hashtable builder_to_attr;
+       static Hashtable builder_to_method;
 
        // <remarks>
-       //  Keeps track of methods
+       //  Contains all public types from referenced assemblies.
+       //  This member is used only if CLS Compliance verification is required.
        // </remarks>
-
-       static Hashtable builder_to_method;
+       public static Hashtable all_imported_types;
 
        struct Signature {
                public string name;
@@ -254,13 +265,11 @@ public class TypeManager {
                method_arguments = null;
                indexer_arguments = null;
                method_internal_params = null;
-               builder_to_attr = null;
                builder_to_method = null;
                
                fields = null;
                references = null;
                negative_hits = null;
-               attr_to_allowmult = null;
                builder_to_constant = null;
                fieldbuilders_to_fields = null;
                events = null;
@@ -350,7 +359,6 @@ public class TypeManager {
                typecontainers = new Hashtable ();
                
                builder_to_declspace = new PtrHashtable ();
-               builder_to_attr = new PtrHashtable ();
                builder_to_method = new PtrHashtable ();
                method_arguments = new PtrHashtable ();
                method_internal_params = new PtrHashtable ();
@@ -449,14 +457,15 @@ public class TypeManager {
                builder_to_declspace.Add (t, i);
        }
 
-       public static void AddMethod (MethodBuilder builder, MethodData method)
+
+       public static void AddMethod (MethodBase builder, IMethodData method)
        {
                builder_to_method.Add (builder, method);
        }
 
-       public static void RegisterAttrType (Type t, TypeContainer tc)
+       public static IMethodData GetMethod (MethodBase builder)
        {
-               builder_to_attr.Add (t, tc);
+               return (IMethodData) builder_to_method [builder];
        }
 
        /// <summary>
@@ -502,10 +511,10 @@ public class TypeManager {
        {
                return builder_to_declspace [t] as Enum;
        }
-       
-       public static TypeContainer LookupAttr (Type t)
+
+       public static Class LookupClass (Type t)
        {
-               return (TypeContainer) builder_to_attr [t];
+               return (Class) builder_to_declspace [t];
        }
        
        /// <summary>
@@ -513,6 +522,11 @@ public class TypeManager {
        /// </summary>
        public static void AddAssembly (Assembly a)
        {
+               foreach (Assembly assembly in assemblies) {
+                       if (a == assembly)
+                               return;
+               }
+
                int top = assemblies.Length;
                Assembly [] n = new Assembly [top + 1];
 
@@ -522,6 +536,11 @@ public class TypeManager {
                assemblies = n;
        }
 
+        public static Assembly [] GetAssemblies ()
+        {
+                return assemblies;
+        }
+
        /// <summary>
        ///  Registers a module builder to lookup types from
        /// </summary>
@@ -536,6 +555,12 @@ public class TypeManager {
                modules = n;
        }
 
+       public static Module[] Modules {
+               get {
+                       return modules;
+               }
+       }
+
        static Hashtable references = new Hashtable ();
        
        //
@@ -554,7 +579,7 @@ public class TypeManager {
                //
                if (ret == null){
                        if (references [t] == null)
-                               references [t] = CodeGen.ModuleBuilder.GetType (tname);
+                               references [t] = CodeGen.Module.Builder.GetType (tname);
                        ret = (Type) references [t];
                }
 
@@ -579,7 +604,7 @@ public class TypeManager {
                //
                if (ret == null){
                        if (pointers [t] == null)
-                               pointers [t] = CodeGen.ModuleBuilder.GetType (tname);
+                               pointers [t] = CodeGen.Module.Builder.GetType (tname);
                        
                        ret = (Type) pointers [t];
                }
@@ -645,12 +670,17 @@ public class TypeManager {
                Type t = (Type) types [name];
                if (t != null)
                        return t;
-
+               
+               if (negative_hits.Contains (name))
+                       return null;
+               
                t = LookupTypeReflection (name);
+               
                if (t == null)
-                       return null;
-
-               types [name] = t;
+                       negative_hits [name] = null;
+               else
+                       types [name] = t;
+               
                return t;
        }
        
@@ -745,19 +775,38 @@ public class TypeManager {
                                }
                        }
                } else {
-                       foreach (Assembly a in assemblies){
-                               foreach (Type t in a.GetTypes ()){
+                       Hashtable cache = new Hashtable ();
+                       cache.Add ("", null);
+                       foreach (Assembly a in assemblies) {
+                               foreach (Type t in a.GetExportedTypes ()) {
                                        string ns = t.Namespace;
-
-                                       // t.Namespace returns null for <PrivateImplDetails>
-                                       if (ns == ""|| ns == null)
+                                       if (ns == null || cache.Contains (ns))
                                                continue;
+
                                        Namespace.LookupNamespace (ns, true);
+                                       cache.Add (ns, null);
                                }
                        }
                }
        }
 
+       /// <summary>
+       /// Fills static table with exported types from all referenced assemblies.
+       /// This information is required for CLS Compliance tests.
+       /// </summary>
+       public static void LoadAllImportedTypes ()
+       {
+               if (!CodeGen.Assembly.IsClsCompliant)
+                       return;
+
+               all_imported_types = new Hashtable ();
+               foreach (Assembly a in assemblies) {
+                       foreach (Type t in a.GetExportedTypes ()) {
+                               all_imported_types [t.FullName] = t;
+                       }
+               }
+       }
+
        public static bool NamespaceClash (string name, Location loc)
        {
                if (Namespace.LookupNamespace (name, false) == null)
@@ -797,33 +846,82 @@ public class TypeManager {
        }
 
         /// <summary>
-        ///   Returns the signature of the method
-        /// </summary>
-        static public string CSharpSignature (MethodBase mb)
-        {
-                string sig = "(";
+       ///  Returns the signature of the method with full namespace classification
+       /// </summary>
+       static public string GetFullNameSignature (MemberInfo mi)
+       {
+               return mi.DeclaringType.FullName.Replace ('+', '.') + '.' + mi.Name;
+       }
+
+       static public string GetFullNameSignature (MethodBase mb)
+       {
+               string name = mb.Name;
+               if (name == ".ctor")
+                       name = mb.DeclaringType.Name;
+
+               if (mb.IsSpecialName) {
+                       if (name.StartsWith ("get_") || name.StartsWith ("set_")) {
+                               name = name.Remove (0, 4);
+                       }
+
+                       if (name == "Item")
+                               name = "this";
+               }
+
+               return mb.DeclaringType.FullName.Replace ('+', '.') + '.' + name;
+       }
+
+       /// <summary>
+       ///   Returns the signature of the property and indexer
+       /// </summary>
+       static public string CSharpSignature (PropertyBuilder pb, bool is_indexer) 
+       {
+               if (!is_indexer) {
+                       return GetFullNameSignature (pb);
+               }
+
+               MethodBase mb = pb.GetSetMethod (true) != null ? pb.GetSetMethod (true) : pb.GetGetMethod (true);
+               string signature = GetFullNameSignature (mb);
+               string arg = TypeManager.LookupParametersByBuilder (mb).ParameterDesc (0);
+               return String.Format ("{0}.this[{1}]", signature.Substring (0, signature.LastIndexOf ('.')), arg);
+       }
+
+       /// <summary>
+       ///   Returns the signature of the method
+       /// </summary>
+       static public string CSharpSignature (MethodBase mb)
+       {
+               StringBuilder sig = new StringBuilder ("(");
 
                //
                // FIXME: We should really have a single function to do
                // everything instead of the following 5 line pattern
                //
-                ParameterData iparams = LookupParametersByBuilder (mb);
+               ParameterData iparams = LookupParametersByBuilder (mb);
 
-               if (iparams == null){
-                       ParameterInfo [] pi = mb.GetParameters ();
-                       iparams = new ReflectionParameters (pi);
-               }
+               if (iparams == null)
+                       iparams = new ReflectionParameters (mb);
+
+               // Is property
+               if (mb.IsSpecialName && iparams.Count == 0)
+                       return GetFullNameSignature (mb);
                
-                for (int i = 0; i < iparams.Count; i++) {
-                        if (i > 0) {
-                                sig += ", ";
-                        }
-                        sig += iparams.ParameterDesc(i);
-                }
-                sig += ")";
-
-                return mb.DeclaringType.Name + "." + mb.Name + sig;
-        }
+               for (int i = 0; i < iparams.Count; i++) {
+                       if (i > 0) {
+                               sig.Append (", ");
+                       }
+                       sig.Append (iparams.ParameterDesc (i));
+               }
+               sig.Append (")");
+
+               // Is indexer
+               if (mb.IsSpecialName && iparams.Count == 1) {
+                       sig.Replace ('(', '[');
+                       sig.Replace (')', ']');
+               }
+
+               return GetFullNameSignature (mb) + sig.ToString ();
+       }
 
        /// <summary>
        ///   Looks up a type, and aborts if it is not found.  This is used
@@ -835,7 +933,7 @@ public class TypeManager {
 
                if (t == null){
                        Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
-                       Environment.Exit (0);
+                       Environment.Exit (1);
                }
 
                return t;
@@ -955,6 +1053,7 @@ public class TypeManager {
                type_type     = CoreLookupType ("System.Type");
 
                runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
+               runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
                runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
                default_member_type  = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
                runtime_handle_type  = CoreLookupType ("System.RuntimeTypeHandle");
@@ -964,6 +1063,7 @@ public class TypeManager {
                ienumerable_type     = CoreLookupType ("System.Collections.IEnumerable");
                idisposable_type     = CoreLookupType ("System.IDisposable");
                icloneable_type      = CoreLookupType ("System.ICloneable");
+               iconvertible_type    = CoreLookupType ("System.IConvertible");
                monitor_type         = CoreLookupType ("System.Threading.Monitor");
                intptr_type          = CoreLookupType ("System.IntPtr");
 
@@ -974,6 +1074,9 @@ public class TypeManager {
                marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
                param_array_type     = CoreLookupType ("System.ParamArrayAttribute");
                in_attribute_type    = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
+               typed_reference_type = CoreLookupType ("System.TypedReference");
+               arg_iterator_type    = CoreLookupType ("System.ArgIterator");
+               mbr_type             = CoreLookupType ("System.MarshalByRefObject");
 
                //
                // Sigh. Remove this before the release.  Wonder what versions of Mono
@@ -995,6 +1098,9 @@ public class TypeManager {
                //
                obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
                conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
+               cls_compliant_attribute_type = CoreLookupType ("System.CLSCompliantAttribute");
+               struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices.StructLayoutAttribute");
+               field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices.FieldOffsetAttribute");
 
                //
                // When compiling corlib, store the "real" types here.
@@ -1041,7 +1147,7 @@ public class TypeManager {
                                args [2] = enum_type;
                                args [3] = void_type;
                                
-                               set_corlib_type_builders.Invoke (CodeGen.AssemblyBuilder, args);
+                               set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
                        } else {
                                // Compatibility for an older version of the class libs.
                                set_corlib_type_builders = GetMethod (
@@ -1058,7 +1164,7 @@ public class TypeManager {
                                args [1] = value_type;
                                args [2] = enum_type;
                                
-                               set_corlib_type_builders.Invoke (CodeGen.AssemblyBuilder, args);
+                               set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
                        }
                }
 
@@ -1100,10 +1206,19 @@ public class TypeManager {
                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[] params_string = { TypeManager.LookupType ("System.String[]") };
+               string_concat_string_dot_dot_dot = GetMethod (
+                       string_type, "Concat", params_string);
 
                Type [] object_object = { object_type, object_type };
                string_concat_object_object = GetMethod (
                        string_type, "Concat", object_object);
+               Type [] object_object_object = { object_type, object_type, object_type };
+               string_concat_object_object_object = GetMethod (
+                       string_type, "Concat", object_object_object);
+               Type[] params_object = { TypeManager.LookupType ("System.Object[]") };
+               string_concat_object_dot_dot_dot = GetMethod (
+                       string_type, "Concat", params_object);
 
                Type [] string_ = { string_type };
                string_isinterneted_string = GetMethod (
@@ -1350,6 +1465,11 @@ public class TypeManager {
                        return false;
        }
 
+       public static bool IsBuiltinType (TypeContainer tc)
+       {
+               return IsBuiltinType (tc.TypeBuilder);
+       }
+
        //
        // 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.
@@ -1409,12 +1529,15 @@ public class TypeManager {
                        if (t is TypeBuilder){
                                TypeContainer tc = LookupTypeContainer (t);
 
-                               foreach (Field f in tc.Fields){
-                                       if (f.FieldBuilder.IsStatic)
-                                               continue;
-                                       if (!IsUnmanagedType (f.FieldBuilder.FieldType))
-                                               return false;
-                               }
+                               if (tc.Fields != null){
+                                       foreach (Field f in tc.Fields){
+                                               if (f.FieldBuilder.IsStatic)
+                                                       continue;
+                                               if (!IsUnmanagedType (f.FieldBuilder.FieldType))
+                                                       return false;
+                                       }
+                               } else
+                                       return true;
                        } else {
                                FieldInfo [] fields = t.GetFields ();
 
@@ -1511,39 +1634,6 @@ 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)
@@ -1776,6 +1866,64 @@ public class TypeManager {
                return true;
        }
 
+       public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
+       {
+               Hashtable hash = new Hashtable ();
+               return CheckStructCycles (tc, seen, hash);
+       }
+
+       public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
+                                             Hashtable hash)
+       {
+               if (!(tc is Struct) || IsBuiltinType (tc))
+                       return true;
+
+               //
+               // `seen' contains all types we've already visited.
+               //
+               if (seen.Contains (tc))
+                       return true;
+               seen.Add (tc, null);
+
+               if (tc.Fields == null)
+                       return true;
+
+               foreach (Field field in tc.Fields) {
+                       if (field.FieldBuilder.IsStatic)
+                               continue;
+
+                       Type ftype = field.FieldBuilder.FieldType;
+                       TypeContainer ftc = LookupTypeContainer (ftype);
+                       if (ftc == null)
+                               continue;
+
+                       if (hash.Contains (ftc)) {
+                               Report.Error (523, tc.Location,
+                                             "Struct member `{0}.{1}' of type `{2}' " +
+                                             "causes a cycle in the struct layout",
+                                             tc.Name, field.Name, ftc.Name);
+                               return false;
+                       }
+
+                       //
+                       // `hash' contains all types in the current path.
+                       //
+                       hash.Add (tc, null);
+
+                       bool ok = CheckStructCycles (ftc, seen, hash);
+
+                       hash.Remove (tc);
+
+                       if (!ok)
+                               return false;
+
+                       if (!seen.Contains (ftc))
+                               seen.Add (ftc, null);
+               }
+
+               return true;
+       }
+
        /// <summary>
        ///   Given an array of interface types, expand and eliminate repeated ocurrences
        ///   of an interface.  
@@ -1980,15 +2128,15 @@ public class TypeManager {
                if (t is TypeBuilder) {
                        // slow path needed to compile corlib
                        if (t == TypeManager.bool_type ||
-                                       t == TypeManager.byte_type ||
-                                       t == TypeManager.sbyte_type ||
-                                       t == TypeManager.char_type ||
-                                       t == TypeManager.short_type ||
-                                       t == TypeManager.ushort_type ||
-                                       t == TypeManager.int32_type ||
-                                       t == TypeManager.uint32_type ||
-                                       t == TypeManager.int64_type ||
-                                       t == TypeManager.uint64_type)
+                           t == TypeManager.byte_type ||
+                           t == TypeManager.sbyte_type ||
+                           t == TypeManager.char_type ||
+                           t == TypeManager.short_type ||
+                           t == TypeManager.ushort_type ||
+                           t == TypeManager.int32_type ||
+                           t == TypeManager.uint32_type ||
+                           t == TypeManager.int64_type ||
+                           t == TypeManager.uint64_type)
                                return t;
                        throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
                }
@@ -2064,6 +2212,8 @@ public class TypeManager {
                                return TypeManager.object_type;
                        if (t == typeof (System.Type))
                                return TypeManager.type_type;
+                       if (t == typeof (System.IntPtr))
+                               return TypeManager.intptr_type;
                        return t;
                }
        }
@@ -2134,12 +2284,20 @@ public class TypeManager {
                return "Item";
        }
 
+       static MethodInfo pinned_method = null;
        public static void MakePinned (LocalBuilder builder)
        {
-               //
-               // FIXME: Flag the "LocalBuilder" type as being
-               // pinned.  Figure out API.
-               //
+               if (pinned_method == null) {
+                       pinned_method = typeof (LocalBuilder).GetMethod ("MakePinned", BindingFlags.Instance | BindingFlags.NonPublic);
+                       if (pinned_method == null) {
+                               Report.Warning (-24, new Location (-1), "Microsoft.NET does not support making pinned variables." +
+                                       "This code may cause errors on a runtime with a moving GC");
+                               
+                               return;
+                       }
+               }
+               
+               pinned_method.Invoke (builder, null);
        }
 
 
@@ -2209,224 +2367,145 @@ public class TypeManager {
                return target_list;
        }
 
-       [Flags]
-       public enum MethodFlags {
-               IsObsolete = 1,
-               IsObsoleteError = 1 << 1,
-               ShouldIgnore = 1 << 2
-       }
-       
-       //
-       // Returns the TypeManager.MethodFlags for this method.
-       // This emits an error 619 / warning 618 if the method is obsolete.
-       // In the former case, TypeManager.MethodFlags.IsObsoleteError is returned.
-       //
-       static public MethodFlags GetMethodFlags (MethodBase mb, Location loc)
-       {
-               MethodFlags flags = 0;
-               
-               if (mb.DeclaringType is TypeBuilder){
-                       MethodData method = (MethodData) builder_to_method [mb];
-                       if (method == null) {
-                               // FIXME: implement Obsolete attribute on Property,
-                               //        Indexer and Event.
-                               return 0;
-                       }
-
-                       return method.GetMethodFlags (loc);
-               }
-
-               object [] attrs = mb.GetCustomAttributes (true);
-               foreach (object ta in attrs){
-                       if (!(ta is System.Attribute)){
-                               Console.WriteLine ("Unknown type in GetMethodFlags: " + ta);
-                               continue;
-                       }
-                       System.Attribute a = (System.Attribute) ta;
-                       if (a.TypeId == TypeManager.obsolete_attribute_type){
-                               ObsoleteAttribute oa = (ObsoleteAttribute) a;
-
-                               string method_desc = TypeManager.CSharpSignature (mb);
-
-                               if (oa.IsError) {
-                                       Report.Error (619, loc, "Method `" + method_desc +
-                                                     "' is obsolete: `" + oa.Message + "'");
-                                       return MethodFlags.IsObsoleteError;
-                               } else
-                                       Report.Warning (618, loc, "Method `" + method_desc +
-                                                       "' is obsolete: `" + oa.Message + "'");
-
-                               flags |= MethodFlags.IsObsolete;
-
-                               continue;
-                       }
-                       
-                       //
-                       // Skip over conditional code.
-                       //
-                       if (a.TypeId == TypeManager.conditional_attribute_type){
-                               ConditionalAttribute ca = (ConditionalAttribute) a;
-
-                               if (RootContext.AllDefines [ca.ConditionString] == null)
-                                       flags |= MethodFlags.ShouldIgnore;
-                       }
-               }
 
-               return flags;
-       }
-       
 #region MemberLookup implementation
        
        //
        // Whether we allow private members in the result (since FindMembers
        // uses NonPublic for both protected and private), we need to distinguish.
        //
-       static bool     closure_private_ok;
-
-       //
-       // Who is invoking us and which type is being queried currently.
-       //
-       static Type     closure_invocation_type;
-       static Type     closure_qualifier_type;
-
-       //
-       // The assembly that defines the type is that is calling us
-       //
-       static Assembly closure_invocation_assembly;
 
        static internal bool FilterNone (MemberInfo m, object filter_criteria)
        {
                return true;
        }
-       
-       //
-       // This filter filters by name + whether it is ok to include private
-       // members in the search
-       //
-       static internal bool FilterWithClosure (MemberInfo m, object filter_criteria)
-       {
-               //
-               // Hack: we know that the filter criteria will always be in the `closure'
-               // fields. 
-               //
-
-               if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
-                       return false;
 
-               if (((closure_qualifier_type == null) || (closure_qualifier_type == closure_invocation_type)) &&
-                   (m.DeclaringType == closure_invocation_type))
-                       return true;
+       internal class Closure {
+               internal bool     private_ok;
 
-               //
-               // Ugly: we need to find out the type of `m', and depending
-               // on this, tell whether we accept or not
-               //
-               if (m is MethodBase){
-                       MethodBase mb = (MethodBase) m;
-                       MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
+               // Who is invoking us and which type is being queried currently.
+               internal Type     invocation_type;
+               internal Type     qualifier_type;
 
-                       if (ma == MethodAttributes.Private)
-                               return closure_private_ok || (closure_invocation_type == m.DeclaringType) ||
-                                       IsNestedChildOf (closure_invocation_type, m.DeclaringType);
+               // The assembly that defines the type is that is calling us
+               internal Assembly invocation_assembly;
+               internal IList almost_match;
 
-                       //
-                       // FamAndAssem requires that we not only derivate, but we are on the
-                       // same assembly.  
-                       //
-                       if (ma == MethodAttributes.FamANDAssem){
-                               if (closure_invocation_assembly != mb.DeclaringType.Assembly)
-                                       return false;
-                       }
-
-                       // Assembly and FamORAssem succeed if we're in the same assembly.
-                       if ((ma == MethodAttributes.Assembly) || (ma == MethodAttributes.FamORAssem)){
-                               if (closure_invocation_assembly == mb.DeclaringType.Assembly)
-                                       return true;
-                       }
-
-                       // We already know that we aren't in the same assembly.
-                       if (ma == MethodAttributes.Assembly)
+               private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
+               {
+                       if (invocation_type == null)
                                return false;
 
-                       // Family and FamANDAssem require that we derive.
-                       if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem)){
-                               if (closure_invocation_type == null)
-                                       return false;
+                       Debug.Assert (IsSubclassOrNestedChildOf (invocation_type, m.DeclaringType));
 
-                               if (!IsSubclassOrNestedChildOf (closure_invocation_type, mb.DeclaringType))
-                                       return false;
+                       if (is_static)
+                               return true;
+                       
+                       // A nested class has access to all the protected members visible to its parent.
+                       if (qualifier_type != null
+                           && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
+                               return true;
 
+                       if (invocation_type == m.DeclaringType
+                           || invocation_type.IsSubclassOf (m.DeclaringType)) {
                                // 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;
+                               // => Ancestry should be: declaring_type ->* invocation_type ->*  qualified_type
+                               if (qualifier_type == null
+                                   || qualifier_type == invocation_type
+                                   || qualifier_type.IsSubclassOf (invocation_type))
+                                       return true;
                        }
 
-                       // Public.
-                       return true;
+                       if (almost_match != null)
+                               almost_match.Add (m);
+                       return false;
                }
-
-               if (m is FieldInfo){
-                       FieldInfo fi = (FieldInfo) m;
-                       FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
-
-                       if (fa == FieldAttributes.Private)
-                               return closure_private_ok || (closure_invocation_type == m.DeclaringType) ||
-                                       IsNestedChildOf (closure_invocation_type, m.DeclaringType);
-
+               
+               //
+               // This filter filters by name + whether it is ok to include private
+               // members in the search
+               //
+               internal bool Filter (MemberInfo m, object filter_criteria)
+               {
                        //
-                       // FamAndAssem requires that we not only derivate, but we are on the
-                       // same assembly.  
+                       // Hack: we know that the filter criteria will always be in the `closure'
+                       // fields. 
                        //
-                       if (fa == FieldAttributes.FamANDAssem){
-                               if (closure_invocation_assembly != fi.DeclaringType.Assembly)
-                                       return false;
-                       }
-
-                       // Assembly and FamORAssem succeed if we're in the same assembly.
-                       if ((fa == FieldAttributes.Assembly) || (fa == FieldAttributes.FamORAssem)){
-                               if (closure_invocation_assembly == fi.DeclaringType.Assembly)
-                                       return true;
-                       }
 
-                       // We already know that we aren't in the same assembly.
-                       if (fa == FieldAttributes.Assembly)
+                       if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
                                return false;
+                       
+                       if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
+                           (m.DeclaringType == invocation_type))
+                               return true;
+                       
+                       //
+                       // Ugly: we need to find out the type of `m', and depending
+                       // on this, tell whether we accept or not
+                       //
+                       if (m is MethodBase){
+                               MethodBase mb = (MethodBase) m;
+                               MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
 
-                       // Family and FamANDAssem require that we derive.
-                       if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem)){
-                               if (closure_invocation_type == null)
-                                       return false;
-
-                               if (!IsSubclassOrNestedChildOf (closure_invocation_type, fi.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 (!fi.IsStatic && (closure_invocation_type != closure_qualifier_type) &&
-                                   (closure_qualifier_type != null) &&
-                                   closure_invocation_type.IsSubclassOf (closure_qualifier_type))
-                                       return false;
-
+                               if (ma == MethodAttributes.Private)
+                                       return private_ok || (invocation_type == m.DeclaringType) ||
+                                               IsNestedChildOf (invocation_type, m.DeclaringType);
+                               
+                               // Assembly succeeds if we're in the same assembly.
+                               if (ma == MethodAttributes.Assembly)
+                                       return (invocation_assembly == mb.DeclaringType.Assembly);
+                               
+                               // FamAndAssem requires that we not only derive, but we are on the same assembly.  
+                               if (ma == MethodAttributes.FamANDAssem){
+                                       if (invocation_assembly != mb.DeclaringType.Assembly)
+                                               return false;
+                               }
+                               
+                               // Family and FamANDAssem require that we derive.
+                               if ((ma == MethodAttributes.Family) || (ma == MethodAttributes.FamANDAssem))
+                                       return CheckValidFamilyAccess (mb.IsStatic, m);
+                               
+                               // Public.
                                return true;
                        }
-
-                       // Public.
+                       
+                       if (m is FieldInfo){
+                               FieldInfo fi = (FieldInfo) m;
+                               FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
+                               
+                               if (fa == FieldAttributes.Private)
+                                       return private_ok || (invocation_type == m.DeclaringType) ||
+                                               IsNestedChildOf (invocation_type, m.DeclaringType);
+                               
+                               // Assembly succeeds if we're in the same assembly.
+                               if (fa == FieldAttributes.Assembly)
+                                       return (invocation_assembly == fi.DeclaringType.Assembly);
+                                               
+                               // FamAndAssem requires that we not only derive, but we are on the same assembly.  
+                               if (fa == FieldAttributes.FamANDAssem){
+                                       if (invocation_assembly != fi.DeclaringType.Assembly)
+                                               return false;
+                               }
+                               
+                               // Family and FamANDAssem require that we derive.
+                               if ((fa == FieldAttributes.Family) || (fa == FieldAttributes.FamANDAssem))
+                                       return CheckValidFamilyAccess (fi.IsStatic, m);
+                               
+                               // Public.
+                               return true;
+                       }
+                       
+                       //
+                       // EventInfos and PropertyInfos, return true because they lack permission
+                       // information, so we need to check later on the methods.
+                       //
                        return true;
                }
-
-               //
-               // EventInfos and PropertyInfos, return true because they lack permission
-               // informaiton, so we need to check later on the methods.
-               //
-               return true;
        }
 
-       static MemberFilter FilterWithClosure_delegate = new MemberFilter (FilterWithClosure);
+       static Closure closure = new Closure ();
+       static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
        static MemberFilter FilterNone_delegate = new MemberFilter (FilterNone);
 
        //
@@ -2454,17 +2533,19 @@ public class TypeManager {
        // is allowed to access (using the specified `qualifier_type' if given); only use
        // BindingFlags.NonPublic to bypass the permission check.
        //
+       // The 'almost_match' argument is used for reporting error CS1540.
+       //
        // 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 qualifier_type,
                                                  Type queried_type,  MemberTypes mt,
-                                                 BindingFlags original_bf, string name)
+                                                 BindingFlags original_bf, string name, IList almost_match)
        {
                Timer.StartTimer (TimerType.MemberLookup);
 
                MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
-                                                       queried_type, mt, original_bf, name);
+                                                       queried_type, mt, original_bf, name, almost_match);
 
                Timer.StopTimer (TimerType.MemberLookup);
 
@@ -2473,7 +2554,7 @@ public class TypeManager {
 
        static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
                                               Type queried_type, MemberTypes mt,
-                                              BindingFlags original_bf, string name)
+                                              BindingFlags original_bf, string name, IList almost_match)
        {
                BindingFlags bf = original_bf;
                
@@ -2483,9 +2564,10 @@ public class TypeManager {
                bool skip_iface_check = true, used_cache = false;
                bool always_ok_flag = false;
 
-               closure_invocation_type = invocation_type;
-               closure_invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
-               closure_qualifier_type = qualifier_type;
+               closure.invocation_type = invocation_type;
+               closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
+               closure.qualifier_type = qualifier_type;
+               closure.almost_match = almost_match;
 
                //
                // If we are a nested class, we always have access to our container
@@ -2509,7 +2591,7 @@ public class TypeManager {
                // This is from the first time we find a method
                // in most cases, we do not actually find a method in the base class
                // so we can just ignore it, and save the arraylist allocation
-               MemberInfo [] first_methods_list = null;
+               MemberInfo [] first_members_list = null;
                bool use_first_members_list = false;
                
                do {
@@ -2532,7 +2614,7 @@ public class TypeManager {
                        else
                                bf = original_bf;
 
-                       closure_private_ok = (original_bf & BindingFlags.NonPublic) != 0;
+                       closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
 
                        Timer.StopTimer (TimerType.MemberLookup);
 
@@ -2603,23 +2685,29 @@ public class TypeManager {
                        // mode.
                        //
 
-                       if (first_methods_list != null) {
+                       if (first_members_list != null) {
                                if (use_first_members_list) {
-                                       method_list = CopyNewMethods (method_list, first_methods_list);
+                                       method_list = CopyNewMethods (method_list, first_members_list);
                                        use_first_members_list = false;
                                }
                                
                                method_list = CopyNewMethods (method_list, list);
                        } else {
-                               first_methods_list = list;
+                               first_members_list = list;
                                use_first_members_list = true;
+                               mt &= (MemberTypes.Method | MemberTypes.Constructor);
                        }
-                       
-                       mt &= (MemberTypes.Method | MemberTypes.Constructor);
                } while (searching);
                
-               if (use_first_members_list)
-                       return first_methods_list;
+               if (use_first_members_list) {
+                       foreach (MemberInfo mi in first_members_list) {
+                               if (! (mi is MethodBase)) {
+                                       method_list = CopyNewMethods (method_list, first_members_list);
+                                       return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
+                               }
+                       }
+                       return (MemberInfo []) first_members_list;
+               }
 
                if (method_list != null && method_list.Count > 0)
                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
@@ -2648,7 +2736,7 @@ public class TypeManager {
                foreach (TypeExpr itype in ifaces){
                        MemberInfo [] x;
 
-                       x = MemberLookup (null, null, itype.Type, mt, bf, name);
+                       x = MemberLookup (null, null, itype.Type, mt, bf, name, null);
                        if (x != null)
                                return x;
                }