* cs-parser.jay (GetTokenName): Mark GENERATE_COMPLETION and COMPLETE_COMPLETION...
[mono.git] / mcs / mcs / typemanager.cs
index 1d3921cbf36f61d9b406174110952a31e7aafd73..055c2f5e03859d098f007ad15b23a4df4ee8acbe 100644 (file)
@@ -5,10 +5,10 @@
 //         Ravi Pratap     (ravi@ximian.com)
 //         Marek Safar     (marek.safar@seznam.cz)
 //
-// Licensed under the terms of the GNU GPL
-//
-// (C) 2001 Ximian, Inc (http://www.ximian.com)
+// Dual licensed under the terms of the MIT X11 or GNU GPL
 //
+// Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2008 Novell, Inc.
 //
 
 //
@@ -25,7 +25,6 @@ using System.Collections;
 using System.Reflection;
 using System.Reflection.Emit;
 using System.Text;
-using System.Text.RegularExpressions;
 using System.Runtime.CompilerServices;
 using System.Diagnostics;
 
@@ -48,7 +47,6 @@ namespace Mono.CSharp {
        static public Type float_type;
        static public Type double_type;
        static public Type char_type;
-       static public Type char_ptr_type;
        static public Type short_type;
        static public Type decimal_type;
        static public Type bool_type;
@@ -62,67 +60,41 @@ namespace Mono.CSharp {
        static public Type null_type;
        static public Type array_type;
        static public Type runtime_handle_type;
-       static public Type icloneable_type;
        static public Type type_type;
        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 uintptr_type;
-       static public Type monitor_type;
-       static public Type interlocked_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 decimal_constant_attribute_type;
-       static public Type dllimport_type;
-       static public Type unverifiable_code_type;
-       static public Type methodimpl_attr_type;
-       static public Type marshal_as_attr_type;
-       static public Type param_array_type;
        static public Type void_ptr_type;
-       static public Type indexer_name_type;
        static public Type exception_type;
-       static public Type invalid_operation_exception_type;
-       static public Type not_supported_exception_type;
-       static public Type obsolete_attribute_type;
-       static public Type conditional_attribute_type;
-       static public Type in_attribute_type;
-       static public Type out_attribute_type;
-       static public Type extension_attribute_type;
-       static public Type default_parameter_value_attribute_type;
 
        static public Type anonymous_method_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;
-       static public Type security_attr_type;
-       static public Type required_attr_type;
-       static public Type guid_attr_type;
-       static public Type assembly_culture_attribute_type;
-       static public Type assembly_version_attribute_type;
-       static public Type coclass_attr_type;
-       static public Type comimport_attr_type;
-
-       /// 
-       /// .NET 2.0
-       ///
-#if NET_2_0
-       static internal Type runtime_compatibility_attr_type;
-       static internal Type compiler_generated_attr_type;
-       static internal Type fixed_buffer_attr_type;
-       static internal Type default_charset_type;
-       static internal Type internals_visible_attr_type;
-       static internal Type type_forwarder_attr_type;
-#endif
+       public static Type runtime_helpers_type;
+
+       // 
+       // C# 2.0
+       //
+       static internal Type isvolatile_type;
+       static public Type generic_ilist_type;
+       static public Type generic_icollection_type;
+       static public Type generic_ienumerator_type;
+       static public Type generic_ienumerable_type;
+       static public Type generic_nullable_type;
+
+       //
+       // C# 3.0
+       //
+       static internal Type expression_type;
+       public static Type parameter_expression_type;
 
        // 
        // Expressions representing the internal types.  Used during declaration
@@ -136,86 +108,36 @@ namespace Mono.CSharp {
        static public TypeExpr system_int32_expr, system_uint32_expr;
        static public TypeExpr system_int64_expr, system_uint64_expr;
        static public TypeExpr system_char_expr, system_void_expr;
-       static public TypeExpr system_asynccallback_expr;
-       static public TypeExpr system_iasyncresult_expr;
        static public TypeExpr system_valuetype_expr;
        static public TypeExpr system_intptr_expr;
+       public static TypeExpr expression_type_expr;
 
-       //
-       // This is only used when compiling corlib
-       //
-       static public Type system_int32_type;
-       static public Type system_array_type;
-       static public Type system_type_type;
-       static public Type system_assemblybuilder_type;
-       static public MethodInfo system_int_array_get_length;
-       static public MethodInfo system_int_array_get_rank;
-       static public MethodInfo system_object_array_clone;
-       static public MethodInfo system_int_array_get_length_int;
-       static public MethodInfo system_int_array_get_lower_bound_int;
-       static public MethodInfo system_int_array_get_upper_bound_int;
-       static public MethodInfo system_void_array_copyto_array_int;
 
-       
-       //
-       // Internal, not really used outside
-       //
-       static Type runtime_helpers_type;
-       
        //
        // 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_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_isinterned_string;
+       static public FieldInfo string_empty;
        static public MethodInfo system_type_get_type_from_handle;
        static public MethodInfo bool_movenext_void;
-       static public MethodInfo ienumerable_getenumerator_void;
-       static public MethodInfo void_reset_void;
        static public MethodInfo void_dispose_void;
        static public MethodInfo void_monitor_enter_object;
        static public MethodInfo void_monitor_exit_object;
        static public MethodInfo void_initializearray_array_fieldhandle;
-       static public MethodInfo int_getlength_int;
        static public MethodInfo delegate_combine_delegate_delegate;
        static public MethodInfo delegate_remove_delegate_delegate;
-       static public MethodInfo int_get_offset_to_string_data;
-       static public MethodInfo int_array_get_length;
-       static public MethodInfo int_array_get_rank;
-       static public MethodInfo object_array_clone;
-       static public MethodInfo int_array_get_length_int;
-       static public MethodInfo int_array_get_lower_bound_int;
-       static public MethodInfo int_array_get_upper_bound_int;
-       static public MethodInfo void_array_copyto_array_int;
+       static public PropertyInfo int_get_offset_to_string_data;
        static public MethodInfo int_interlocked_compare_exchange;
        static public PropertyInfo ienumerator_getcurrent;
-       
+       public static MethodInfo methodbase_get_type_from_handle;
+       public static MethodInfo methodbase_get_type_from_handle_generic;
+       public static MethodInfo fieldinfo_get_field_from_handle;
+       static public MethodInfo activator_create_instance;
+
        //
-       // The attribute constructors.
+       // The constructors.
        //
-       static public ConstructorInfo object_ctor;
-       static public ConstructorInfo cons_param_array_attribute;
        static public ConstructorInfo void_decimal_ctor_five_args;
        static public ConstructorInfo void_decimal_ctor_int_arg;
-       static public ConstructorInfo unverifiable_code_ctor;
-       static public ConstructorInfo default_member_ctor;
-       static public ConstructorInfo decimal_constant_attribute_ctor;
-       static internal ConstructorInfo struct_layout_attribute_ctor;
-       static public ConstructorInfo field_offset_attribute_ctor;
-       
-#if NET_2_0
-       /// C# 2.0
-       static internal CustomAttributeBuilder compiler_generated_attr;
-       static internal ConstructorInfo fixed_buffer_attr_ctor;
-#endif
-
-       /// C# 3.0
-       static internal CustomAttributeBuilder extension_attribute_attr;
 
        static PtrHashtable builder_to_declspace;
 
@@ -227,12 +149,6 @@ namespace Mono.CSharp {
        // </remarks>
        static PtrHashtable builder_to_ifaces;
 
-       // <remarks>
-       //   Maps PropertyBuilder to a Type array that contains
-       //   the arguments to the indexer
-       // </remarks>
-       static Hashtable indexer_arguments;
-
        // <remarks>
        //   Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
        // <remarks>
@@ -259,16 +175,8 @@ namespace Mono.CSharp {
        static Hashtable propertybuilder_to_property;
        static Hashtable fields;
        static Hashtable events;
-
-#if GMCS_SOURCE
        static PtrHashtable assembly_internals_vis_attrs;
-#endif
 
-       struct Signature {
-               public string name;
-               public Type [] args;
-       }
-       
        public static void CleanUp ()
        {
                // Lets get everything clean so that we can collect before generating code
@@ -276,7 +184,6 @@ namespace Mono.CSharp {
                builder_to_member_cache = null;
                builder_to_ifaces = null;
                builder_to_type_param = null;
-               indexer_arguments = null;
                method_params = null;
                builder_to_method = null;
                
@@ -285,112 +192,85 @@ namespace Mono.CSharp {
                type_hash = null;
                propertybuilder_to_property = null;
 
-#if GMCS_SOURCE
-               assembly_internals_vis_attrs = null;
-#endif
-
                TypeHandle.CleanUp ();
        }
 
-       /// <summary>
-       ///   A filter for Findmembers that uses the Signature object to
-       ///   extract objects
-       /// </summary>
-       static bool SignatureFilter (MemberInfo mi, object criteria)
-       {
-               Signature sig = (Signature) criteria;
-
-               if (!(mi is MethodBase))
-                       return false;
-
-               if (mi.Name != sig.name)
-                       return false;
-
-               int count = sig.args.Length;
-               
-               if (mi is MethodBuilder || mi is ConstructorBuilder){
-                       Type [] candidate_args = GetParameterData ((MethodBase) mi).Types;
-
-                       if (candidate_args.Length != count)
-                               return false;
-                       
-                       for (int i = 0; i < count; i++)
-                               if (candidate_args [i] != sig.args [i])
-                                       return false;
-                       
-                       return true;
-               } else {
-                       ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
-
-                       if (pars.Length != count)
-                               return false;
-
-                       for (int i = 0; i < count; i++)
-                               if (pars [i].ParameterType != sig.args [i])
-                                       return false;
-                       return true;
-               }
-       }
-
-       // A delegate that points to the filter above.
-       static MemberFilter signature_filter;
-
        //
        // These are expressions that represent some of the internal data types, used
        // elsewhere
        //
        static void InitExpressionTypes ()
        {
-               system_object_expr  = new TypeLookupExpression ("System.Object");
-               system_string_expr  = new TypeLookupExpression ("System.String");
-               system_boolean_expr = new TypeLookupExpression ("System.Boolean");
-               system_decimal_expr = new TypeLookupExpression ("System.Decimal");
-               system_single_expr  = new TypeLookupExpression ("System.Single");
-               system_double_expr  = new TypeLookupExpression ("System.Double");
-               system_sbyte_expr   = new TypeLookupExpression ("System.SByte");
-               system_byte_expr    = new TypeLookupExpression ("System.Byte");
-               system_int16_expr   = new TypeLookupExpression ("System.Int16");
-               system_uint16_expr  = new TypeLookupExpression ("System.UInt16");
-               system_int32_expr   = new TypeLookupExpression ("System.Int32");
-               system_uint32_expr  = new TypeLookupExpression ("System.UInt32");
-               system_int64_expr   = new TypeLookupExpression ("System.Int64");
-               system_uint64_expr  = new TypeLookupExpression ("System.UInt64");
-               system_char_expr    = new TypeLookupExpression ("System.Char");
-               system_void_expr    = new TypeLookupExpression ("System.Void");
-               system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
-               system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
-               system_valuetype_expr  = new TypeLookupExpression ("System.ValueType");
-               system_intptr_expr  = new TypeLookupExpression ("System.IntPtr");
+               system_object_expr  = new TypeLookupExpression ("System", "Object");
+               system_string_expr  = new TypeLookupExpression ("System", "String");
+               system_boolean_expr = new TypeLookupExpression ("System", "Boolean");
+               system_decimal_expr = new TypeLookupExpression ("System", "Decimal");
+               system_single_expr  = new TypeLookupExpression ("System", "Single");
+               system_double_expr  = new TypeLookupExpression ("System", "Double");
+               system_sbyte_expr   = new TypeLookupExpression ("System", "SByte");
+               system_byte_expr    = new TypeLookupExpression ("System", "Byte");
+               system_int16_expr   = new TypeLookupExpression ("System", "Int16");
+               system_uint16_expr  = new TypeLookupExpression ("System", "UInt16");
+               system_int32_expr   = new TypeLookupExpression ("System", "Int32");
+               system_uint32_expr  = new TypeLookupExpression ("System", "UInt32");
+               system_int64_expr   = new TypeLookupExpression ("System", "Int64");
+               system_uint64_expr  = new TypeLookupExpression ("System", "UInt64");
+               system_char_expr    = new TypeLookupExpression ("System", "Char");
+               system_void_expr    = new TypeLookupExpression ("System", "Void");
+               system_valuetype_expr  = new TypeLookupExpression ("System", "ValueType");
+               system_intptr_expr  = new TypeLookupExpression ("System", "IntPtr");
        }
 
        static TypeManager ()
        {
                Reset ();
-
-               signature_filter = new MemberFilter (SignatureFilter);
-               InitExpressionTypes ();
        }
 
        static public void Reset ()
        {
+               InitExpressionTypes ();
+               
                builder_to_declspace = new PtrHashtable ();
                builder_to_member_cache = new PtrHashtable ();
                builder_to_method = new PtrHashtable ();
                builder_to_type_param = new PtrHashtable ();
                method_params = new PtrHashtable ();
                method_overrides = new PtrHashtable ();
-               indexer_arguments = new PtrHashtable ();
                builder_to_ifaces = new PtrHashtable ();
                
                fieldbuilders_to_fields = new Hashtable ();
                propertybuilder_to_property = new Hashtable ();
                fields = new Hashtable ();
                type_hash = new DoubleHash ();
-
-#if GMCS_SOURCE
                assembly_internals_vis_attrs = new PtrHashtable ();
-#endif
-
+               iface_cache = new PtrHashtable ();
+               
+               closure = new Closure ();
+               FilterWithClosure_delegate = new MemberFilter (closure.Filter);
+
+               // TODO: I am really bored by all this static stuff
+               system_type_get_type_from_handle =
+               bool_movenext_void =
+               void_dispose_void =
+               void_monitor_enter_object =
+               void_monitor_exit_object =
+               void_initializearray_array_fieldhandle =
+               delegate_combine_delegate_delegate =
+               delegate_remove_delegate_delegate =
+               int_interlocked_compare_exchange =
+               methodbase_get_type_from_handle =
+               methodbase_get_type_from_handle_generic =
+               fieldinfo_get_field_from_handle =
+               activator_create_instance = null;
+
+               int_get_offset_to_string_data =
+               ienumerator_getcurrent = null;
+
+               void_decimal_ctor_five_args =
+               void_decimal_ctor_int_arg = null;
+
+               isvolatile_type = null;
+                       
                // to uncover regressions
                AllClsTopLevelTypes = null;
        }
@@ -440,7 +320,7 @@ namespace Mono.CSharp {
 
        public static MemberCache LookupMemberCache (Type t)
        {
-               if (t.Module == CodeGen.Module.Builder) {
+               if (t.Module == RootContext.ToplevelTypes.Builder) {
                        DeclSpace container = (DeclSpace)builder_to_declspace [t];
                        if (container != null)
                                return container.MemberCache;
@@ -599,7 +479,7 @@ namespace Mono.CSharp {
        public static void LoadAllImportedTypes ()
        {
                AllClsTopLevelTypes = new Hashtable (1500);
-               foreach (Assembly a in RootNamespace.Global.Assemblies) {
+               foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
                        foreach (Type t in a.GetExportedTypes ()) {
                                AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
                        }
@@ -608,7 +488,7 @@ namespace Mono.CSharp {
 
        public static bool NamespaceClash (string name, Location loc)
        {
-               if (! RootNamespace.Global.IsNamespace (name))
+               if (!GlobalRootNamespace.Instance.IsNamespace (name))
                        return false;
 
                Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
@@ -620,70 +500,87 @@ namespace Mono.CSharp {
        /// </summary>
        static public string CSharpName (Type t)
        {
-               if (t == typeof(NullType))
+               if (t == null_type)
                        return "null";
 
                if (t == typeof (ArglistParameter))
                        return "__arglist";
                        
-               if (t == typeof (AnonymousMethod))
+               if (t == typeof (AnonymousMethodBody))
                        return "anonymous method";
 
-               return CSharpName (GetFullName (t));
-    }
+               if (t == typeof (MethodGroupExpr))
+                       return "method group";
 
-       public static string CSharpName (string name)
-       {
-               if (name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
+               if (t == null)
+                       return "internal error";
+
+               return CSharpName (GetFullName (t), t);
+       }
+
+       static readonly char [] elements = new char [] { '*', '[' };
+
+       public static string CSharpName (string name, Type type)
+       {
+               if (name.Length > 10) {
+                       string s;
+                       switch (name) {
+                       case "System.Int32": s = "int"; break;
+                       case "System.Int64": s = "long"; break;
+                       case "System.String": s = "string"; break;
+                       case "System.Boolean": s = "bool"; break;
+                       case "System.Void": s = "void"; break;
+                       case "System.Object": s = "object"; break;
+                       case "System.UInt32": s = "uint"; break;
+                       case "System.Int16": s = "short"; break;
+                       case "System.UInt16": s = "ushort"; break;
+                       case "System.UInt64": s = "ulong"; break;
+                       case "System.Single": s = "float"; break;
+                       case "System.Double": s = "double"; break;
+                       case "System.Decimal": s = "decimal"; break;
+                       case "System.Char": s = "char"; break;
+                       case "System.Byte": s = "byte"; break;
+                       case "System.SByte": s = "sbyte"; break;
+                       default: s = null; break;
+                       }
+
+                       if (s != null) {
+                               //
+                               // Predefined names can come from mscorlib only
+                               //
+                               if (type == null || type.Module.Name == "mscorlib.dll" || !RootContext.StdLib)
+                                       return s;
+                                       
+                               return name;
+                       }
+
+                       if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
                                return AnonymousTypeClass.SignatureForError;
-                       
-               return Regex.Replace (name,
-                       @"^System\." +
-                       @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
-                       @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
-                       @"Boolean|String|Void|Null)" +
-                       @"(\W+|\b)",
-                       new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
+
+                       int idx = name.IndexOfAny (elements, 10);
+                       if (idx > 0)
+                               return CSharpName (name.Substring (0, idx), type) + name.Substring (idx);
+               }
+
+               return name.Replace ('+', '.');
        }
 
        static public string CSharpName (Type[] types)
        {
+               if (types.Length == 0)
+                       return string.Empty;
+
                StringBuilder sb = new StringBuilder ();
-               foreach (Type t in types) {
-                       sb.Append (CSharpName (t));
-                       sb.Append (',');
+               for (int i = 0; i < types.Length; ++i) {
+                       if (i > 0)
+                               sb.Append (", ");
+
+                       sb.Append (CSharpName (types [i]));
                }
-               sb.Remove (sb.Length - 1, 1);
                return sb.ToString ();
        }
-       
-       static String CSharpNameMatch (Match match) 
-       {
-               string s = match.Groups [1].Captures [0].Value;
-               return s.ToLower ().
-               Replace ("int32", "int").
-               Replace ("uint32", "uint").
-               Replace ("int16", "short").
-               Replace ("uint16", "ushort").
-               Replace ("int64", "long").
-               Replace ("uint64", "ulong").
-               Replace ("single", "float").
-               Replace ("boolean", "bool")
-               + match.Groups [2].Captures [0].Value;
-       }
 
-       // Used for error reporting to show symbolic name instead of underlying value
-       public static string CSharpEnumValue (Type t, object value)
-       {
-               t = DropGenericTypeArguments (t);
-               Enum e = LookupDeclSpace (t) as Enum;
-               if (e == null)
-                       return System.Enum.GetName (t, value);
-
-               return e.GetDefinition (value).GetSignatureForError ();
-       }
-
-        /// <summary>
+       /// <summary>
        ///  Returns the signature of the method with full namespace classification
        /// </summary>
        static public string GetFullNameSignature (MemberInfo mi)
@@ -743,7 +640,7 @@ namespace Mono.CSharp {
        {
                if (t.IsArray) {
                        string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
-                       return GetFullName (t.GetElementType ()) + dimension;
+                       return GetFullName (GetElementType (t)) + dimension;
                }
 
                if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
@@ -793,15 +690,21 @@ namespace Mono.CSharp {
                StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
                sig.Append ('.');
 
-               ParameterData iparams = GetParameterData (mb);
+               AParametersCollection iparams = GetParameterData (mb);
                string parameters = iparams.GetSignatureForError ();
                int accessor_end = 0;
 
                if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
-                       Operator.OpType ot = Operator.GetOperatorType (mb.Name);
-                       if (ot != Operator.OpType.TOP) {
-                               sig.Append ("operator ");
-                               sig.Append (Operator.GetName (ot));
+                       string op_name = Operator.GetName (mb.Name);
+                       if (op_name != null) {
+                               if (op_name == "explicit" || op_name == "implicit") {
+                                       sig.Append (op_name);
+                                       sig.Append (" operator ");
+                                       sig.Append (CSharpName (((MethodInfo)mb).ReturnType));
+                               } else {
+                                       sig.Append ("operator ");
+                                       sig.Append (op_name);
+                               }
                                sig.Append (parameters);
                                return sig.ToString ();
                        }
@@ -831,9 +734,8 @@ namespace Mono.CSharp {
                        else {
                                sig.Append (mb.Name);
 
-#if GMCS_SOURCE
-                               if (TypeManager.IsGenericMethod (mb)) {
-                                       Type[] args = mb.GetGenericArguments ();
+                               if (IsGenericMethod (mb)) {
+                                       Type[] args = GetGenericArguments (mb);
                                        sig.Append ('<');
                                        for (int i = 0; i < args.Length; i++) {
                                                if (i > 0)
@@ -842,7 +744,6 @@ namespace Mono.CSharp {
                                        }
                                        sig.Append ('>');
                                }
-#endif
                        }
 
                        sig.Append (parameters);
@@ -858,14 +759,10 @@ namespace Mono.CSharp {
 
        public static string GetMethodName (MethodInfo m)
        {
-#if GMCS_SOURCE
                if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
                        return m.Name;
 
-               return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
-#else
-               return m.Name;
-#endif
+               return MemberName.MakeName (m.Name, TypeManager.GetGenericArguments (m).Length);
        }
 
        static public string CSharpSignature (EventInfo ei)
@@ -873,523 +770,275 @@ namespace Mono.CSharp {
                return CSharpName (ei.DeclaringType) + "." + ei.Name;
        }
 
-       /// <summary>
-       ///   Looks up a type, and aborts if it is not found.  This is used
-       ///   by types required by the compiler
-       /// </summary>
-       public static Type CoreLookupType (string namespaceName, string name)
+       //
+       // Looks up a type, and aborts if it is not found.  This is used
+       // by predefined types required by the compiler
+       //
+       public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
        {
-               return CoreLookupType (namespaceName, name, false);
-       }
+               Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, true);
+               Expression expr = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
 
-       static Type CoreLookupType (string ns_name, string name, bool mayFail)
-       {
-               Namespace ns = RootNamespace.Global.GetNamespace (ns_name, true);
-               FullNamedExpression fne = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
-               Type t = fne == null ? null : fne.Type;
-               if (t == null) {
-                       if (!mayFail)
-                               Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
+               if (expr == null) {
+                       if (required) {
+                               Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
+                                       ns_name, name);
+                       }
                        return null;
                }
 
-               AttributeTester.RegisterNonObsoleteType (t);
-               return t;
-       }
-
-       /// <summary>
-       ///   Returns the MethodInfo for a method named `name' defined
-       ///   in type `t' which takes arguments of types `args'
-       /// </summary>
-       static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
-       {
-               MemberList list;
-               Signature sig;
-               BindingFlags flags = instance_and_static | BindingFlags.Public;
-
-               sig.name = name;
-               sig.args = args;
-
-               if (is_private)
-                       flags |= BindingFlags.NonPublic;
+               Type t = expr.Type;
+               if (RootContext.StdLib || t == null || !required)
+                       return t;
 
-               list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
-               if (list.Count == 0) {
-                       if (report_errors)
-                               Report.Error (-19, "Can not find the core function `" + name + "'");
-                       return null;
-               }
+               // TODO: All predefined imported types have to have correct signature
+               if (t.Module != RootContext.ToplevelTypes.Builder)
+                       return t;
 
-               MethodInfo mi = list [0] as MethodInfo;
-               if (mi == null) {
-                       if (report_errors)
-                               Report.Error (-19, "Can not find the core function `" + name + "'");
-                       return null;
+               DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
+               if (ds is Delegate) {
+                       if (type_kind == Kind.Delegate)
+                               return t;
+               } else {
+                       TypeContainer tc = (TypeContainer)ds;
+                       if (tc.Kind == type_kind)
+                               return t;
                }
 
-               return mi;
-       }
-
-       static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
-       {
-               return GetMethod (t, name, args, false, report_errors);
+               Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
+                       ns_name, name);
+               return null;
        }
 
-       public static MethodInfo GetMethod (Type t, string name, Type [] args)
+       static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
        {
-               return GetMethod (t, name, args, true);
-       }
+               const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
 
-       /// <summary>
-       ///   Returns the PropertyInfo for a property named `name' defined
-       ///   in type `t'
-       /// </summary>
-       public static PropertyInfo GetProperty (Type t, string name)
-       {
-               MemberList list = FindMembers (t, MemberTypes.Property, BindingFlags.Public |
-                                              BindingFlags.Instance, Type.FilterName, name);
-               if (list.Count == 0) {
-                       Report.Error (-19, "Can not find the core property `" + name + "'");
-                       return null;
-               }
+               MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
+               if (members != null) {
+                       for (int i = 0; i < members.Length; ++i) {
+                               MemberInfo member = members [i];
+                               if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
+                                       MethodBase mb = member as MethodBase;
+                                       if (mb == null)
+                                               continue;
 
-               PropertyInfo pi = list [0] as PropertyInfo;
-               if (pi == null) {
-                       Report.Error (-19, "Can not find the core function `" + name + "'");
-                       return null;
-               }
+                                       AParametersCollection pd = TypeManager.GetParameterData (mb);
+                                       if (IsEqual (pd.Types, args))
+                                               return member;
+                               }
+                               if (mt == MemberTypes.Field) {
+                                       FieldInfo fi = member as FieldInfo;
+                                       if (fi == null)
+                                               continue;
 
-               return pi;
-       }
+                                       if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
+                                               continue;
 
-       /// <summary>
-       ///    Returns the ConstructorInfo for "args"
-       /// </summary>
-       public static ConstructorInfo GetConstructor (Type t, Type [] args)
-       {
-               return GetConstructor (t, args, true);
-       }
+                                       return member;
+                               }
 
-       public static ConstructorInfo GetConstructor (Type t, Type [] args, bool report_errors)
-       {
-               MemberList list;
-               Signature sig;
+                               if (mt == MemberTypes.Property) {
+                                       PropertyInfo pi = member as PropertyInfo;
+                                       if (pi == null)
+                                               continue;
 
-               sig.name = ".ctor";
-               sig.args = args;
+                                       if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
+                                               continue;
 
-               if (t == null)
-                       throw new InternalErrorException ("Core types haven't been initialized yet?");
-               
-               list = FindMembers (t, MemberTypes.Constructor,
-                                   instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
-                                   signature_filter, sig);
-               if (list.Count == 0){
-                       if (report_errors)
-                               Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
-                       return null;
+                                       return member;
+                               }
+                       }
                }
 
-               ConstructorInfo ci = list [0] as ConstructorInfo;
-               if (ci == null){
-                       if (report_errors)
-                               Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
-                       return null;
-               }
+               string method_args = null;
+               if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
+                       method_args = "(" + TypeManager.CSharpName (args) + ")";
+
+               Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
+                       TypeManager.CSharpName (t), name, method_args);
 
-               return ci;
+               return null;
        }
 
-       public static void InitEnumUnderlyingTypes ()
+       //
+       // Returns the ConstructorInfo for "args"
+       //
+       public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
        {
-               int32_type    = CoreLookupType ("System", "Int32");
-               int64_type    = CoreLookupType ("System", "Int64");
-               uint32_type   = CoreLookupType ("System", "UInt32"); 
-               uint64_type   = CoreLookupType ("System", "UInt64"); 
-               byte_type     = CoreLookupType ("System", "Byte");
-               sbyte_type    = CoreLookupType ("System", "SByte");
-               short_type    = CoreLookupType ("System", "Int16");
-               ushort_type   = CoreLookupType ("System", "UInt16");
+               return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
+       }
 
-               ienumerator_type     = CoreLookupType ("System.Collections", "IEnumerator");
-               ienumerable_type     = CoreLookupType ("System.Collections", "IEnumerable");
+       //
+       // Returns the MethodInfo for a method named `name' defined
+       // in type `t' which takes arguments of types `args'
+       //
+       public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
+       {
+               return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
+       }
 
-               idisposable_type     = CoreLookupType ("System", "IDisposable");
+       public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
+       {
+               return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
+       }
 
-#if GMCS_SOURCE
-               InitGenericCoreTypes ();
-#endif
+       public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
+       {
+               return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
        }
-       
+
        /// <remarks>
        ///   The types have to be initialized after the initial
        ///   population of the type has happened (for example, to
        ///   bootstrap the corlib.dll
        /// </remarks>
-       public static void InitCoreTypes ()
+       public static bool InitCoreTypes ()
        {
-               object_type   = CoreLookupType ("System", "Object");
+               object_type   = CoreLookupType ("System", "Object", Kind.Class, true);
                system_object_expr.Type = object_type;
-               value_type    = CoreLookupType ("System", "ValueType");
+               value_type    = CoreLookupType ("System", "ValueType", Kind.Class, true);
                system_valuetype_expr.Type = value_type;
+               attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
 
-               InitEnumUnderlyingTypes ();
-
-               char_type     = CoreLookupType ("System", "Char");
-               string_type   = CoreLookupType ("System", "String");
-               float_type    = CoreLookupType ("System", "Single");
-               double_type   = CoreLookupType ("System", "Double");
-               char_ptr_type = GetPointerType (char_type);
-               decimal_type  = CoreLookupType ("System", "Decimal");
-               bool_type     = CoreLookupType ("System", "Boolean");
-               enum_type     = CoreLookupType ("System", "Enum");
-
-               multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate");
-               delegate_type           = CoreLookupType ("System", "Delegate");
-
-               array_type    = CoreLookupType ("System", "Array");
-               void_type     = CoreLookupType ("System", "Void");
-               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");
-               asynccallback_type   = CoreLookupType ("System", "AsyncCallback");
-               iasyncresult_type    = CoreLookupType ("System", "IAsyncResult");
-               icloneable_type      = CoreLookupType ("System", "ICloneable");
-               iconvertible_type    = CoreLookupType ("System", "IConvertible");
-               interlocked_type     = CoreLookupType ("System.Threading", "Interlocked");
-               monitor_type         = CoreLookupType ("System.Threading", "Monitor");
-               intptr_type          = CoreLookupType ("System", "IntPtr");
-               uintptr_type         = CoreLookupType ("System", "UIntPtr");
-
-               attribute_type       = CoreLookupType ("System", "Attribute");
-               attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute");
-               dllimport_type       = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute");
-               methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute");
-               marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute");
-               param_array_type     = CoreLookupType ("System", "ParamArrayAttribute");
-               in_attribute_type    = CoreLookupType ("System.Runtime.InteropServices", "InAttribute");
-               out_attribute_type   = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute");
-#if NET_2_0
-               // needed before any call susceptible to fail, as it is used during resolution
-               internals_visible_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
-
-               // this can fail if the user doesn't have an -r:System.dll
-               default_parameter_value_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultParameterValueAttribute", true);
-#endif
-               typed_reference_type = CoreLookupType ("System", "TypedReference");
-               arg_iterator_type    = CoreLookupType ("System", "ArgIterator", true);
-               mbr_type             = CoreLookupType ("System", "MarshalByRefObject");
-               decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute");
-
-               unverifiable_code_type= CoreLookupType ("System.Security", "UnverifiableCodeAttribute");
-
-               void_ptr_type         = GetPointerType (void_type);
-
-               indexer_name_type     = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute");
-
-               exception_type        = CoreLookupType ("System", "Exception");
-               invalid_operation_exception_type = CoreLookupType ("System", "InvalidOperationException");
-               not_supported_exception_type = CoreLookupType ("System", "NotSupportedException");
-
-               //
-               // Attribute types
-               //
-               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");
-               security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute");
-               required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute", true);
-               guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute");
-               assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute");
-               assembly_version_attribute_type = CoreLookupType ("System.Reflection", "AssemblyVersionAttribute");
-               comimport_attr_type = CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute");
-               coclass_attr_type = CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute");
-
-               //
-               // .NET 2.0
-               //
-#if NET_2_0
-               compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
-               fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute");
-               default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute");
-               runtime_compatibility_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
-               type_forwarder_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "TypeForwardedToAttribute", true);
-
-               //
-               // C# 3.0
-               //
-               extension_attribute_type = CoreLookupType("System.Runtime.CompilerServices", "ExtensionAttribute", true);
-#endif
+               int32_type    = CoreLookupType ("System", "Int32", Kind.Struct, true);
+               system_int32_expr.Type = int32_type;
+               int64_type    = CoreLookupType ("System", "Int64", Kind.Struct, true);
+               system_int64_expr.Type = int64_type;
+               uint32_type   = CoreLookupType ("System", "UInt32", Kind.Struct, true);
+               system_uint32_expr.Type = uint32_type;
+               uint64_type   = CoreLookupType ("System", "UInt64", Kind.Struct, true);
+               system_uint64_expr.Type = uint64_type;
+               byte_type     = CoreLookupType ("System", "Byte", Kind.Struct, true);
+               system_byte_expr.Type = byte_type;
+               sbyte_type    = CoreLookupType ("System", "SByte", Kind.Struct, true);
+               system_sbyte_expr.Type = sbyte_type;
+               short_type    = CoreLookupType ("System", "Int16", Kind.Struct, true);
+               system_int16_expr.Type = short_type;
+               ushort_type   = CoreLookupType ("System", "UInt16", Kind.Struct, true);
+               system_uint16_expr.Type = ushort_type;
 
-               //
-               // When compiling corlib, store the "real" types here.
-               //
-               if (!RootContext.StdLib) {
-                       system_int32_type = typeof (System.Int32);
-                       system_array_type = typeof (System.Array);
-                       system_type_type = typeof (System.Type);
-                       system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
-
-                       system_int_array_get_length = GetMethod (
-                               system_array_type, "get_Length", Type.EmptyTypes);
-                       system_int_array_get_rank = GetMethod (
-                               system_array_type, "get_Rank", Type.EmptyTypes);
-                       system_object_array_clone = GetMethod (
-                               system_array_type, "Clone", Type.EmptyTypes);
-
-                       Type [] system_int_arg = { system_int32_type };
-                       system_int_array_get_length_int = GetMethod (
-                               system_array_type, "GetLength", system_int_arg);
-                       system_int_array_get_upper_bound_int = GetMethod (
-                               system_array_type, "GetUpperBound", system_int_arg);
-                       system_int_array_get_lower_bound_int = GetMethod (
-                               system_array_type, "GetLowerBound", system_int_arg);
-
-                       Type [] system_array_int_arg = { system_array_type, system_int32_type };
-                       system_void_array_copyto_array_int = GetMethod (
-                               system_array_type, "CopyTo", system_array_int_arg);
-
-                       Type [] system_3_type_arg = {
-                               system_type_type, system_type_type, system_type_type };
-                       Type [] system_4_type_arg = {
-                               system_type_type, system_type_type, system_type_type, system_type_type };
-
-                       MethodInfo set_corlib_type_builders = GetMethod (
-                               system_assemblybuilder_type, "SetCorlibTypeBuilders",
-                               system_4_type_arg, true, false);
+               ienumerator_type     = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
+               ienumerable_type     = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
+               idisposable_type     = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
 
-                       if (set_corlib_type_builders != null) {
-                               object[] args = new object [4];
-                               args [0] = object_type;
-                               args [1] = value_type;
-                               args [2] = enum_type;
-                               args [3] = void_type;
-                               
-                               set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
-                       } else {
-                               // Compatibility for an older version of the class libs.
-                               set_corlib_type_builders = GetMethod (
-                                       system_assemblybuilder_type, "SetCorlibTypeBuilders",
-                                       system_3_type_arg, true, true);
-
-                               if (set_corlib_type_builders == null) {
-                                       Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
-                                       return;
-                               }
-
-                               object[] args = new object [3];
-                               args [0] = object_type;
-                               args [1] = value_type;
-                               args [2] = enum_type;
-                               
-                               set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
-                       }
-               }
+               // HACK: DefineType immediately resolves iterators (very wrong)
+               generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
 
+               char_type     = CoreLookupType ("System", "Char", Kind.Struct, true);
+               system_char_expr.Type = char_type;
+               string_type   = CoreLookupType ("System", "String", Kind.Class, true);
                system_string_expr.Type = string_type;
-               system_boolean_expr.Type = bool_type;
-               system_decimal_expr.Type = decimal_type;
+               float_type    = CoreLookupType ("System", "Single", Kind.Struct, true);
                system_single_expr.Type = float_type;
+               double_type   = CoreLookupType ("System", "Double", Kind.Struct, true);
                system_double_expr.Type = double_type;
-               system_sbyte_expr.Type = sbyte_type;
-               system_byte_expr.Type = byte_type;
-               system_int16_expr.Type = short_type;
-               system_uint16_expr.Type = ushort_type;
-               system_int32_expr.Type = int32_type;
-               system_uint32_expr.Type = uint32_type;
-               system_int64_expr.Type = int64_type;
-               system_uint64_expr.Type = uint64_type;
-               system_char_expr.Type = char_type;
+               decimal_type  = CoreLookupType ("System", "Decimal", Kind.Struct, true);
+               system_decimal_expr.Type = decimal_type;
+               bool_type     = CoreLookupType ("System", "Boolean", Kind.Struct, true);
+               system_boolean_expr.Type = bool_type;
+               intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
+               system_intptr_expr.Type = intptr_type;
+               uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
+
+               multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
+               delegate_type           = CoreLookupType ("System", "Delegate", Kind.Class, true);
+
+               enum_type       = CoreLookupType ("System", "Enum", Kind.Class, true);
+               array_type      = CoreLookupType ("System", "Array", Kind.Class, true);
+               void_type       = CoreLookupType ("System", "Void", Kind.Struct, true);
                system_void_expr.Type = void_type;
-               system_asynccallback_expr.Type = asynccallback_type;
-               system_iasyncresult_expr.Type = iasyncresult_type;
+               type_type       = CoreLookupType ("System", "Type", Kind.Class, true);
+               exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
 
-               //
-               // These are only used for compare purposes
-               //
-               anonymous_method_type = typeof (AnonymousMethod);
-               null_type = typeof (NullType);
+               runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
+               runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
+
+               PredefinedAttributes.Get.ParamArray.Resolve (false);
+               PredefinedAttributes.Get.Out.Resolve (false);
+
+               return Report.Errors == 0;
        }
 
        //
-       // The helper methods that are used by the compiler
+       // Initializes optional core types
        //
-       public static void InitCodeHelpers ()
+       public static void InitOptionalCoreTypes ()
        {
                //
-               // Now load the default methods that we use.
-               //
-               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[] params_string = { GetConstructedType (string_type, "[]") };
-               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 = { GetConstructedType (object_type, "[]") };
-               string_concat_object_dot_dot_dot = GetMethod (
-                       string_type, "Concat", params_object);
-
-               Type [] string_ = { string_type };
-               string_isinterned_string = GetMethod (
-                       string_type, "IsInterned", string_);
-               
-               Type [] runtime_type_handle = { runtime_handle_type };
-               system_type_get_type_from_handle = GetMethod (
-                       type_type, "GetTypeFromHandle", runtime_type_handle);
-
-               Type [] delegate_delegate = { delegate_type, delegate_type };
-               delegate_combine_delegate_delegate = GetMethod (
-                               delegate_type, "Combine", delegate_delegate);
-
-               delegate_remove_delegate_delegate = GetMethod (
-                               delegate_type, "Remove", delegate_delegate);
-
-               //
-               // Void arguments
-               //
-               ienumerator_getcurrent = GetProperty (
-                       ienumerator_type, "Current");
-               bool_movenext_void = GetMethod (
-                       ienumerator_type, "MoveNext", Type.EmptyTypes);
-               void_reset_void = GetMethod (
-                       ienumerator_type, "Reset", Type.EmptyTypes);
-               void_dispose_void = GetMethod (
-                       idisposable_type, "Dispose", Type.EmptyTypes);
-               int_get_offset_to_string_data = GetMethod (
-                       runtime_helpers_type, "get_OffsetToStringData", Type.EmptyTypes);
-               int_array_get_length = GetMethod (
-                       array_type, "get_Length", Type.EmptyTypes);
-               int_array_get_rank = GetMethod (
-                       array_type, "get_Rank", Type.EmptyTypes);
-               ienumerable_getenumerator_void = GetMethod (
-                       ienumerable_type, "GetEnumerator", Type.EmptyTypes);
-               
-               //
-               // Int32 arguments
-               //
-               Type [] int_arg = { int32_type };
-               int_array_get_length_int = GetMethod (
-                       array_type, "GetLength", int_arg);
-               int_array_get_upper_bound_int = GetMethod (
-                       array_type, "GetUpperBound", int_arg);
-               int_array_get_lower_bound_int = GetMethod (
-                       array_type, "GetLowerBound", int_arg);
-
-               //
-               // System.Array methods
+               // These are only used for compare purposes
                //
-               object_array_clone = GetMethod (
-                       array_type, "Clone", Type.EmptyTypes);
-               Type [] array_int_arg = { array_type, int32_type };
-               void_array_copyto_array_int = GetMethod (
-                       array_type, "CopyTo", array_int_arg);
+               anonymous_method_type = typeof (AnonymousMethodBody);
+               null_type = typeof (NullLiteral);
                
-               //
-               // object arguments
-               //
-               Type [] object_arg = { object_type };
-               void_monitor_enter_object = GetMethod (
-                       monitor_type, "Enter", object_arg);
-               void_monitor_exit_object = GetMethod (
-                       monitor_type, "Exit", object_arg);
-
-               Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
-               
-               void_initializearray_array_fieldhandle = GetMethod (
-                       runtime_helpers_type, "InitializeArray", array_field_handle_arg);
+               void_ptr_type = GetPointerType (void_type);
 
                //
-               // Array functions
+               // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
+               // types cache with incorrect accessiblity when any of optional types is internal.
                //
-               int_getlength_int = GetMethod (
-                       array_type, "GetLength", int_arg);
+               PredefinedAttributes.Get.Initialize ();
 
-               //
-               // Decimal constructors
-               //
-               Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
-               void_decimal_ctor_five_args = GetConstructor (
-                       decimal_type, dec_arg);
-               
-               void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
+               runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
+               asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
+               iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
+               typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
+               arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
+               mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
 
                //
-               // Attributes
+               // Optional attributes, used for error reporting only
                //
-               unverifiable_code_ctor = GetConstructor (unverifiable_code_type, Type.EmptyTypes);
-               default_member_ctor = GetConstructor (default_member_type, string_);
-               cons_param_array_attribute = GetConstructor (param_array_type, Type.EmptyTypes);
+               //if (PredefinedAttributes.Get.Obsolete.IsDefined) {
+               //    Class c = TypeManager.LookupClass (PredefinedAttributes.Get.Obsolete.Type);
+               //    if (c != null)
+               //        c.Define ();
+               //}
 
-               Type[] short_arg = { short_type };
-               // fails for .net 2.1
-               struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg, false);
-
-               decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
-                       { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
-
-               field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
-                       { int32_type });
-
-               //
-               // System.Threading.CompareExchange
-               //
-               Type[] compare_exchange_types = {
-                       GetReferenceType (int32_type), int32_type, int32_type };
-               int_interlocked_compare_exchange = GetMethod (
-                       interlocked_type, "CompareExchange", compare_exchange_types);
+               generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
+               generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
+               generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
+               generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
 
                //
-               // .NET 2.0 types
+               // Optional types which are used as types and for member lookup
                //
-#if NET_2_0
-               compiler_generated_attr = new CustomAttributeBuilder (
-                       GetConstructor (compiler_generated_attr_type, Type.EmptyTypes), new object[0]);
-
-               Type[] type_int_arg = { type_type, int32_type };
-               fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
+               runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
 
-               // C# 3.0
-               InitSystemCore ();
-#endif
+               // New in .NET 3.5
+               // Note: extension_attribute_type is already loaded
+               expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
 
-               // Object
-               object_ctor = GetConstructor (object_type, Type.EmptyTypes);
-
-#if GMCS_SOURCE
-               InitGenericCodeHelpers ();
-#endif
-       }
+               if (!RootContext.StdLib) {
+                       //
+                       // HACK: When building Mono corlib mcs uses loaded mscorlib which
+                       // has different predefined types and this method sets mscorlib types
+                       // to be same to avoid any type check errors.
+                       //
 
-#if GMCS_SOURCE
-       static void InitSystemCore ()
-       {
-               if (RootContext.Version != LanguageVersion.LINQ)
-                       return;
+                       Type type = typeof (Type);
+                       Type [] system_4_type_arg = { type, type, type, type };
+                               
+                       MethodInfo set_corlib_type_builders = 
+                               typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
+                               "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
+                               system_4_type_arg, null);
 
-               if (extension_attribute_type != null)
-                       extension_attribute_attr = new CustomAttributeBuilder (
-                               GetConstructor (extension_attribute_type, Type.EmptyTypes), new object[0]);
+                       if (set_corlib_type_builders != null) {
+                               object[] args = new object [4];
+                               args [0] = object_type;
+                               args [1] = value_type;
+                               args [2] = enum_type;
+                               args [3] = void_type;
+                               
+                               set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
+                       } else {
+                               Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
+                                       TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
+                                       TypeManager.CSharpName (system_4_type_arg));
+                       }
+               }
        }
-#endif
 
        const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
 
@@ -1508,6 +1157,17 @@ namespace Mono.CSharp {
                                        mt, bf, name, FilterWithClosure_delegate, null);
                        }
 
+                       //
+                       // We have to take care of arrays specially, because GetType on
+                       // a TypeBuilder array will return a Type, not a TypeBuilder,
+                       // and we can not call FindMembers on this type.
+                       //
+                       if (t.IsArray) {
+                               used_cache = true;
+                               return TypeHandle.ArrayType.MemberCache.FindMembers (
+                                       mt, bf, name, FilterWithClosure_delegate, null);
+                       }
+
                        if (t.IsGenericType && !t.IsGenericTypeDefinition)
                                t = t.GetGenericTypeDefinition ();
 #else
@@ -1597,11 +1257,6 @@ namespace Mono.CSharp {
                        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.
@@ -1616,29 +1271,20 @@ namespace Mono.CSharp {
 
        public static bool IsDelegateType (Type t)
        {
-#if GMCS_SOURCE
-               if (t.IsGenericParameter)
+               if (TypeManager.IsGenericParameter (t))
                        return false;
-#endif
 
-               t = DropGenericTypeArguments (t);
-               if (t.IsSubclassOf (TypeManager.delegate_type))
-                       return true;
-               else
+               if (t == TypeManager.delegate_type || t == TypeManager.multicast_delegate_type)
                        return false;
+
+               t = DropGenericTypeArguments (t);
+               return IsSubclassOf (t, TypeManager.delegate_type);
        }
        
        public static bool IsEnumType (Type t)
        {
                t = DropGenericTypeArguments (t);
-               if (builder_to_declspace [t] is Enum)
-                       return true;
-
-#if MS_COMPATIBLE && GMCS_SOURCE
-               if (t.IsGenericParameter || t.IsGenericType)
-                       return false;
-#endif
-               return t.IsEnum;
+               return t.BaseType == TypeManager.enum_type;
        }
 
        public static bool IsBuiltinOrEnum (Type t)
@@ -1652,26 +1298,20 @@ namespace Mono.CSharp {
                return false;
        }
 
-       public static bool IsNullType (Type t)
-       {
-               return t == null_type;
-       }
-
        public static bool IsAttributeType (Type t)
        {
                return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
        }
        
-       static Stack unmanaged_enclosing_types = new Stack (4);
-
        //
        // Whether a type is unmanaged.  This is used by the unsafe code (25.2)
        //
+       // mcs4: delete, DeclSpace.IsUnmanagedType is replacement
        public static bool IsUnmanagedType (Type t)
        {
-               // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
-               if (unmanaged_enclosing_types.Contains (t))
-                       return true;
+               DeclSpace ds = TypeManager.LookupDeclSpace (t);
+               if (ds != null)
+                       return ds.IsUnmanagedType ();
 
                // builtins that are not unmanaged types
                if (t == TypeManager.object_type || t == TypeManager.string_type)
@@ -1685,7 +1325,7 @@ namespace Mono.CSharp {
 
                // Someone did the work of checking if the ElementType of t is unmanaged.  Let's not repeat it.
                if (t.IsPointer)
-                       return true;
+                       return IsUnmanagedType (GetElementType (t));
 
                // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
                if (t.IsArray)
@@ -1694,48 +1334,28 @@ namespace Mono.CSharp {
                if (!IsValueType (t))
                        return false;
 
-#if GMCS_SOURCE
                for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
-                       if (p.IsGenericTypeDefinition)
+                       if (IsGenericTypeDefinition (p))
                                return false;
                }
-#endif
-
-               unmanaged_enclosing_types.Push (t);
 
                bool retval = true;
-
-               if (t is TypeBuilder) {
-                       TypeContainer tc = LookupTypeContainer (t);
-                       if (tc.Fields != null){
-                               foreach (FieldBase f in tc.Fields){
-                                       // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
-                                       if ((f.ModFlags & Modifiers.STATIC) != 0)
-                                               continue;
-                                       if (f.MemberType == null)
-                                               continue;
-                                       if (!IsUnmanagedType (f.MemberType)){
-                                               Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
-                                               retval = false;
-                                       }
-                               }
-                       }
-               } else {
+               {
                        FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                        
                        foreach (FieldInfo f in fields){
                                if (!IsUnmanagedType (f.FieldType)){
-                                       Report.SymbolRelatedToPreviousError (f);
                                        retval = false;
                                }
                        }
                }
 
-               unmanaged_enclosing_types.Pop ();
-
                return retval;
        }
-                       
+
+       //
+       // Null is considered to be a reference type
+       //                      
        public static bool IsReferenceType (Type t)
        {
                if (TypeManager.IsGenericParameter (t)) {
@@ -1746,15 +1366,25 @@ namespace Mono.CSharp {
                        return constraints.IsReferenceType;
                }
 
-               if (t == TypeManager.null_type)
-                       return false;
-
-               return !t.IsValueType;
+               return !IsStruct (t) && !IsEnumType (t);
        }                       
                
        public static bool IsValueType (Type t)
        {
-               return t.IsValueType || IsGenericParameter (t);
+               if (TypeManager.IsGenericParameter (t)) {
+                       GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
+                       if (constraints == null)
+                               return false;
+
+                       return constraints.IsValueType;
+               }
+
+               return IsStruct (t) || IsEnumType (t);
+       }
+
+       public static bool IsStruct (Type t)
+       {
+               return t.BaseType == value_type && t != enum_type && t.IsSealed;
        }
        
        public static bool IsInterfaceType (Type t)
@@ -1870,35 +1500,51 @@ namespace Mono.CSharp {
                return false;
        }
 
-#if GMCS_SOURCE
+       public static bool IsSpecialType (Type t)
+       {
+               return t == arg_iterator_type || t == typed_reference_type;
+       }
+
        //
        // Checks whether `extern_type' is friend of the output assembly
        //
-       public static bool IsFriendAssembly (Assembly assembly)
+       public static bool IsThisOrFriendAssembly (Assembly assembly)
        {
-               // FIXME: This should not be reached
                if (assembly == CodeGen.Assembly.Builder)
-                       return false;
+                       return true;
 
                if (assembly_internals_vis_attrs.Contains (assembly))
                        return (bool)(assembly_internals_vis_attrs [assembly]);
+
+               PredefinedAttribute pa = PredefinedAttributes.Get.InternalsVisibleTo;
+               // HACK: Do very early resolve of SRE type checking
+               if (pa.Type == null)
+                       pa.Resolve (true);
+
+               if (!pa.IsDefined)
+                       return false;
                
-               object [] attrs = assembly.GetCustomAttributes (internals_visible_attr_type, false);
+               object [] attrs = assembly.GetCustomAttributes (pa.Type, false);
                if (attrs.Length == 0) {
                        assembly_internals_vis_attrs.Add (assembly, false);
                        return false;
                }
 
+               bool is_friend = false;
+
                AssemblyName this_name = CodeGen.Assembly.Name;
                byte [] this_token = this_name.GetPublicKeyToken ();
-               bool is_friend = false;
                foreach (InternalsVisibleToAttribute attr in attrs) {
                        if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
                                continue;
                        
                        AssemblyName aname = null;
                        try {
+#if GMCS_SOURCE
                                aname = new AssemblyName (attr.AssemblyName);
+#else
+                               throw new NotSupportedException ();
+#endif
                        } catch (FileLoadException) {
                        } catch (ArgumentException) {
                        }
@@ -1937,18 +1583,11 @@ namespace Mono.CSharp {
 
        static void Error_FriendAccessNameNotMatching (string other_name)
        {
-               Report.Error (281, "Friend access was granted to `" + other_name + 
-                               "', but the output assembly is named `" + CodeGen.Assembly.Name.FullName +
-                               "'. Try adding a reference to `" + other_name + 
-                               "' or change the output assembly name to match it");
-       }
-#else
-       public static bool IsFriendAssembly (Assembly assembly)
-       {
-               return false;
+               Report.Error (281,
+                       "Friend access was granted to `{0}', but the output assembly is named `{1}'. Try adding a reference to `{0}' or change the output assembly name to match it",
+                       other_name, CodeGen.Assembly.Name.FullName);
        }
-#endif
-       
+
         //
         // Do the right thing when returning the element type of an
         // array type based on whether we are compiling corlib or not
@@ -1968,6 +1607,21 @@ namespace Mono.CSharp {
        {
                return t.IsArray || t.IsPointer || t.IsByRef;
        }
+
+       public static Type GetEnumUnderlyingType (Type t)
+       {
+               t = DropGenericTypeArguments (t);
+               Enum e = LookupTypeContainer (t) as Enum;
+               if (e != null)
+                       return e.UnderlyingType;
+
+               // TODO: cache it ?
+               FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null, Type.EmptyTypes);
+               if (fi == null)
+                       return TypeManager.int32_type;
+
+               return TypeToCoreType (fi.FieldType);
+       }
        
        /// <summary>
        ///   Gigantic work around for missing features in System.Reflection.Emit follows.
@@ -1978,23 +1632,30 @@ namespace Mono.CSharp {
        ///   for anything which is dynamic, and we need this in a number of places,
        ///   we register this information here, and use it afterwards.
        /// </remarks>
-       static public void RegisterMethod (MethodBase mb, Parameters ip)
+       static public void RegisterMethod (MethodBase mb, AParametersCollection ip)
        {
                method_params.Add (mb, ip);
        }
+
+       static public void RegisterIndexer (PropertyBuilder pb, AParametersCollection p)
+       {
+               method_params.Add (pb, p);
+       }
        
-       static public ParameterData GetParameterData (MethodBase mb)
+       static public AParametersCollection GetParameterData (MethodBase mb)
        {
-               ParameterData pd = (ParameterData)method_params [mb];
+               AParametersCollection pd = (AParametersCollection) method_params [mb];
                if (pd == null) {
 #if MS_COMPATIBLE
                        if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
                                MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
                                pd = GetParameterData (mi);
+                               /*
                                if (mi.IsGenericMethod)
                                        pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
                                else
                                        pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
+                               */
                                method_params.Add (mb, pd);
                                return pd;
                        }
@@ -2003,14 +1664,41 @@ namespace Mono.CSharp {
                                throw new InternalErrorException ("Parameters are not registered for method `{0}'",
                                        TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
                        }
+
+                       pd = ParametersImported.Create (mb);
+#else
+                       MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
+                       if (generic != mb) {
+                               pd = TypeManager.GetParameterData (generic);
+                               pd = ParametersImported.Create (pd, mb);
+                       } else {
+                               pd = ParametersImported.Create (mb);
+                       }
 #endif
-                       pd = new ReflectionParameters (mb);
                        method_params.Add (mb, pd);
                }
                return pd;
        }
 
-       public static ParameterData GetDelegateParameters (Type t)
+       public static AParametersCollection GetParameterData (PropertyInfo pi)
+       {
+               AParametersCollection pd = (AParametersCollection)method_params [pi];
+               if (pd == null) {
+                       if (pi is PropertyBuilder)
+                               return ParametersCompiled.EmptyReadOnlyParameters;
+
+                       ParameterInfo [] p = pi.GetIndexParameters ();
+                       if (p == null)
+                               return ParametersCompiled.EmptyReadOnlyParameters;
+
+                       pd = ParametersImported.Create (p, null);
+                       method_params.Add (pi, pd);
+               }
+
+               return pd;
+       }
+
+       public static AParametersCollection GetDelegateParameters (Type t)
        {
                Delegate d = builder_to_declspace [t] as Delegate;
                if (d != null)
@@ -2044,38 +1732,6 @@ namespace Mono.CSharp {
                return (MethodBase) method_overrides [m];
        }
 
-       /// <summary>
-       ///    Returns the argument types for an indexer based on its PropertyInfo
-       ///
-       ///    For dynamic indexers, we use the compiler provided types, for
-       ///    indexers from existing assemblies we load them from GetParameters,
-       ///    and insert them into the cache
-       /// </summary>
-       static public Type [] GetArgumentTypes (PropertyInfo indexer)
-       {
-               if (indexer_arguments.Contains (indexer))
-                       return (Type []) indexer_arguments [indexer];
-               else if (indexer is PropertyBuilder)
-                       // If we're a PropertyBuilder and not in the
-                       // `indexer_arguments' hash, then we're a property and
-                       // not an indexer.
-                       return Type.EmptyTypes;
-               else {
-                       ParameterInfo [] pi = indexer.GetIndexParameters ();
-                       // Property, not an indexer.
-                       if (pi == null)
-                               return Type.EmptyTypes;
-                       int c = pi.Length;
-                       Type [] types = new Type [c];
-                       
-                       for (int i = 0; i < c; i++)
-                               types [i] = pi [i].ParameterType;
-
-                       indexer_arguments.Add (indexer, types);
-                       return types;
-               }
-       }
-       
        public static void RegisterConstant (FieldInfo fb, IConstant ic)
        {
                fields.Add (fb, ic);
@@ -2149,14 +1805,6 @@ namespace Mono.CSharp {
                return (EventField) events [ei];
        }
 
-       static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
-                                            MethodBase set, Type[] args)
-       {
-               indexer_arguments.Add (pb, args);
-
-               return true;
-       }
-
        public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
        {
                Hashtable hash = new Hashtable ();
@@ -2166,7 +1814,7 @@ namespace Mono.CSharp {
        public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
                                              Hashtable hash)
        {
-               if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
+               if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
                        return true;
 
                //
@@ -2270,7 +1918,7 @@ namespace Mono.CSharp {
                return ret;
        }
                
-       static PtrHashtable iface_cache = new PtrHashtable ();
+       static PtrHashtable iface_cache;
                
        /// <summary>
        ///   This function returns the interfaces in the type `t'.  Works with
@@ -2321,7 +1969,6 @@ namespace Mono.CSharp {
 
                        iface_cache [t] = result;
                        return result;
-#if GMCS_SOURCE
                } else if (t is GenericTypeParameterBuilder){
                        Type[] type_ifaces = (Type []) builder_to_ifaces [t];
                        if (type_ifaces == null || type_ifaces.Length == 0)
@@ -2329,7 +1976,6 @@ namespace Mono.CSharp {
 
                        iface_cache [t] = type_ifaces;
                        return type_ifaces;
-#endif
                } else {
                        Type[] ifaces = t.GetInterfaces ();
                        iface_cache [t] = ifaces;
@@ -2365,7 +2011,7 @@ namespace Mono.CSharp {
 
                        if (interfaces != null){
                                foreach (Type i in interfaces){
-                                       if (i == iface)
+                                       if (i == iface || IsVariantOf (i, iface))
                                                return true;
                                }
                        }
@@ -2376,6 +2022,39 @@ namespace Mono.CSharp {
                return false;
        }
 
+       public static bool IsVariantOf (Type type1, Type type2)
+       {
+#if GMCS_SOURCE
+               if (type1.IsGenericType && type2.IsGenericType) {
+                       Type generic_target_type = type2.GetGenericTypeDefinition ();
+                       if (type1.GetGenericTypeDefinition () == generic_target_type) {
+                               Type [] t1 = type1.GetGenericArguments ();
+                               Type [] t2 = type2.GetGenericArguments ();
+                               int i = 0;
+                               foreach (Type t in generic_target_type.GetGenericArguments ()) {
+                                       if ((t.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) != 0) {
+                                               // FIXME this is not right
+                                               if (IsValueType (t1[i]) || IsValueType (t2[i])) {
+                                                       return false;
+                                               }
+                                               if ((t.GenericParameterAttributes & GenericParameterAttributes.Covariant) != 0 && !t2[i].IsAssignableFrom (t1[i])) {
+                                                       return false;
+                                               }
+                                               if ((t.GenericParameterAttributes & GenericParameterAttributes.Contravariant) != 0 && !t1[i].IsAssignableFrom (t2[i])) {
+                                                       return false;
+                                               }
+                                       } else if (t1[i] != t2[i]) {
+                                               return false;
+                                       }
+                                       i++;
+                               }
+                               return true;
+                       }
+               }
+#endif
+               return false;
+       }
+
        static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
 
        // This is a custom version of Convert.ChangeType() which works
@@ -2413,7 +2092,7 @@ namespace Mono.CSharp {
                        if (conversionType.Equals (typeof (DateTime)))
                                return (object)(convert_value.ToDateTime (nf_provider));
 
-                       if (conversionType.Equals (TypeManager.decimal_type)) {
+                       if (conversionType.Equals (decimal_type)) {
                                if (convert_value.GetType () == TypeManager.char_type)
                                        return (decimal)convert_value.ToInt32 (nf_provider);
                                return convert_value.ToDecimal (nf_provider);
@@ -2427,9 +2106,9 @@ namespace Mono.CSharp {
 
                        if (conversionType.Equals (typeof (Int16)))
                                return (object)(convert_value.ToInt16 (nf_provider));
-                       if (conversionType.Equals (typeof (Int32)))
+                       if (conversionType.Equals (int32_type))
                                return (object)(convert_value.ToInt32 (nf_provider));
-                       if (conversionType.Equals (typeof (Int64)))
+                       if (conversionType.Equals (int64_type))
                                return (object)(convert_value.ToInt64 (nf_provider));
                        if (conversionType.Equals (typeof (SByte)))
                                return (object)(convert_value.ToSByte (nf_provider));
@@ -2459,68 +2138,12 @@ namespace Mono.CSharp {
        }
 
        //
-       // This is needed, because enumerations from assemblies
-       // do not report their underlyingtype, but they report
-       // themselves
-       //
-       public static Type EnumToUnderlying (Type t)
-       {
-               t = DropGenericTypeArguments (t);
-               if (t == TypeManager.enum_type)
-                       return t;
-
-               t = t.UnderlyingSystemType;
-               if (!TypeManager.IsEnumType (t))
-                       return t;
-       
-               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)
-                               return t;
-               }
-               TypeCode tc = Type.GetTypeCode (t);
-
-               switch (tc){
-               case TypeCode.Boolean:
-                       return TypeManager.bool_type;
-               case TypeCode.Byte:
-                       return TypeManager.byte_type;
-               case TypeCode.SByte:
-                       return TypeManager.sbyte_type;
-               case TypeCode.Char:
-                       return TypeManager.char_type;
-               case TypeCode.Int16:
-                       return TypeManager.short_type;
-               case TypeCode.UInt16:
-                       return TypeManager.ushort_type;
-               case TypeCode.Int32:
-                       return TypeManager.int32_type;
-               case TypeCode.UInt32:
-                       return TypeManager.uint32_type;
-               case TypeCode.Int64:
-                       return TypeManager.int64_type;
-               case TypeCode.UInt64:
-                       return TypeManager.uint64_type;
-               }
-               throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
-       }
-
-       //
-       // When compiling corlib and called with one of the core types, return
-       // the corresponding typebuilder for that type.
+       // When compiling with -nostdlib and the type is imported from an external assembly
+       // SRE uses "wrong" type and we have to convert it to the right compiler instance.
        //
        public static Type TypeToCoreType (Type t)
        {
-               if (RootContext.StdLib || (t is TypeBuilder))
+               if (RootContext.StdLib || t.Module != typeof (object).Module)
                        return t;
 
                TypeCode tc = Type.GetTypeCode (t);
@@ -2554,17 +2177,34 @@ namespace Mono.CSharp {
                        return TypeManager.string_type;
                case TypeCode.Decimal:
                        return TypeManager.decimal_type;
-               default:
-                       if (t == typeof (void))
-                               return TypeManager.void_type;
-                       if (t == typeof (object))
-                               return TypeManager.object_type;
-                       if (t == typeof (System.Type))
-                               return TypeManager.type_type;
-                       if (t == typeof (System.IntPtr))
-                               return TypeManager.intptr_type;
-                       return t;
                }
+
+               if (t == typeof (void))
+                       return TypeManager.void_type;
+               if (t == typeof (object))
+                       return TypeManager.object_type;
+               if (t == typeof (System.Type))
+                       return TypeManager.type_type;
+               if (t == typeof (System.IntPtr))
+                       return TypeManager.intptr_type;
+               if (t == typeof (System.UIntPtr))
+                       return TypeManager.uintptr_type;
+#if GMCS_SOURCE
+               if (t.IsArray) {
+                       int dim = t.GetArrayRank ();
+                       t = GetElementType (t);
+                       return t.MakeArrayType (dim);
+               }
+               if (t.IsByRef) {
+                       t = GetElementType (t);
+                       return t.MakeByRefType ();
+               }
+               if (t.IsPointer) {
+                       t = GetElementType (t);
+                       return t.MakePointerType ();
+               }
+#endif
+               return t;
        }
 
        /// <summary>
@@ -2576,6 +2216,10 @@ namespace Mono.CSharp {
                if (IsUnmanagedType (t))
                        return true;
 
+               while (t.IsPointer)
+                       t = GetElementType (t);
+
+               Report.SymbolRelatedToPreviousError (t);
                Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
                        CSharpName (t));
 
@@ -2597,12 +2241,15 @@ namespace Mono.CSharp {
                        TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
                        return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
                }
-               
-               System.Attribute attr = System.Attribute.GetCustomAttribute (
-                       t, TypeManager.default_member_type);
-               if (attr != null){
-                       DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
-                       return dma.MemberName;
+
+               PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
+               if (pa.IsDefined) {
+                       System.Attribute attr = System.Attribute.GetCustomAttribute (
+                               t, pa.Type);
+                       if (attr != null) {
+                               DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
+                               return dma.MemberName;
+                       }
                }
 
                return TypeContainer.DefaultIndexerName;
@@ -2663,19 +2310,18 @@ namespace Mono.CSharp {
                        if (a.GetArrayRank () != b.GetArrayRank ())
                                return false;
 
-                       return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
+                       return IsSignatureEqual (GetElementType (a), GetElementType (b));
                }
 
                if (a.IsByRef && b.IsByRef)
-                       return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
+                       return IsSignatureEqual (GetElementType (a), GetElementType (b));
 
-#if GMCS_SOURCE
-               if (a.IsGenericType && b.IsGenericType) {
-                       if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
+               if (IsGenericType (a) && IsGenericType (b)) {
+                       if (DropGenericTypeArguments (a) != DropGenericTypeArguments (b))
                                return false;
 
-                       Type[] aargs = a.GetGenericArguments ();
-                       Type[] bargs = b.GetGenericArguments ();
+                       Type[] aargs = GetTypeArguments (a);
+                       Type[] bargs = GetTypeArguments (b);
 
                        if (aargs.Length != bargs.Length)
                                return false;
@@ -2687,7 +2333,6 @@ namespace Mono.CSharp {
 
                        return true;
                }
-#endif
 
                return false;
        }
@@ -2695,19 +2340,22 @@ namespace Mono.CSharp {
        //
        // Returns whether the array of memberinfos contains the given method
        //
-       public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
+       public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method, bool ignoreDeclType)
        {
                Type [] new_args = TypeManager.GetParameterData (new_method).Types;
                
                foreach (MethodBase method in array) {
+                       if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
+                               continue;
+               
                        if (method.Name != new_method.Name)
                                continue;
 
-                        if (method is MethodInfo && new_method is MethodInfo)
-                                if (!IsSignatureEqual (((MethodInfo) method).ReturnType,
-                                                      ((MethodInfo) new_method).ReturnType))
-                                        continue;
-
+                       if (method is MethodInfo && new_method is MethodInfo &&
+                               !IsSignatureEqual (
+                                       TypeToCoreType (((MethodInfo) method).ReturnType),
+                                       TypeToCoreType (((MethodInfo) new_method).ReturnType)))
+                               continue;
                         
                        Type [] old_args = TypeManager.GetParameterData (method).Types;
                        int old_count = old_args.Length;
@@ -2753,7 +2401,7 @@ namespace Mono.CSharp {
                foreach (MemberInfo mi in new_members){
                        MethodBase new_method = (MethodBase) mi;
                        
-                       if (!ArrayContainsMethod (target_array, new_method))
+                       if (!ArrayContainsMethod (target_array, new_method, true))
                                target_list.Add (new_method);
                }
                return target_list;
@@ -2850,30 +2498,37 @@ namespace Mono.CSharp {
                        if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
                                return a.FullName == b.FullName;
 
+                       // Some types are never equal
+                       if (a == TypeManager.null_type || a == TypeManager.anonymous_method_type)
+                               return false;
+
                        return true;
                }
 
-#if GMCS_SOURCE
-               if (a.IsGenericParameter && b.IsGenericParameter) {
+               if (IsGenericParameter (a) && IsGenericParameter (b)) {
                        // TODO: needs more testing before cleaning up
                        //if (a.DeclaringMethod != b.DeclaringMethod &&
                        //    (a.DeclaringMethod == null || b.DeclaringMethod == null))
                        //      return false;
+#if GMCS_SOURCE
                        return a.GenericParameterPosition == b.GenericParameterPosition;
+#else
+                       throw new NotSupportedException ();
+#endif
                }
 
                if (a.IsArray && b.IsArray) {
                        if (a.GetArrayRank () != b.GetArrayRank ())
                                return false;
-                       return IsEqual (a.GetElementType (), b.GetElementType ());
+                       return IsEqual (GetElementType (a), GetElementType (b));
                }
 
                if (a.IsByRef && b.IsByRef)
                        return IsEqual (a.GetElementType (), b.GetElementType ());
 
-               if (a.IsGenericType && b.IsGenericType) {
-                       Type adef = a.GetGenericTypeDefinition ();
-                       Type bdef = b.GetGenericTypeDefinition ();
+               if (IsGenericType (a) && IsGenericType (b)) {
+                       Type adef = DropGenericTypeArguments (a);
+                       Type bdef = DropGenericTypeArguments (b);
 
                        if (adef != bdef)
                                return false;
@@ -2881,8 +2536,8 @@ namespace Mono.CSharp {
                        if (adef.IsEnum && bdef.IsEnum)
                                return true;
 
-                       Type[] aargs = a.GetGenericArguments ();
-                       Type[] bargs = b.GetGenericArguments ();
+                       Type[] aargs = GetTypeArguments (a);
+                       Type[] bargs = GetTypeArguments (b);
 
                        if (aargs.Length != bargs.Length)
                                return false;
@@ -2894,11 +2549,30 @@ namespace Mono.CSharp {
 
                        return true;
                }
-#endif
 
                return false;
        }
 
+       public static bool IsEqual (Type[] a, Type[] b)
+       {
+               if (a == null || b == null || a.Length != b.Length)
+                       return false;
+
+               for (int i = 0; i < a.Length; ++i) {
+                       if (a [i] == null || b [i] == null) {
+                               if (a [i] == b [i])
+                                       continue;
+
+                               return false;
+                       }
+               
+                       if (!IsEqual (a [i], b [i]))
+                               return false;
+               }
+
+               return true;
+       }
+
        public static Type DropGenericTypeArguments (Type t)
        {
 #if GMCS_SOURCE
@@ -2916,14 +2590,14 @@ namespace Mono.CSharp {
        public static MethodBase DropGenericMethodArguments (MethodBase m)
        {
 #if GMCS_SOURCE
-               if (m.IsGenericMethodDefinition)
-                       return m;
                if (m.IsGenericMethod)
-                       return ((MethodInfo) m).GetGenericMethodDefinition ();
-               if (!m.DeclaringType.IsGenericType)
+                 m = ((MethodInfo) m).GetGenericMethodDefinition ();
+
+               Type t = m.DeclaringType;
+               if (!t.IsGenericType || t.IsGenericTypeDefinition)
                        return m;
 
-               Type t = m.DeclaringType.GetGenericTypeDefinition ();
+               t = t.GetGenericTypeDefinition ();
                BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
                        BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
 
@@ -3071,30 +2745,6 @@ namespace Mono.CSharp {
                return generic_nullable_type == DropGenericTypeArguments (t);
 #else
                return false;
-#endif
-       }
-
-       public static bool IsNullableTypeOf (Type t, Type nullable)
-       {
-#if GMCS_SOURCE
-               if (!IsNullableType (t))
-                       return false;
-
-               return GetTypeArguments (t) [0] == nullable;
-#else
-               return false;
-#endif
-       }
-
-       public static bool IsNullableValueType (Type t)
-       {
-#if GMCS_SOURCE
-               if (!IsNullableType (t))
-                       return false;
-
-               return GetTypeArguments (t) [0].IsValueType;
-#else
-               return false;
 #endif
        }
 #endregion
@@ -3186,8 +2836,7 @@ namespace Mono.CSharp {
                                                IsPrivateAccessible (invocation_type, m.DeclaringType) ||
                                                IsNestedChildOf (invocation_type, m.DeclaringType);
 
-                               if (invocation_assembly == mb.DeclaringType.Assembly ||
-                                   TypeManager.IsFriendAssembly (mb.DeclaringType.Assembly)) {
+                               if (TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly)) {
                                        if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
                                                return true;
                                } else {
@@ -3214,9 +2863,7 @@ namespace Mono.CSharp {
                                                IsPrivateAccessible (invocation_type, m.DeclaringType) ||
                                                IsNestedChildOf (invocation_type, m.DeclaringType);
 
-                               if ((invocation_assembly == fi.DeclaringType.Assembly) ||
-                                   (invocation_assembly == null) ||
-                                   TypeManager.IsFriendAssembly (fi.DeclaringType.Assembly)) {
+                               if (TypeManager.IsThisOrFriendAssembly (fi.DeclaringType.Assembly)) {
                                        if ((fa == FieldAttributes.Assembly) ||
                                            (fa == FieldAttributes.FamORAssem))
                                                return true;
@@ -3238,8 +2885,8 @@ namespace Mono.CSharp {
                }
        }
 
-       static Closure closure = new Closure ();
-       static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
+       static Closure closure;
+       static MemberFilter FilterWithClosure_delegate;
 
        //
        // Looks up a member called `name' in the `queried_type'.  This lookup
@@ -3525,17 +3172,9 @@ namespace Mono.CSharp {
                        return true;
 
                string name = mb.Name;
-               if (name.StartsWith ("op_")){
-                       foreach (string oname in Unary.oper_names) {
-                               if (oname == name)
-                                       return true;
-                       }
+               if (name.StartsWith ("op_"))
+                       return Operator.GetName (name) != null;
 
-                       foreach (string oname in Binary.oper_names) {
-                               if (oname == name)
-                                       return true;
-                       }
-               }
                return false;
        }
 
@@ -3546,12 +3185,37 @@ namespace Mono.CSharp {
        {
                MethodInfo get_method = pi.GetGetMethod (true);
                MethodInfo set_method = pi.GetSetMethod (true);
+               int g_count = 0;
+               int s_count = 0;
                if (get_method != null && set_method != null) {
-                       int g_count = get_method.GetParameters ().Length;
-                       int s_count = set_method.GetParameters ().Length;
+                       g_count = get_method.GetParameters ().Length;
+                       s_count = set_method.GetParameters ().Length;
                        if (g_count + 1 != s_count)
                                return false;
+               } else if (get_method != null) {
+                       g_count = get_method.GetParameters ().Length;
+               } else if (set_method != null) {
+                       s_count = set_method.GetParameters ().Length;
+               }
+
+               //
+               // DefaultMemberName and indexer name has to match to identify valid C# indexer
+               //
+               PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
+               if ((s_count > 1 || g_count > 0) && pa.IsDefined) {
+                       object[] o = pi.DeclaringType.GetCustomAttributes (pa.Type, false);
+                       if (o.Length == 0)
+                               return false;
+                       
+                       DefaultMemberAttribute dma = (DefaultMemberAttribute) o [0];
+                       if (dma.MemberName != pi.Name)
+                               return false;
+                       if (get_method != null && "get_" + dma.MemberName != get_method.Name)
+                               return false;
+                       if (set_method != null && "set_" + dma.MemberName != set_method.Name)
+                               return false;
                }
+
                return true;
        }
 
@@ -3686,11 +3350,12 @@ public sealed class TypeHandle : IMemberContainer {
        {
                MemberInfo [] members;
 
-#if GMCS_SOURCE
                if (type is GenericTypeParameterBuilder)
                        return MemberList.Empty;
-#endif
 
+#if MS_COMPATIBLE
+               type = TypeManager.DropGenericTypeArguments (type);
+#endif
                if (mt == MemberTypes.Event)
                        members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
                else
@@ -3726,5 +3391,4 @@ public sealed class TypeHandle : IMemberContainer {
                        return "TypeHandle (" + id + "," + Name + ")";
        }
 }
-
 }