New tests.
[mono.git] / mcs / class / corlib / System.Reflection.Emit / TypeBuilder.cs
index 82bc20c3ba7c5047bfd99bf627214c289407b3c0..0a7be28f12e0fdf5cc4146d4913b26bd6bbf5c2e 100644 (file)
@@ -1,8 +1,9 @@
 //
-// System.Reflection.Emit/TypeBuilder.cs
+// System.Reflection.Emit.TypeBuilder.cs
 //
 // Author:
 //   Paolo Molaro (lupus@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
 //
 // (C) 2001 Ximian, Inc.  http://www.ximian.com
 //
@@ -42,47 +43,49 @@ using System.Security;
 using System.Security.Permissions;
 using System.Diagnostics.SymbolStore;
 
-namespace System.Reflection.Emit {
-#if NET_2_0
+namespace System.Reflection.Emit
+{
        [ComVisible (true)]
        [ComDefaultInterface (typeof (_TypeBuilder))]
-#endif
        [ClassInterface (ClassInterfaceType.None)]
-       public sealed class TypeBuilder : Type, _TypeBuilder {
-       #region Sync with reflection.h
-       private string tname;
-       private string nspace;
-       private Type parent;
-       private Type nesting_type;
-       private Type[] interfaces;
-       private int num_methods;
-       private MethodBuilder[] methods;
-       private ConstructorBuilder[] ctors;
-       private PropertyBuilder[] properties;
-       private int num_fields;
-       private FieldBuilder[] fields;
-       private EventBuilder[] events;
-       private CustomAttributeBuilder[] cattrs;
-       internal TypeBuilder[] subtypes;
-       internal TypeAttributes attrs;
-       private int table_idx;
-       private ModuleBuilder pmodule;
-       private int class_size;
-       private PackingSize packing_size;
-       private IntPtr generic_container;
-#if NET_2_0 || BOOTSTRAP_NET_2_0
-       private GenericTypeParameterBuilder[] generic_params;
-#else
-        private Object generic_params; /* so offsets don't change */
-#endif
-       private RefEmitPermissionSet[] permissions;     
-       private Type created;
-       #endregion
-       string fullname;
-
-       public const int UnspecifiedTypeSize = 0;
+       public sealed class TypeBuilder : Type, _TypeBuilder
+       {
+#pragma warning disable 169            
+               #region Sync with reflection.h
+               private string tname;
+               private string nspace;
+               private Type parent;
+               private Type nesting_type;
+               internal Type[] interfaces;
+               internal int num_methods;
+               internal MethodBuilder[] methods;
+               internal ConstructorBuilder[] ctors;
+               internal PropertyBuilder[] properties;
+               internal int num_fields;
+               internal FieldBuilder[] fields;
+               internal EventBuilder[] events;
+               private CustomAttributeBuilder[] cattrs;
+               internal TypeBuilder[] subtypes;
+               internal TypeAttributes attrs;
+               private int table_idx;
+               private ModuleBuilder pmodule;
+               private int class_size;
+               private PackingSize packing_size;
+               private IntPtr generic_container;
+               private GenericTypeParameterBuilder[] generic_params;
+               private RefEmitPermissionSet[] permissions;
+               private Type created;
+               #endregion
+#pragma warning restore 169            
+               
+               string fullname;
+               bool createTypeCalled;
+               private Type underlying_type;
 
-               protected override TypeAttributes GetAttributeFlagsImpl () {
+               public const int UnspecifiedTypeSize = 0;
+               
+               protected override TypeAttributes GetAttributeFlagsImpl ()
+               {
                        return attrs;
                }
                
@@ -101,24 +104,32 @@ namespace System.Reflection.Emit {
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern EventInfo get_event_info (EventBuilder eb);
 
-               internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr) {
+               internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr, int table_idx)
+               {
                        this.parent = null;
                        this.attrs = attr;
                        this.class_size = UnspecifiedTypeSize;
-                       this.table_idx = 1;
-                       fullname = this.tname = "<Module>";
+                       this.table_idx = table_idx;
+                       fullname = this.tname = table_idx == 1 ? "<Module>" : "type_" + table_idx.ToString ();
                        this.nspace = String.Empty;
                        pmodule = mb;
                        setup_internal_class (this);
                }
 
-               internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type) {
+               internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type)
+               {
                        int sep_index;
                        this.parent = parent;
                        this.attrs = attr;
                        this.class_size = type_size;
                        this.packing_size = packing_size;
                        this.nesting_type = nesting_type;
+
+                       check_name ("fullname", name);
+
+                       if (parent == null && (attr & TypeAttributes.Interface) != 0 && (attr & TypeAttributes.Abstract) == 0)
+                               throw new InvalidOperationException ("Interface must be declared abstract.");
+
                        sep_index = name.LastIndexOf('.');
                        if (sep_index != -1) {
                                this.tname = name.Substring (sep_index + 1);
@@ -132,6 +143,10 @@ namespace System.Reflection.Emit {
                                System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
                        }
                        pmodule = mb;
+
+                       if (((attr & TypeAttributes.Interface) == 0) && (parent == null) && !IsCompilerContext)
+                               this.parent = typeof (object);
+
                        // skip .<Module> ?
                        table_idx = mb.get_next_table_index (this, 0x02, true);
                        setup_internal_class (this);
@@ -144,17 +159,22 @@ namespace System.Reflection.Emit {
 
                public override string AssemblyQualifiedName {
                        get {
-                               return fullname + ", " + Assembly.GetName().FullName;
+                               return fullname + ", " + Assembly.FullName;
                        }
                }
+
                public override Type BaseType {
                        get {
                                return parent;
                        }
                }
-               public override Type DeclaringType {get {return nesting_type;}}
 
-/*             public override bool IsSubclassOf (Type c)
+               public override Type DeclaringType {
+                       get { return nesting_type; }
+               }
+
+               [ComVisible (true)]
+               public override bool IsSubclassOf (Type c)
                {
                        Type t;
                        if (c == null)
@@ -168,34 +188,26 @@ namespace System.Reflection.Emit {
                                t = t.BaseType;
                        }
                        return false;
-               }*/
+               }
 
-               [MonoTODO]
                public override Type UnderlyingSystemType {
                        get {
+                               if (is_created)
+                                       return created.UnderlyingSystemType;
+
+                               if (!IsCompilerContext && IsEnum) {
+                                       if (underlying_type != null)
+                                               return underlying_type;
+                                       throw new InvalidOperationException (
+                                               "Enumeration type is not defined.");
+                               }
 
-                               // Return this as requested by Zoltan.
-                               
                                return this;
-
-#if false
-                               // Dont know what to do with the rest, should be killed:
-                               // See bug: 75008.
-                               //
-                               ////// This should return the type itself for non-enum types but 
-                               ////// that breaks mcs.
-                               if (fields != null) {
-                                       foreach (FieldBuilder f in fields) {
-                                               if ((f != null) && (f.Attributes & FieldAttributes.Static) == 0)
-                                                       return f.FieldType;
-                                       }
-                               }
-                               throw new InvalidOperationException ("Underlying type information on enumeration is not specified.");
-#endif
                        }
                }
 
-               string GetFullName () {
+               string GetFullName ()
+               {
                        if (nesting_type != null)
                                return String.Concat (nesting_type.FullName, "+", tname);
                        if ((nspace != null) && (nspace.Length > 0))
@@ -219,21 +231,30 @@ namespace System.Reflection.Emit {
                public override Module Module {
                        get {return pmodule;}
                }
+
                public override string Name {
                        get {return tname;}
                }
+
                public override string Namespace {
                        get {return nspace;}
                }
+
                public PackingSize PackingSize {
                        get {return packing_size;}
                }
+
                public int Size {
                        get { return class_size; }
                }
-               public override Type ReflectedType {get {return nesting_type;}}
 
-               public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
+               public override Type ReflectedType {
+                       get { return nesting_type; }
+               }
+
+               public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
+               {
+#if !NET_2_1
                        if (pset == null)
                                throw new ArgumentNullException ("pset");
                        if ((action == SecurityAction.RequestMinimum) ||
@@ -258,12 +279,12 @@ namespace System.Reflection.Emit {
 
                        permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
                        attrs |= TypeAttributes.HasSecurity;
+#endif
                }
 
-#if NET_2_0
                [ComVisible (true)]
-#endif
-               public void AddInterfaceImplementation( Type interfaceType) {
+               public void AddInterfaceImplementation (Type interfaceType)
+               {
                        if (interfaceType == null)
                                throw new ArgumentNullException ("interfaceType");
                        check_not_created ();
@@ -284,51 +305,64 @@ namespace System.Reflection.Emit {
                        }
                }
 
-               [MonoTODO]
                protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
                                                                       CallingConventions callConvention, Type[] types,
                                                                       ParameterModifier[] modifiers)
                {
                        check_created ();
-                       
-                       if (ctors == null)
-                               return null;
 
-                       ConstructorBuilder found = null;
-                       int count = 0;
+                       if (created == typeof (object)) {
+                               /* 
+                                * This happens when building corlib. Calling created.GetConstructor 
+                                * would return constructors from the real mscorlib, instead of the
+                                * newly built one.
+                                */
+
+                               if (ctors == null)
+                                       return null;
+                               ConstructorBuilder found = null;
+                               int count = 0;
                        
-                       foreach (ConstructorBuilder cb in ctors){
-                               if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
-                                       continue;
-                               found = cb;
-                               count++;
-                       }
-
-                       if (count == 0)
-                               return null;
-                       if (types == null){
-                               if (count > 1)
-                                       throw new AmbiguousMatchException ();
-                               return found;
-                       }
-                       MethodBase[] match = new MethodBase [count];
-                       if (count == 1)
-                               match [0] = found;
-                       else {
-                               count = 0;
-                               foreach (ConstructorInfo m in ctors) {
-                                       if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
+                               foreach (ConstructorBuilder cb in ctors) {
+                                       if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
                                                continue;
-                                       match [count++] = m;
+                                       found = cb;
+                                       count++;
+                               }
+
+                               if (count == 0)
+                                       return null;
+                               if (types == null) {
+                                       if (count > 1)
+                                               throw new AmbiguousMatchException ();
+                                       return found;
+                               }
+                               MethodBase[] match = new MethodBase [count];
+                               if (count == 1)
+                                       match [0] = found;
+                               else {
+                                       count = 0;
+                                       foreach (ConstructorInfo m in ctors) {
+                                               if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
+                                                       continue;
+                                               match [count++] = m;
+                                       }
                                }
+                               if (binder == null)
+                                       binder = Binder.DefaultBinder;
+                               return (ConstructorInfo) binder.SelectMethod (bindingAttr, match,
+                                                                                                                         types, modifiers);
                        }
-                       if (binder == null)
-                               binder = Binder.DefaultBinder;
-                       return (ConstructorInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
+
+                       return created.GetConstructor (bindingAttr, binder, 
+                               callConvention, types, modifiers);
                }
 
-               public override bool IsDefinedType attributeType, bool inherit)
+               public override bool IsDefined (Type attributeType, bool inherit)
                {
+                       if (!is_created && !IsCompilerContext)
+                               throw new NotSupportedException ();
                        /*
                         * MS throws NotSupported here, but we can't because some corlib
                         * classes make calls to IsDefined.
@@ -350,22 +384,25 @@ namespace System.Reflection.Emit {
                        return created.GetCustomAttributes (attributeType, inherit);
                }
 
-               public TypeBuilder DefineNestedType (string name) {
-                       return DefineNestedType (name, TypeAttributes.NestedPrivate, pmodule.assemblyb.corlib_object_type, null);
+               public TypeBuilder DefineNestedType (string name)
+               {
+                       return DefineNestedType (name, TypeAttributes.NestedPrivate,
+                               pmodule.assemblyb.corlib_object_type, null);
                }
 
-               public TypeBuilder DefineNestedType (string name, TypeAttributes attr) {
+               public TypeBuilder DefineNestedType (string name, TypeAttributes attr)
+               {
                        return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
                }
 
-               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) {
+               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent)
+               {
                        return DefineNestedType (name, attr, parent, null);
                }
 
                private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
-                                                     PackingSize packsize, int typesize)
+                                                     PackingSize packSize, int typeSize)
                {
-                       check_name ("name", name);
                        // Visibility must be NestedXXX
                        /* This breaks mcs
                        if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
@@ -377,7 +414,7 @@ namespace System.Reflection.Emit {
                                        if (iface == null)
                                                throw new ArgumentNullException ("interfaces");
 
-                       TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packsize, typesize, this);
+                       TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packSize, typeSize, this);
                        res.fullname = res.GetFullName ();
                        pmodule.RegisterTypeName (res, res.fullname);
                        if (subtypes != null) {
@@ -392,40 +429,35 @@ namespace System.Reflection.Emit {
                        return res;
                }
 
-#if NET_2_0
                [ComVisible (true)]
-#endif
-               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
+               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces)
+               {
                        return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
                }
 
-               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
-                       return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typesize);
+               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typeSize)
+               {
+                       return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typeSize);
                }
 
-               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
-                       return DefineNestedType (name, attr, parent, null, packsize, UnspecifiedTypeSize);
+               public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packSize)
+               {
+                       return DefineNestedType (name, attr, parent, null, packSize, UnspecifiedTypeSize);
                }
 
-#if NET_2_0
                [ComVisible (true)]
-#endif
-               public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) {
+               public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
+               {
                        return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
                }
 
-#if NET_2_0
                [ComVisible (true)]
-#endif
-#if NET_2_0 || BOOTSTRAP_NET_2_0
-               public
-#else
-               internal
-#endif
-               ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
+               public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
                {
                        check_not_created ();
-                       ConstructorBuilder cb = new ConstructorBuilder (this, attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
+                       ConstructorBuilder cb = new ConstructorBuilder (this, attributes,
+                               callingConvention, parameterTypes, requiredCustomModifiers,
+                               optionalCustomModifiers);
                        if (ctors != null) {
                                ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
                                System.Array.Copy (ctors, new_ctors, ctors.Length);
@@ -438,9 +470,7 @@ namespace System.Reflection.Emit {
                        return cb;
                }
 
-#if NET_2_0
                [ComVisible (true)]
-#endif
                public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
                {
                        Type parent_type;
@@ -450,6 +480,7 @@ namespace System.Reflection.Emit {
                        else
                                parent_type = pmodule.assemblyb.corlib_object_type;
 
+                       parent_type = parent_type.InternalResolve ();
                        ConstructorInfo parent_constructor =
                                parent_type.GetConstructor (
                                        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
@@ -462,7 +493,7 @@ namespace System.Reflection.Emit {
                        }
 
                        ConstructorBuilder cb = DefineConstructor (attributes, 
-                               CallingConventions.Standard, new Type[0]);
+                               CallingConventions.Standard, Type.EmptyTypes);
                        ILGenerator ig = cb.GetILGenerator ();
                        ig.Emit (OpCodes.Ldarg_0);
                        ig.Emit (OpCodes.Call, parent_constructor);
@@ -470,7 +501,8 @@ namespace System.Reflection.Emit {
                        return cb;
                }
 
-               private void append_method (MethodBuilder mb) {
+               private void append_method (MethodBuilder mb)
+               {
                        if (methods != null) {
                                if (methods.Length == num_methods) {
                                        MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
@@ -484,45 +516,48 @@ namespace System.Reflection.Emit {
                        num_methods ++;
                }
 
-               public MethodBuilder DefineMethod( string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
-                       return DefineMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
+               public MethodBuilder DefineMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
+               {
+                       return DefineMethod (name, attributes, CallingConventions.Standard,
+                               returnType, parameterTypes);
                }
 
-               public MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
-                       return DefineMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
+               public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
+               {
+                       return DefineMethod (name, attributes, callingConvention, returnType,
+                               null, null, parameterTypes, null, null);
                }
 
-#if NET_2_0 || BOOTSTRAP_NET_2_0
-               public
-#else
-               internal
-#endif
-               MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
+               public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
+               {
                        check_name ("name", name);
                        check_not_created ();
                        if (IsInterface && (
                                !((attributes & MethodAttributes.Abstract) != 0) || 
                                !((attributes & MethodAttributes.Virtual) != 0)) &&
                                !(((attributes & MethodAttributes.Static) != 0)))
-                               throw new ArgumentException ("attributes", "Interface method must be abstract and virtual.");
+                               throw new ArgumentException ("Interface method must be abstract and virtual.");
 
                        if (returnType == null)
                                returnType = pmodule.assemblyb.corlib_void_type;
-                       MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
+                       MethodBuilder res = new MethodBuilder (this, name, attributes, 
+                               callingConvention, returnType,
+                               returnTypeRequiredCustomModifiers,
+                               returnTypeOptionalCustomModifiers, parameterTypes,
+                               parameterTypeRequiredCustomModifiers,
+                               parameterTypeOptionalCustomModifiers);
                        append_method (res);
                        return res;
                }
 
-               public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
-                       return DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet);
+               public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
+               {
+                       return DefinePInvokeMethod (name, dllName, entryName, attributes,
+                               callingConvention, returnType, null, null, parameterTypes,
+                               null, null, nativeCallConv, nativeCharSet);
                }
 
-#if NET_2_0 || BOOTSTRAP_NET_2_0
-               public
-#else
-               internal
-#endif
-               MethodBuilder DefinePInvokeMethod (
+               public MethodBuilder DefinePInvokeMethod (
                                                string name, 
                                                string dllName, 
                                                string entryName, MethodAttributes attributes, 
@@ -534,14 +569,15 @@ namespace System.Reflection.Emit {
                                                Type[][] parameterTypeRequiredCustomModifiers, 
                                                Type[][] parameterTypeOptionalCustomModifiers, 
                                                CallingConvention nativeCallConv, 
-                                               CharSet nativeCharSet) {
+                                               CharSet nativeCharSet)
+               {
                        check_name ("name", name);
                        check_name ("dllName", dllName);
                        check_name ("entryName", entryName);
                        if ((attributes & MethodAttributes.Abstract) != 0)
-                               throw new ArgumentException ("attributes", "PInvoke methods must be static and native and cannot be abstract.");
+                               throw new ArgumentException ("PInvoke methods must be static and native and cannot be abstract.");
                        if (IsInterface)
-                               throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");            
+                               throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
                        check_not_created ();
 
                        MethodBuilder res 
@@ -569,22 +605,25 @@ namespace System.Reflection.Emit {
                                nativeCallConv, nativeCharSet);
                }
 
-#if NET_2_0 || BOOTSTRAP_NET_2_0
-               public MethodBuilder DefineMethod (string name, MethodAttributes attributes) {
+               public MethodBuilder DefineMethod (string name, MethodAttributes attributes)
+               {
                        return DefineMethod (name, attributes, CallingConventions.Standard);
                }
 
-               public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callConv) {
-                       return DefineMethod (name, attributes, callConv, null, null);
+               public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention)
+               {
+                       return DefineMethod (name, attributes, callingConvention, null, null);
                }
-#endif
 
-               public void DefineMethodOverride( MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) {
+               public void DefineMethodOverride (MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
+               {
                        if (methodInfoBody == null)
                                throw new ArgumentNullException ("methodInfoBody");
                        if (methodInfoDeclaration == null)
                                throw new ArgumentNullException ("methodInfoDeclaration");
                        check_not_created ();
+                       if (methodInfoBody.DeclaringType != this)
+                               throw new ArgumentException ("method body must belong to this type");
 
                        if (methodInfoBody is MethodBuilder) {
                                MethodBuilder mb = (MethodBuilder)methodInfoBody;
@@ -592,22 +631,19 @@ namespace System.Reflection.Emit {
                        }
                }
 
-               public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) {
+               public FieldBuilder DefineField (string fieldName, Type type, FieldAttributes attributes)
+               {
                        return DefineField (fieldName, type, null, null, attributes);
                }
 
-#if NET_2_0 || BOOTSTRAP_NET_2_0
-               public
-#else
-               internal
-#endif
-           FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomAttributes, Type[] optionalCustomAttributes, FieldAttributes attributes) {
+               public FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
+               {
                        check_name ("fieldName", fieldName);
                        if (type == typeof (void))
-                               throw new ArgumentException ("type",  "Bad field type in defining field.");
+                               throw new ArgumentException ("Bad field type in defining field.");
                        check_not_created ();
 
-                       FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomAttributes, optionalCustomAttributes);
+                       FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomModifiers, optionalCustomModifiers);
                        if (fields != null) {
                                if (fields.Length == num_fields) {
                                        FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
@@ -622,19 +658,22 @@ namespace System.Reflection.Emit {
                                num_fields ++;
                                create_internal_class (this);
                        }
+
+                       if (IsEnum && !IsCompilerContext) {
+                               if (underlying_type == null && (attributes & FieldAttributes.Static) == 0)
+                                       underlying_type = type;
+                       }
+
                        return res;
                }
 
-               public PropertyBuilder DefineProperty( string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
+               public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
+               {
                        return DefineProperty (name, attributes, returnType, null, null, parameterTypes, null, null);
                }
 
-#if NET_2_0
-               public 
-#else
-               internal
-#endif
-               PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
+               public  PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
+               {
                        check_name ("name", name);
                        if (parameterTypes != null)
                                foreach (Type param in parameterTypes)
@@ -656,17 +695,20 @@ namespace System.Reflection.Emit {
                        return res;
                }
 
-#if NET_2_0
                [ComVisible (true)]
-#endif
-               public ConstructorBuilder DefineTypeInitializer() {
-                       return DefineConstructor (MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, null);
+               public ConstructorBuilder DefineTypeInitializer()
+               {
+                       return DefineConstructor (MethodAttributes.Public |
+                               MethodAttributes.Static | MethodAttributes.SpecialName |
+                               MethodAttributes.RTSpecialName, CallingConventions.Standard,
+                               null);
                }
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern Type create_runtime_class (TypeBuilder tb);
 
-               private bool is_nested_in (Type t) {
+               private bool is_nested_in (Type t)
+               {
                        while (t != null) {
                                if (t == this)
                                        return true;
@@ -675,12 +717,31 @@ namespace System.Reflection.Emit {
                        }
                        return false;
                }
+
+               // Return whenever this type has a ctor defined using DefineMethod ()
+               private bool has_ctor_method () {
+                       MethodAttributes ctor_attrs = MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
+
+                       for (int i = 0; i < num_methods; ++i) {
+                               MethodBuilder mb = (MethodBuilder)(methods[i]);
+
+                               if (mb.Name == ConstructorInfo.ConstructorName && (mb.Attributes & ctor_attrs) == ctor_attrs)
+                                       return true;
+                       }
+
+                       return false;
+           }
                
-               public Type CreateType() {
+               public Type CreateType()
+               {
                        /* handle nesting_type */
-                       if (created != null)
+                       if (createTypeCalled)
                                return created;
 
+                       if (!IsInterface && (parent == null) && (this != pmodule.assemblyb.corlib_object_type) && (FullName != "<Module>")) {
+                               SetParent (pmodule.assemblyb.corlib_object_type);
+                       }
+
                        create_generic_class ();
 
                        // Fire TypeResolve events for fields whose type is an unfinished
@@ -705,26 +766,37 @@ namespace System.Reflection.Emit {
                                }
                        }
 
-                       if ((parent != null) && parent.IsSealed)
-                               throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
-
-                       if (methods != null) {
-                               for (int i = 0; i < num_methods; ++i)
-                                       ((MethodBuilder)(methods[i])).fixup ();
-                       }
-
                        //
                        // On classes, define a default constructor if not provided
                        //
                        if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") && 
-                               (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed))
+                               (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ())
                                DefineDefaultConstructor (MethodAttributes.Public);
 
+                       createTypeCalled = true;
+
+                       if ((parent != null) && parent.IsSealed)
+                               throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
+
+                       if (parent == pmodule.assemblyb.corlib_enum_type && methods != null)
+                               throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is an enum with methods.");
+
+                       if (methods != null) {
+                               bool is_concrete = !IsAbstract;
+                               for (int i = 0; i < num_methods; ++i) {
+                                       MethodBuilder mb = (MethodBuilder)(methods[i]);
+                                       if (is_concrete && mb.IsAbstract)
+                                               throw new InvalidOperationException ("Type is concrete but has abstract method " + mb);
+                                       mb.check_override ();
+                                       mb.fixup ();
+                               }
+                       }
+
                        if (ctors != null){
                                foreach (ConstructorBuilder ctor in ctors) 
                                        ctor.fixup ();
                        }
-                       
+
                        created = create_runtime_class (this);
                        if (created != null)
                                return created;
@@ -748,12 +820,26 @@ namespace System.Reflection.Emit {
                        }
                        
                        symbolWriter.CloseNamespace ();
+
+                       if (subtypes != null) {
+                               for (int i = 0; i < subtypes.Length; ++i)
+                                       subtypes [i].GenerateDebugInfo (symbolWriter);
+                       }
                }
 
-#if NET_2_0
                [ComVisible (true)]
-#endif
                public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
+               {
+                       if (is_created)
+                               return created.GetConstructors (bindingAttr);
+
+                       if (!IsCompilerContext)
+                               throw new NotSupportedException ();
+
+                       return GetConstructorsInternal (bindingAttr);
+               }
+
+               internal ConstructorInfo[] GetConstructorsInternal (BindingFlags bindingAttr)
                {
                        if (ctors == null)
                                return new ConstructorInfo [0];
@@ -790,12 +876,13 @@ namespace System.Reflection.Emit {
                        return result;
                }
 
-               public override Type GetElementType () { 
-                       check_created ();
-                       return created.GetElementType ();
+               public override Type GetElementType ()
+               {
+                       throw new NotSupportedException ();
                }
 
-               public override EventInfo GetEvent (string name, BindingFlags bindingAttr) {
+               public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
+               {
                        check_created ();
                        return created.GetEvent (name, bindingAttr);
                }
@@ -806,14 +893,13 @@ namespace System.Reflection.Emit {
                        return GetEvents (DefaultBindingFlags);
                }
 
-               public override EventInfo[] GetEvents (BindingFlags bindingAttr) {
-                       /* FIXME: mcs calls this
-                          check_created ();
-                       */
-                       if (!is_created)
-                               return new EventInfo [0];
-                       else
+               public override EventInfo[] GetEvents (BindingFlags bindingAttr)
+               {
+                       if (is_created)
                                return created.GetEvents (bindingAttr);
+                       if (!IsCompilerContext)
+                               throw new NotSupportedException ();
+                       return new EventInfo [0]; /*FIXME shouldn't we return the events here?*/
                }
 
                // This is only used from MonoGenericInst.initialize().
@@ -863,7 +949,11 @@ namespace System.Reflection.Emit {
                        return result;
                }
 
-               public override FieldInfo GetField( string name, BindingFlags bindingAttr) {
+               public override FieldInfo GetField (string name, BindingFlags bindingAttr)
+               {
+                       if (created != null)
+                               return created.GetField (name, bindingAttr);
+
                        if (fields == null)
                                return null;
 
@@ -901,7 +991,11 @@ namespace System.Reflection.Emit {
                        return null;
                }
 
-               public override FieldInfo[] GetFields (BindingFlags bindingAttr) {
+               public override FieldInfo[] GetFields (BindingFlags bindingAttr)
+               {
+                       if (created != null)
+                               return created.GetFields (bindingAttr);
+
                        if (fields == null)
                                return new FieldInfo [0];
                        ArrayList l = new ArrayList ();
@@ -939,12 +1033,17 @@ namespace System.Reflection.Emit {
                        return result;
                }
 
-               public override Type GetInterface (string name, bool ignoreCase) {
+               public override Type GetInterface (string name, bool ignoreCase)
+               {
                        check_created ();
                        return created.GetInterface (name, ignoreCase);
                }
                
-               public override Type[] GetInterfaces () {
+               public override Type[] GetInterfaces ()
+               {
+                       if (is_created)
+                               return created.GetInterfaces ();
+
                        if (interfaces != null) {
                                Type[] ret = new Type [interfaces.Length];
                                interfaces.CopyTo (ret, 0);
@@ -955,26 +1054,64 @@ namespace System.Reflection.Emit {
                }
 
                public override MemberInfo[] GetMember (string name, MemberTypes type,
-                                                                                               BindingFlags bindingAttr) {
+                                                                                               BindingFlags bindingAttr)
+               {
                        check_created ();
                        return created.GetMember (name, type, bindingAttr);
                }
 
-               public override MemberInfo[] GetMembers (BindingFlags bindingAttr) {
+               public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
+               {
                        check_created ();
                        return created.GetMembers (bindingAttr);
                }
 
-               private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type) {
+               private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type)
+               {
                        MethodInfo[] candidates;
+                       bool match;
+                       MethodAttributes mattrs;
+
                        if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
-                               MethodInfo[] parent_methods = parent.GetMethods (bindingAttr);
-                               if (methods == null)
-                                       candidates = parent_methods;
-                               else {
-                                       candidates = new MethodInfo [methods.Length + parent_methods.Length];
-                                       parent_methods.CopyTo (candidates, 0);
-                                       methods.CopyTo (candidates, parent_methods.Length);
+                               MethodInfo [] parent_methods = parent.GetMethods (bindingAttr);
+                               ArrayList parent_candidates = new ArrayList (parent_methods.Length);
+
+                               bool flatten = (bindingAttr & BindingFlags.FlattenHierarchy) != 0;
+
+                               for (int i = 0; i < parent_methods.Length; i++) {
+                                       MethodInfo m = parent_methods [i];
+
+                                       mattrs = m.Attributes;
+
+                                       if (m.IsStatic && !flatten)
+                                               continue;
+
+                                       switch (mattrs & MethodAttributes.MemberAccessMask) {
+                                       case MethodAttributes.Public:
+                                               match = (bindingAttr & BindingFlags.Public) != 0;
+                                               break;
+                                       case MethodAttributes.Assembly:
+                                               match = (bindingAttr & BindingFlags.NonPublic) != 0;
+                                               break;
+                                       case MethodAttributes.Private:
+                                               match = false;
+                                               break;
+                                       default:
+                                               match = (bindingAttr & BindingFlags.NonPublic) != 0;
+                                               break;
+                                       }
+
+                                       if (match)
+                                               parent_candidates.Add (m);
+                               }
+
+                               if (methods == null) {
+                                       candidates = new MethodInfo [parent_candidates.Count];
+                                       parent_candidates.CopyTo (candidates);
+                               } else {
+                                       candidates = new MethodInfo [methods.Length + parent_candidates.Count];
+                                       parent_candidates.CopyTo (candidates, 0);
+                                       methods.CopyTo (candidates, parent_candidates.Count);
                                }
                        }
                        else
@@ -984,8 +1121,6 @@ namespace System.Reflection.Emit {
                                return new MethodInfo [0];
 
                        ArrayList l = new ArrayList ();
-                       bool match;
-                       MethodAttributes mattrs;
 
                        foreach (MethodInfo c in candidates) {
                                if (c == null)
@@ -1023,7 +1158,8 @@ namespace System.Reflection.Emit {
                        return result;
                }
 
-               public override MethodInfo[] GetMethods (BindingFlags bindingAttr) {
+               public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
+               {
                        return GetMethodsByName (null, bindingAttr, false, this);
                }
 
@@ -1076,12 +1212,35 @@ namespace System.Reflection.Emit {
                        return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
                }
 
-               public override Type GetNestedType( string name, BindingFlags bindingAttr) {
+               public override Type GetNestedType (string name, BindingFlags bindingAttr)
+               {
                        check_created ();
-                       return created.GetNestedType (name, bindingAttr);
+
+                       if (subtypes == null)
+                               return null;
+
+                       foreach (TypeBuilder t in subtypes) {
+                               if (!t.is_created)
+                                       continue;
+                               if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
+                                       if ((bindingAttr & BindingFlags.Public) == 0)
+                                               continue;
+                               } else {
+                                       if ((bindingAttr & BindingFlags.NonPublic) == 0)
+                                               continue;
+                               }
+                               if (t.Name == name)
+                                       return t.created;
+                       }
+
+                       return null;
                }
 
-               public override Type[] GetNestedTypes (BindingFlags bindingAttr) {
+               public override Type[] GetNestedTypes (BindingFlags bindingAttr)
+               {
+                       if (!is_created && !IsCompilerContext)
+                               throw new NotSupportedException ();
+
                        bool match;
                        ArrayList result = new ArrayList ();
 
@@ -1105,7 +1264,11 @@ namespace System.Reflection.Emit {
                        return r;
                }
 
-               public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) {
+               public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
+               {
+                       if (is_created)
+                               return created.GetProperties (bindingAttr);
+
                        if (properties == null)
                                return new PropertyInfo [0];
                        ArrayList l = new ArrayList ();
@@ -1147,54 +1310,127 @@ namespace System.Reflection.Emit {
                        return result;
                }
                
-               protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
+               protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
+               {
                        throw not_supported ();
                }
 
-               protected override bool HasElementTypeImpl () {
-                       check_created ();
+               protected override bool HasElementTypeImpl ()
+               {
+                       // a TypeBuilder can never represent an array, pointer
+                       if (!is_created)
+                               return false;
+
                        return created.HasElementType;
                }
 
-               public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
+               public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
+               {
                        check_created ();
                        return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
                }
 
                protected override bool IsArrayImpl ()
                {
-                       return Type.IsArrayImpl (this);
+                       return false; /*A TypeBuilder never represents a non typedef type.*/
                }
 
-               protected override bool IsByRefImpl () {
-                       // FIXME
-                       return false;
+               protected override bool IsByRefImpl ()
+               {
+                       return false; /*A TypeBuilder never represents a non typedef type.*/
                }
-               protected override bool IsCOMObjectImpl () {
-                       return false;
+
+               protected override bool IsCOMObjectImpl ()
+               {
+                       return ((GetAttributeFlagsImpl () & TypeAttributes.Import) != 0);
                }
-               protected override bool IsPointerImpl () {
-                       // FIXME
-                       return false;
+
+               protected override bool IsPointerImpl ()
+               {
+                       return false; /*A TypeBuilder never represents a non typedef type.*/
                }
-               protected override bool IsPrimitiveImpl () {
+
+               protected override bool IsPrimitiveImpl ()
+               {
                        // FIXME
                        return false;
                }
-               protected override bool IsValueTypeImpl () {
-                       return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
-                               this != pmodule.assemblyb.corlib_value_type &&
-                               this != pmodule.assemblyb.corlib_enum_type);
+
+               // FIXME: I doubt just removing this still works.
+               protected override bool IsValueTypeImpl ()
+               {
+                       if (this == pmodule.assemblyb.corlib_value_type || this == pmodule.assemblyb.corlib_enum_type)
+                               return false;
+                       Type parent_type = parent;
+                       while (parent_type != null) {
+                               if (parent_type == pmodule.assemblyb.corlib_value_type)
+                                       return true;
+                               parent_type = parent_type.BaseType;
+                       }
+                       return false;
                }
                
-               public override RuntimeTypeHandle TypeHandle { 
-                       get { 
+               public override Type MakeArrayType ()
+               {
+                       return new ArrayType (this, 0);
+               }
+
+               public override Type MakeArrayType (int rank)
+               {
+                       if (rank < 1)
+                               throw new IndexOutOfRangeException ();
+                       return new ArrayType (this, rank);
+               }
+
+               public override Type MakeByRefType ()
+               {
+                       return new ByRefType (this);
+               }
+
+               public override Type MakeGenericType (params Type [] typeArguments)
+               {
+                       //return base.MakeGenericType (typeArguments);
+
+                       if (!IsGenericTypeDefinition)
+                               throw new InvalidOperationException ("not a generic type definition");
+                       if (typeArguments == null)
+                               throw new ArgumentNullException ("typeArguments");
+
+                       if (generic_params.Length != typeArguments.Length)
+                               throw new ArgumentException (String.Format ("The type or method has {0} generic parameter(s) but {1} generic argument(s) where provided. A generic argument must be provided for each generic parameter.", generic_params.Length, typeArguments.Length), "typeArguments");
+
+                       foreach (Type t in typeArguments) {
+                               if (t == null)
+                                       throw new ArgumentNullException ("typeArguments");                              
+                       }
+
+                       Type[] copy = new Type [typeArguments.Length];
+                       typeArguments.CopyTo (copy, 0);
+                       return pmodule.assemblyb.MakeGenericType (this, copy);
+               }
+
+               public override Type MakePointerType ()
+               {
+                       return new PointerType (this);
+               }
+
+               public override RuntimeTypeHandle TypeHandle {
+                       get {
                                check_created ();
                                return created.TypeHandle;
-                       } 
+                       }
+               }
+               
+               //
+               // Used internally by mcs only
+               //
+               internal void SetCharSet (TypeAttributes ta)
+               {
+                       this.attrs = ta;
                }
 
-               public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
+               public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
+               {
                        if (customBuilder == null)
                                throw new ArgumentNullException ("customBuilder");
 
@@ -1279,17 +1515,17 @@ namespace System.Reflection.Emit {
                                        }
                                }
                                return;
-#if NET_2_0
                        } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
                                attrs |= TypeAttributes.SpecialName;
                                return;
-#endif
                        } else if (attrname == "System.SerializableAttribute") {
                                attrs |= TypeAttributes.Serializable;
                                return;
                        } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
                                attrs |= TypeAttributes.Import;
                                return;
+                       } else if (attrname == "System.Security.SuppressUnmanagedCodeSecurityAttribute") {
+                               attrs |= TypeAttributes.HasSecurity;
                        }
 
                        if (cattrs != null) {
@@ -1303,17 +1539,17 @@ namespace System.Reflection.Emit {
                        }
                }
 
-#if NET_2_0
                [ComVisible (true)]
-#endif
-               public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
+               public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
+               {
                        SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
                }
 
-               public EventBuilder DefineEvent( string name, EventAttributes attributes, Type eventtype) {
+               public EventBuilder DefineEvent (string name, EventAttributes attributes, Type eventtype)
+               {
                        check_name ("name", name);
                        if (eventtype == null)
-                               throw new ArgumentNullException ("eventtype");
+                               throw new ArgumentNullException ("type");
                        check_not_created ();
 
                        EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
@@ -1329,32 +1565,34 @@ namespace System.Reflection.Emit {
                        return res;
                }
 
-               public FieldBuilder DefineInitializedDatastring name, byte[] data, FieldAttributes attributes) {
+               public FieldBuilder DefineInitializedData (string name, byte[] data, FieldAttributes attributes) {
                        if (data == null)
                                throw new ArgumentNullException ("data");
-                       if ((data.Length == 0) || (data.Length > 0x3f0000))
-                               throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
 
                        FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
                        res.SetRVAData (data);
-
                        return res;
                }
 
-               static int UnmanagedDataCount = 0;
-               
-               public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
-                       check_name ("name", name);
+               public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
+               {
+                       if (name == null)
+                               throw new ArgumentNullException ("name");
+                       if (name.Length == 0)
+                               throw new ArgumentException ("Empty name is not legal", "name");
                        if ((size <= 0) || (size > 0x3f0000))
-                               throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
+                               throw new ArgumentException ("Data size must be > 0 and < 0x3f0000");
                        check_not_created ();
 
-                       string s = "$ArrayType$"+UnmanagedDataCount.ToString();
-                       UnmanagedDataCount++;
-                       TypeBuilder datablobtype = DefineNestedType (s,
-                               TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
-                               pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
-                       datablobtype.CreateType ();
+                       string typeName = "$ArrayType$" + size;
+                       Type datablobtype = pmodule.GetRegisteredType (fullname + "+" + typeName);
+                       if (datablobtype == null) {
+                               TypeBuilder tb = DefineNestedType (typeName,
+                                       TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
+                                       pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
+                               tb.CreateType ();
+                               datablobtype = tb;
+                       }
                        return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
                }
 
@@ -1363,23 +1601,32 @@ namespace System.Reflection.Emit {
                                return new TypeToken (0x02000000 | table_idx);
                        }
                }
-               public void SetParent (Type parentType) {
+
+               public void SetParent (Type parent)
+               {
                        check_not_created ();
 
-                       if (parentType == null && (attrs & TypeAttributes.Interface) == 0)
-                               throw new ArgumentNullException ("parentType");
-                       
-                       parent = parentType;
+                       if (parent == null) {
+                               if ((attrs & TypeAttributes.Interface) != 0) {
+                                       if ((attrs & TypeAttributes.Abstract) == 0)
+                                               throw new InvalidOperationException ("Interface must be declared abstract.");
+                                       this.parent = null;
+                               } else {
+                                       this.parent = typeof (object);
+                               }
+                       } else {
+                               this.parent = parent;
+                       }
+
                        // will just set the parent-related bits if called a second time
                        setup_internal_class (this);
                }
+
                internal int get_next_table_index (object obj, int table, bool inc) {
                        return pmodule.get_next_table_index (obj, table, inc);
                }
 
-#if NET_2_0
                [ComVisible (true)]
-#endif
                public override InterfaceMapping GetInterfaceMap (Type interfaceType)
                {
                        if (created == null)
@@ -1388,9 +1635,21 @@ namespace System.Reflection.Emit {
                        return created.GetInterfaceMap (interfaceType);
                }
 
+               internal override bool IsCompilerContext {
+                       get {
+                               return pmodule.assemblyb.IsCompilerContext;
+                       }
+               }
+
+               internal override Type InternalResolve ()
+               {
+                       check_created ();
+                       return created;
+               }
+
                internal bool is_created {
                        get {
-                               return created != null;
+                               return createTypeCalled;
                        }
                }
 
@@ -1417,7 +1676,7 @@ namespace System.Reflection.Emit {
                                throw new ArgumentNullException (argName);
                        if (name.Length == 0)
                                throw new ArgumentException ("Empty name is not legal", argName);
-                       if (name.IndexOf ((char)0) != -1)
+                       if (name [0] == ((char)0))
                                throw new ArgumentException ("Illegal name", argName);
                }
 
@@ -1432,15 +1691,6 @@ namespace System.Reflection.Emit {
                        return base.IsAssignableFrom (c);
                }
 
-#if NET_2_0
-               [ComVisible (true)]
-#endif
-               [MonoTODO]
-               public override bool IsSubclassOf (Type c)
-               {
-                       return base.IsSubclassOf (c);
-               }
-
                [MonoTODO ("arrays")]
                internal bool IsAssignableTo (Type c)
                {
@@ -1448,12 +1698,18 @@ namespace System.Reflection.Emit {
                                return true;
 
                        if (c.IsInterface) {
+                               if (parent != null && is_created) {
+                                       if (c.IsAssignableFrom (parent))
+                                               return true;
+                               }
+
                                if (interfaces == null)
                                        return false;
                                foreach (Type t in interfaces)
                                        if (c.IsAssignableFrom (t))
                                                return true;
-                               return false;
+                               if (!is_created)
+                                       return false;
                        }
 
                        if (parent == null)
@@ -1462,24 +1718,25 @@ namespace System.Reflection.Emit {
                                return c.IsAssignableFrom (parent);
                }
 
-#if NET_2_0 || BOOTSTRAP_NET_2_0
-               public bool IsCreated () {
+               public bool IsCreated ()
+               {
                        return is_created;
                }
 
                public override Type[] GetGenericArguments ()
                {
-                       if (generic_params != null)
-                               return generic_params;
-
-                       throw new InvalidOperationException ();
+                       if (generic_params == null)
+                               return null;
+                       Type[] args = new Type [generic_params.Length];
+                       generic_params.CopyTo (args, 0);
+                       return args;
                }
 
                public override Type GetGenericTypeDefinition ()
                {
-                       create_generic_class ();
-
-                       return base.GetGenericTypeDefinition ();
+                       if (generic_params == null)
+                               throw new InvalidOperationException ("Type is not generic");
+                       return this;
                }
 
                public override bool ContainsGenericParameters {
@@ -1493,6 +1750,10 @@ namespace System.Reflection.Emit {
                        get;
                }
 
+               public override GenericParameterAttributes GenericParameterAttributes {
+                       get { return GenericParameterAttributes.None; }
+               }
+
                public override bool IsGenericTypeDefinition {
                        get {
                                return generic_params != null;
@@ -1503,76 +1764,142 @@ namespace System.Reflection.Emit {
                        get { return IsGenericTypeDefinition; }
                }
 
+               [MonoTODO]
                public override int GenericParameterPosition {
                        get {
-                               throw new NotImplementedException ();
+                               return 0;
                        }
                }
 
                public override MethodBase DeclaringMethod {
                        get {
-                               throw new NotImplementedException ();
+                               return null;
                        }
                }
 
                public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
                {
+                       if (names == null)
+                               throw new ArgumentNullException ("names");
+                       if (names.Length == 0)
+                               throw new ArgumentException ("names");
+
                        setup_generic_class ();
 
                        generic_params = new GenericTypeParameterBuilder [names.Length];
-                       for (int i = 0; i < names.Length; i++)
-                               generic_params [i] = new GenericTypeParameterBuilder (
-                                       this, null, names [i], i);
+                       for (int i = 0; i < names.Length; i++) {
+                               string item = names [i];
+                               if (item == null)
+                                       throw new ArgumentNullException ("names");
+                               generic_params [i] = new GenericTypeParameterBuilder (this, null, item, i);
+                       }
 
                        return generic_params;
                }
 
-                public static ConstructorInfo GetConstructor (Type instanciated, ConstructorInfo ctor)
-                {
-                       ConstructorInfo res = instanciated.GetConstructor (ctor);
+               public static ConstructorInfo GetConstructor (Type type, ConstructorInfo constructor)
+               {
+                       /*FIXME I would expect the same checks of GetMethod here*/
+                       if (type == null)
+                               throw new ArgumentException ("Type is not generic", "type");
+
+                       if (!type.IsGenericType)
+                               throw new ArgumentException ("Type is not a generic type", "type");
+
+                       if (type.IsGenericTypeDefinition)
+                               throw new ArgumentException ("Type cannot be a generic type definition", "type");
+
+                       if (constructor == null)
+                               throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException
+
+                       ConstructorInfo res = type.GetConstructor (constructor);
                        if (res == null)
-                               throw new System.Exception ("constructor not found");
-                       else
-                               return res;
-                }
+                               throw new ArgumentException ("constructor not found");
+
+                       return res;
+               }
+
+               static bool IsValidGetMethodType (Type type)
+               {
+                       if (type is TypeBuilder || type is MonoGenericClass)
+                               return true;
+                       /*GetMethod() must work with TypeBuilders after CreateType() was called.*/
+                       if (type.Module is ModuleBuilder)
+                               return true;
+                       if (type.IsGenericParameter)
+                               return false;
+
+                       Type[] inst = type.GetGenericArguments ();
+                       if (inst == null)
+                               return false;
+                       for (int i = 0; i < inst.Length; ++i) {
+                               if (IsValidGetMethodType (inst [i]))
+                                       return true;
+                       }
+                       return false;
+               }
+
+               public static MethodInfo GetMethod (Type type, MethodInfo method)
+               {
+                       if (!IsValidGetMethodType (type))
+                               throw new ArgumentException ("type is not TypeBuilder but " + type.GetType (), "type");
+
+                       if (type is TypeBuilder && type.ContainsGenericParameters)
+                               type = type.MakeGenericType (type.GetGenericArguments ());
+
+                       if (!type.IsGenericType)
+                               throw new ArgumentException ("type is not a generic type", "type");
+
+                       if (!method.DeclaringType.IsGenericTypeDefinition)
+                               throw new ArgumentException ("method declaring type is not a generic type definition", "method");
+                       if (method.DeclaringType != type.GetGenericTypeDefinition ())
+                               throw new ArgumentException ("method declaring type is not the generic type definition of type", "method");
+                       if (method == null)
+                               throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException
 
-                public static MethodInfo GetMethod (Type instanciated, MethodInfo meth)
-                {
-                       MethodInfo res = instanciated.GetMethod (meth);
+                       MethodInfo res = type.GetMethod (method);
                        if (res == null)
-                               throw new System.Exception ("method not found");
-                       else
-                               return res;
-                }
+                               throw new ArgumentException (String.Format ("method {0} not found in type {1}", method.Name, type));
+                               
+                       return res;
+               }
 
-                public static FieldInfo GetField (Type instanciated, FieldInfo fld)
-                {
-                       FieldInfo res = instanciated.GetField (fld);
+               public static FieldInfo GetField (Type type, FieldInfo field)
+               {
+                       if (!type.IsGenericType)
+                               throw new ArgumentException ("Type is not a generic type", "type");
+
+                       if (type.IsGenericTypeDefinition)
+                               throw new ArgumentException ("Type cannot be a generic type definition", "type");
+
+                       if (field is FieldOnTypeBuilderInst)
+                               throw new ArgumentException ("The specified field must be declared on a generic type definition.", "field");
+
+                       FieldInfo res = type.GetField (field);
                        if (res == null)
                                throw new System.Exception ("field not found");
                        else
                                return res;
-                }
-#endif
+               }
 
-                void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
-                {
-                        throw new NotImplementedException ();
-                }
-
-                void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
-                {
-                        throw new NotImplementedException ();
-                }
-
-                void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
-                {
-                        throw new NotImplementedException ();
-                }
-
-                void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
-                {
-                        throw new NotImplementedException ();
-                }
+               void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
+               {
+                       throw new NotImplementedException ();
+               }
        }
 }