New test.
[mono.git] / mcs / class / corlib / System.Reflection.Emit / TypeBuilder.cs
1 //
2 // System.Reflection.Emit.TypeBuilder.cs
3 //
4 // Author:
5 //   Paolo Molaro (lupus@ximian.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // (C) 2001 Ximian, Inc.  http://www.ximian.com
9 //
10
11 //
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System;
35 using System.Text;
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Globalization;
41 using System.Collections;
42 using System.Security;
43 using System.Security.Permissions;
44 using System.Diagnostics.SymbolStore;
45
46 namespace System.Reflection.Emit
47 {
48         [ComVisible (true)]
49         [ComDefaultInterface (typeof (_TypeBuilder))]
50         [ClassInterface (ClassInterfaceType.None)]
51         public sealed class TypeBuilder : Type, _TypeBuilder
52         {
53 #pragma warning disable 169             
54                 #region Sync with reflection.h
55                 private string tname;
56                 private string nspace;
57                 private Type parent;
58                 private Type nesting_type;
59                 internal Type[] interfaces;
60                 internal int num_methods;
61                 internal MethodBuilder[] methods;
62                 internal ConstructorBuilder[] ctors;
63                 internal PropertyBuilder[] properties;
64                 internal int num_fields;
65                 internal FieldBuilder[] fields;
66                 internal EventBuilder[] events;
67                 private CustomAttributeBuilder[] cattrs;
68                 internal TypeBuilder[] subtypes;
69                 internal TypeAttributes attrs;
70                 private int table_idx;
71                 private ModuleBuilder pmodule;
72                 private int class_size;
73                 private PackingSize packing_size;
74                 private IntPtr generic_container;
75                 private GenericTypeParameterBuilder[] generic_params;
76                 private RefEmitPermissionSet[] permissions;
77                 private Type created;
78                 #endregion
79 #pragma warning restore 169             
80                 
81                 string fullname;
82                 bool createTypeCalled;
83                 private Type underlying_type;
84
85                 public const int UnspecifiedTypeSize = 0;
86                 
87                 protected override TypeAttributes GetAttributeFlagsImpl ()
88                 {
89                         return attrs;
90                 }
91                 
92                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
93                 private extern void setup_internal_class (TypeBuilder tb);
94                 
95                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
96                 private extern void create_internal_class (TypeBuilder tb);
97                 
98                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
99                 private extern void setup_generic_class ();
100
101                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
102                 private extern void create_generic_class ();
103
104                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
105                 private extern EventInfo get_event_info (EventBuilder eb);
106
107                 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr, int table_idx)
108                 {
109                         this.parent = null;
110                         this.attrs = attr;
111                         this.class_size = UnspecifiedTypeSize;
112                         this.table_idx = table_idx;
113                         fullname = this.tname = table_idx == 1 ? "<Module>" : "type_" + table_idx.ToString ();
114                         this.nspace = String.Empty;
115                         pmodule = mb;
116                         setup_internal_class (this);
117                 }
118
119                 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type)
120                 {
121                         int sep_index;
122                         this.parent = parent;
123                         this.attrs = attr;
124                         this.class_size = type_size;
125                         this.packing_size = packing_size;
126                         this.nesting_type = nesting_type;
127
128                         check_name ("fullname", name);
129
130                         if (parent == null && (attr & TypeAttributes.Interface) != 0 && (attr & TypeAttributes.Abstract) == 0)
131                                 throw new InvalidOperationException ("Interface must be declared abstract.");
132
133                         sep_index = name.LastIndexOf('.');
134                         if (sep_index != -1) {
135                                 this.tname = name.Substring (sep_index + 1);
136                                 this.nspace = name.Substring (0, sep_index);
137                         } else {
138                                 this.tname = name;
139                                 this.nspace = String.Empty;
140                         }
141                         if (interfaces != null) {
142                                 this.interfaces = new Type[interfaces.Length];
143                                 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
144                         }
145                         pmodule = mb;
146
147                         if (((attr & TypeAttributes.Interface) == 0) && (parent == null) && !IsCompilerContext)
148                                 this.parent = typeof (object);
149
150                         // skip .<Module> ?
151                         table_idx = mb.get_next_table_index (this, 0x02, true);
152                         setup_internal_class (this);
153                         fullname = GetFullName ();
154                 }
155
156                 public override Assembly Assembly {
157                         get {return pmodule.Assembly;}
158                 }
159
160                 public override string AssemblyQualifiedName {
161                         get {
162                                 return fullname + ", " + Assembly.FullName;
163                         }
164                 }
165
166                 public override Type BaseType {
167                         get {
168                                 return parent;
169                         }
170                 }
171
172                 public override Type DeclaringType {
173                         get { return nesting_type; }
174                 }
175
176 /*              public override bool IsSubclassOf (Type c)
177                 {
178                         Type t;
179                         if (c == null)
180                                 return false;
181                         if (c == this)
182                                 return false;
183                         t = parent;
184                         while (t != null) {
185                                 if (c == t)
186                                         return true;
187                                 t = t.BaseType;
188                         }
189                         return false;
190                 }*/
191
192                 public override Type UnderlyingSystemType {
193                         get {
194                                 if (is_created)
195                                         return created.UnderlyingSystemType;
196
197                                 if (IsEnum && !IsCompilerContext) {
198                                         if (underlying_type != null)
199                                                 return underlying_type;
200                                         throw new InvalidOperationException (
201                                                 "Enumeration type is not defined.");
202                                 }
203
204                                 return this;
205                         }
206                 }
207
208                 string GetFullName ()
209                 {
210                         if (nesting_type != null)
211                                 return String.Concat (nesting_type.FullName, "+", tname);
212                         if ((nspace != null) && (nspace.Length > 0))
213                                 return String.Concat (nspace, ".", tname);
214                         return tname;
215                 }
216         
217                 public override string FullName {
218                         get {
219                                 return fullname;
220                         }
221                 }
222         
223                 public override Guid GUID {
224                         get {
225                                 check_created ();
226                                 return created.GUID;
227                         }
228                 }
229
230                 public override Module Module {
231                         get {return pmodule;}
232                 }
233
234                 public override string Name {
235                         get {return tname;}
236                 }
237
238                 public override string Namespace {
239                         get {return nspace;}
240                 }
241
242                 public PackingSize PackingSize {
243                         get {return packing_size;}
244                 }
245
246                 public int Size {
247                         get { return class_size; }
248                 }
249
250                 public override Type ReflectedType {
251                         get { return nesting_type; }
252                 }
253
254                 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
255                 {
256 #if !NET_2_1
257                         if (pset == null)
258                                 throw new ArgumentNullException ("pset");
259                         if ((action == SecurityAction.RequestMinimum) ||
260                                 (action == SecurityAction.RequestOptional) ||
261                                 (action == SecurityAction.RequestRefuse))
262                                 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
263
264                         check_not_created ();
265
266                         if (permissions != null) {
267                                 /* Check duplicate actions */
268                                 foreach (RefEmitPermissionSet set in permissions)
269                                         if (set.action == action)
270                                                 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
271
272                                 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
273                                 permissions.CopyTo (new_array, 0);
274                                 permissions = new_array;
275                         }
276                         else
277                                 permissions = new RefEmitPermissionSet [1];
278
279                         permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
280                         attrs |= TypeAttributes.HasSecurity;
281 #endif
282                 }
283
284                 [ComVisible (true)]
285                 public void AddInterfaceImplementation (Type interfaceType)
286                 {
287                         if (interfaceType == null)
288                                 throw new ArgumentNullException ("interfaceType");
289                         check_not_created ();
290
291                         if (interfaces != null) {
292                                 // Check for duplicates
293                                 foreach (Type t in interfaces)
294                                         if (t == interfaceType)
295                                                 return;
296
297                                 Type[] ifnew = new Type [interfaces.Length + 1];
298                                 interfaces.CopyTo (ifnew, 0);
299                                 ifnew [interfaces.Length] = interfaceType;
300                                 interfaces = ifnew;
301                         } else {
302                                 interfaces = new Type [1];
303                                 interfaces [0] = interfaceType;
304                         }
305                 }
306
307                 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
308                                                                        CallingConventions callConvention, Type[] types,
309                                                                        ParameterModifier[] modifiers)
310                 {
311                         check_created ();
312
313                         if (created == typeof (object)) {
314                                 /* 
315                                  * This happens when building corlib. Calling created.GetConstructor 
316                                  * would return constructors from the real mscorlib, instead of the
317                                  * newly built one.
318                                  */
319
320                                 if (ctors == null)
321                                         return null;
322  
323                                 ConstructorBuilder found = null;
324                                 int count = 0;
325                         
326                                 foreach (ConstructorBuilder cb in ctors) {
327                                         if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
328                                                 continue;
329                                         found = cb;
330                                         count++;
331                                 }
332
333                                 if (count == 0)
334                                         return null;
335                                 if (types == null) {
336                                         if (count > 1)
337                                                 throw new AmbiguousMatchException ();
338                                         return found;
339                                 }
340                                 MethodBase[] match = new MethodBase [count];
341                                 if (count == 1)
342                                         match [0] = found;
343                                 else {
344                                         count = 0;
345                                         foreach (ConstructorInfo m in ctors) {
346                                                 if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
347                                                         continue;
348                                                 match [count++] = m;
349                                         }
350                                 }
351                                 if (binder == null)
352                                         binder = Binder.DefaultBinder;
353                                 return (ConstructorInfo) binder.SelectMethod (bindingAttr, match,
354                                                                                                                           types, modifiers);
355                         }
356
357                         return created.GetConstructor (bindingAttr, binder, 
358                                 callConvention, types, modifiers);
359                 }
360
361                 public override bool IsDefined (Type attributeType, bool inherit)
362                 {
363                         if (!is_created && !IsCompilerContext)
364                                 throw new NotSupportedException ();
365                         /*
366                          * MS throws NotSupported here, but we can't because some corlib
367                          * classes make calls to IsDefined.
368                          */
369                         return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
370                 }
371                 
372                 public override object[] GetCustomAttributes(bool inherit)
373                 {
374                         check_created ();
375
376                         return created.GetCustomAttributes (inherit);
377                 }
378                 
379                 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
380                 {
381                         check_created ();
382
383                         return created.GetCustomAttributes (attributeType, inherit);
384                 }
385
386                 public TypeBuilder DefineNestedType (string name)
387                 {
388                         return DefineNestedType (name, TypeAttributes.NestedPrivate,
389                                 pmodule.assemblyb.corlib_object_type, null);
390                 }
391
392                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr)
393                 {
394                         return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
395                 }
396
397                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent)
398                 {
399                         return DefineNestedType (name, attr, parent, null);
400                 }
401
402                 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
403                                                       PackingSize packSize, int typeSize)
404                 {
405                         // Visibility must be NestedXXX
406                         /* This breaks mcs
407                         if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
408                                 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
409                                 throw new ArgumentException ("attr", "Bad type flags for nested type.");
410                         */
411                         if (interfaces != null)
412                                 foreach (Type iface in interfaces)
413                                         if (iface == null)
414                                                 throw new ArgumentNullException ("interfaces");
415
416                         TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packSize, typeSize, this);
417                         res.fullname = res.GetFullName ();
418                         pmodule.RegisterTypeName (res, res.fullname);
419                         if (subtypes != null) {
420                                 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
421                                 System.Array.Copy (subtypes, new_types, subtypes.Length);
422                                 new_types [subtypes.Length] = res;
423                                 subtypes = new_types;
424                         } else {
425                                 subtypes = new TypeBuilder [1];
426                                 subtypes [0] = res;
427                         }
428                         return res;
429                 }
430
431                 [ComVisible (true)]
432                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces)
433                 {
434                         return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
435                 }
436
437                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typeSize)
438                 {
439                         return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typeSize);
440                 }
441
442                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packSize)
443                 {
444                         return DefineNestedType (name, attr, parent, null, packSize, UnspecifiedTypeSize);
445                 }
446
447                 [ComVisible (true)]
448                 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
449                 {
450                         return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
451                 }
452
453                 [ComVisible (true)]
454                 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
455                 {
456                         check_not_created ();
457                         ConstructorBuilder cb = new ConstructorBuilder (this, attributes,
458                                 callingConvention, parameterTypes, requiredCustomModifiers,
459                                 optionalCustomModifiers);
460                         if (ctors != null) {
461                                 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
462                                 System.Array.Copy (ctors, new_ctors, ctors.Length);
463                                 new_ctors [ctors.Length] = cb;
464                                 ctors = new_ctors;
465                         } else {
466                                 ctors = new ConstructorBuilder [1];
467                                 ctors [0] = cb;
468                         }
469                         return cb;
470                 }
471
472                 [ComVisible (true)]
473                 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
474                 {
475                         Type parent_type;
476
477                         if (parent != null)
478                                 parent_type = parent;
479                         else
480                                 parent_type = pmodule.assemblyb.corlib_object_type;
481
482                         ConstructorInfo parent_constructor =
483                                 parent_type.GetConstructor (
484                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
485                                         null, Type.EmptyTypes, null);
486                         if (parent_constructor == null) {
487                                 throw new NotSupportedException ("Parent does"
488                                         + " not have a default constructor."
489                                         + " The default constructor must be"
490                                         + " explicitly defined.");
491                         }
492
493                         ConstructorBuilder cb = DefineConstructor (attributes, 
494                                 CallingConventions.Standard, Type.EmptyTypes);
495                         ILGenerator ig = cb.GetILGenerator ();
496                         ig.Emit (OpCodes.Ldarg_0);
497                         ig.Emit (OpCodes.Call, parent_constructor);
498                         ig.Emit (OpCodes.Ret);
499                         return cb;
500                 }
501
502                 private void append_method (MethodBuilder mb)
503                 {
504                         if (methods != null) {
505                                 if (methods.Length == num_methods) {
506                                         MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
507                                         System.Array.Copy (methods, new_methods, num_methods);
508                                         methods = new_methods;
509                                 }
510                         } else {
511                                 methods = new MethodBuilder [1];
512                         }
513                         methods [num_methods] = mb;
514                         num_methods ++;
515                 }
516
517                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
518                 {
519                         return DefineMethod (name, attributes, CallingConventions.Standard,
520                                 returnType, parameterTypes);
521                 }
522
523                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
524                 {
525                         return DefineMethod (name, attributes, callingConvention, returnType,
526                                 null, null, parameterTypes, null, null);
527                 }
528
529                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
530                 {
531                         check_name ("name", name);
532                         check_not_created ();
533                         if (IsInterface && (
534                                 !((attributes & MethodAttributes.Abstract) != 0) || 
535                                 !((attributes & MethodAttributes.Virtual) != 0)) &&
536                                 !(((attributes & MethodAttributes.Static) != 0)))
537                                 throw new ArgumentException ("Interface method must be abstract and virtual.");
538
539                         if (returnType == null)
540                                 returnType = pmodule.assemblyb.corlib_void_type;
541                         MethodBuilder res = new MethodBuilder (this, name, attributes, 
542                                 callingConvention, returnType,
543                                 returnTypeRequiredCustomModifiers,
544                                 returnTypeOptionalCustomModifiers, parameterTypes,
545                                 parameterTypeRequiredCustomModifiers,
546                                 parameterTypeOptionalCustomModifiers);
547                         append_method (res);
548                         return res;
549                 }
550
551                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
552                 {
553                         return DefinePInvokeMethod (name, dllName, entryName, attributes,
554                                 callingConvention, returnType, null, null, parameterTypes,
555                                 null, null, nativeCallConv, nativeCharSet);
556                 }
557
558                 public MethodBuilder DefinePInvokeMethod (
559                                                 string name, 
560                                                 string dllName, 
561                                                 string entryName, MethodAttributes attributes, 
562                                                 CallingConventions callingConvention, 
563                                                 Type returnType, 
564                                                 Type[] returnTypeRequiredCustomModifiers, 
565                                                 Type[] returnTypeOptionalCustomModifiers, 
566                                                 Type[] parameterTypes, 
567                                                 Type[][] parameterTypeRequiredCustomModifiers, 
568                                                 Type[][] parameterTypeOptionalCustomModifiers, 
569                                                 CallingConvention nativeCallConv, 
570                                                 CharSet nativeCharSet)
571                 {
572                         check_name ("name", name);
573                         check_name ("dllName", dllName);
574                         check_name ("entryName", entryName);
575                         if ((attributes & MethodAttributes.Abstract) != 0)
576                                 throw new ArgumentException ("PInvoke methods must be static and native and cannot be abstract.");
577                         if (IsInterface)
578                                 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
579                         check_not_created ();
580
581                         MethodBuilder res 
582                                 = new MethodBuilder (
583                                                 this, 
584                                                 name, 
585                                                 attributes, 
586                                                 callingConvention,
587                                                 returnType, 
588                                                 returnTypeRequiredCustomModifiers, 
589                                                 returnTypeOptionalCustomModifiers, 
590                                                 parameterTypes, 
591                                                 parameterTypeRequiredCustomModifiers, 
592                                                 parameterTypeOptionalCustomModifiers,
593                                                 dllName, 
594                                                 entryName, 
595                                                 nativeCallConv, 
596                                                 nativeCharSet);
597                         append_method (res);
598                         return res;
599                 }
600
601                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
602                         return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
603                                 nativeCallConv, nativeCharSet);
604                 }
605
606                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes)
607                 {
608                         return DefineMethod (name, attributes, CallingConventions.Standard);
609                 }
610
611                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention)
612                 {
613                         return DefineMethod (name, attributes, callingConvention, null, null);
614                 }
615
616                 public void DefineMethodOverride (MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
617                 {
618                         if (methodInfoBody == null)
619                                 throw new ArgumentNullException ("methodInfoBody");
620                         if (methodInfoDeclaration == null)
621                                 throw new ArgumentNullException ("methodInfoDeclaration");
622                         check_not_created ();
623                         if (methodInfoBody.DeclaringType != this)
624                                 throw new ArgumentException ("method body must belong to this type");
625
626                         if (methodInfoBody is MethodBuilder) {
627                                 MethodBuilder mb = (MethodBuilder)methodInfoBody;
628                                 mb.set_override (methodInfoDeclaration);
629                         }
630                 }
631
632                 public FieldBuilder DefineField (string fieldName, Type type, FieldAttributes attributes)
633                 {
634                         return DefineField (fieldName, type, null, null, attributes);
635                 }
636
637                 public FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
638                 {
639                         check_name ("fieldName", fieldName);
640                         if (type == typeof (void))
641                                 throw new ArgumentException ("Bad field type in defining field.");
642                         check_not_created ();
643
644                         FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomModifiers, optionalCustomModifiers);
645                         if (fields != null) {
646                                 if (fields.Length == num_fields) {
647                                         FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
648                                         System.Array.Copy (fields, new_fields, num_fields);
649                                         fields = new_fields;
650                                 }
651                                 fields [num_fields] = res;
652                                 num_fields ++;
653                         } else {
654                                 fields = new FieldBuilder [1];
655                                 fields [0] = res;
656                                 num_fields ++;
657                                 create_internal_class (this);
658                         }
659
660                         if (IsEnum && !IsCompilerContext) {
661                                 if (underlying_type == null && (attributes & FieldAttributes.Static) == 0)
662                                         underlying_type = type;
663                         }
664
665                         return res;
666                 }
667
668                 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
669                 {
670                         return DefineProperty (name, attributes, returnType, null, null, parameterTypes, null, null);
671                 }
672
673                 public  PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
674                 {
675                         check_name ("name", name);
676                         if (parameterTypes != null)
677                                 foreach (Type param in parameterTypes)
678                                         if (param == null)
679                                                 throw new ArgumentNullException ("parameterTypes");
680                         check_not_created ();
681
682                         PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
683
684                         if (properties != null) {
685                                 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
686                                 System.Array.Copy (properties, new_properties, properties.Length);
687                                 new_properties [properties.Length] = res;
688                                 properties = new_properties;
689                         } else {
690                                 properties = new PropertyBuilder [1];
691                                 properties [0] = res;
692                         }
693                         return res;
694                 }
695
696                 [ComVisible (true)]
697                 public ConstructorBuilder DefineTypeInitializer()
698                 {
699                         return DefineConstructor (MethodAttributes.Public |
700                                 MethodAttributes.Static | MethodAttributes.SpecialName |
701                                 MethodAttributes.RTSpecialName, CallingConventions.Standard,
702                                 null);
703                 }
704
705                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
706                 private extern Type create_runtime_class (TypeBuilder tb);
707
708                 private bool is_nested_in (Type t)
709                 {
710                         while (t != null) {
711                                 if (t == this)
712                                         return true;
713                                 else
714                                         t = t.DeclaringType;
715                         }
716                         return false;
717                 }
718
719                 // Return whenever this type has a ctor defined using DefineMethod ()
720                 private bool has_ctor_method () {
721                         MethodAttributes ctor_attrs = MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
722
723                         for (int i = 0; i < num_methods; ++i) {
724                                 MethodBuilder mb = (MethodBuilder)(methods[i]);
725
726                                 if (mb.Name == ConstructorInfo.ConstructorName && (mb.Attributes & ctor_attrs) == ctor_attrs)
727                                         return true;
728                         }
729
730                         return false;
731             }
732                 
733                 public Type CreateType()
734                 {
735                         /* handle nesting_type */
736                         if (createTypeCalled)
737                                 return created;
738
739                         if (!IsInterface && (parent == null) && (this != pmodule.assemblyb.corlib_object_type) && (FullName != "<Module>")) {
740                                 SetParent (pmodule.assemblyb.corlib_object_type);
741                         }
742
743                         create_generic_class ();
744
745                         // Fire TypeResolve events for fields whose type is an unfinished
746                         // value type.
747                         if (fields != null) {
748                                 foreach (FieldBuilder fb in fields) {
749                                         if (fb == null)
750                                                 continue;
751                                         Type ft = fb.FieldType;
752                                         if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
753                                                 TypeBuilder tb = (TypeBuilder)ft;
754                                                 if (!tb.is_created) {
755                                                         AppDomain.CurrentDomain.DoTypeResolve (tb);
756                                                         if (!tb.is_created) {
757                                                                 // FIXME: We should throw an exception here,
758                                                                 // but mcs expects that the type is created
759                                                                 // even if the exception is thrown
760                                                                 //throw new TypeLoadException ("Could not load type " + tb);
761                                                         }
762                                                 }
763                                         }
764                                 }
765                         }
766
767                         if ((parent != null) && parent.IsSealed)
768                                 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
769
770                         if (parent == pmodule.assemblyb.corlib_enum_type && methods != null)
771                                 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is an enum with methods.");
772
773                         if (methods != null) {
774                                 bool is_concrete = !IsAbstract;
775                                 for (int i = 0; i < num_methods; ++i) {
776                                         MethodBuilder mb = (MethodBuilder)(methods[i]);
777                                         if (is_concrete && mb.IsAbstract)
778                                                 throw new InvalidOperationException ("Type is concrete but has abstract method " + mb);
779                                         mb.check_override ();
780                                         mb.fixup ();
781                                 }
782                         }
783
784                         //
785                         // On classes, define a default constructor if not provided
786                         //
787                         if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") && 
788                                 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ())
789                                 DefineDefaultConstructor (MethodAttributes.Public);
790
791                         if (ctors != null){
792                                 foreach (ConstructorBuilder ctor in ctors) 
793                                         ctor.fixup ();
794                         }
795
796                         createTypeCalled = true;
797                         created = create_runtime_class (this);
798                         if (created != null)
799                                 return created;
800                         return this;
801                 }
802
803                 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
804                 {
805                         symbolWriter.OpenNamespace (this.Namespace);
806
807                         if (methods != null) {
808                                 for (int i = 0; i < num_methods; ++i) {
809                                         MethodBuilder metb = (MethodBuilder) methods[i]; 
810                                         metb.GenerateDebugInfo (symbolWriter);
811                                 }
812                         }
813
814                         if (ctors != null) {
815                                 foreach (ConstructorBuilder ctor in ctors)
816                                         ctor.GenerateDebugInfo (symbolWriter);
817                         }
818                         
819                         symbolWriter.CloseNamespace ();
820
821                         if (subtypes != null) {
822                                 for (int i = 0; i < subtypes.Length; ++i)
823                                         subtypes [i].GenerateDebugInfo (symbolWriter);
824                         }
825                 }
826
827                 [ComVisible (true)]
828                 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
829                 {
830                         if (is_created)
831                                 return created.GetConstructors (bindingAttr);
832
833                         if (!IsCompilerContext)
834                                 throw new NotSupportedException ();
835
836                         return GetConstructorsInternal (bindingAttr);
837                 }
838
839                 internal ConstructorInfo[] GetConstructorsInternal (BindingFlags bindingAttr)
840                 {
841                         if (ctors == null)
842                                 return new ConstructorInfo [0];
843                         ArrayList l = new ArrayList ();
844                         bool match;
845                         MethodAttributes mattrs;
846                         
847                         foreach (ConstructorBuilder c in ctors) {
848                                 match = false;
849                                 mattrs = c.Attributes;
850                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
851                                         if ((bindingAttr & BindingFlags.Public) != 0)
852                                                 match = true;
853                                 } else {
854                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
855                                                 match = true;
856                                 }
857                                 if (!match)
858                                         continue;
859                                 match = false;
860                                 if ((mattrs & MethodAttributes.Static) != 0) {
861                                         if ((bindingAttr & BindingFlags.Static) != 0)
862                                                 match = true;
863                                 } else {
864                                         if ((bindingAttr & BindingFlags.Instance) != 0)
865                                                 match = true;
866                                 }
867                                 if (!match)
868                                         continue;
869                                 l.Add (c);
870                         }
871                         ConstructorInfo[] result = new ConstructorInfo [l.Count];
872                         l.CopyTo (result);
873                         return result;
874                 }
875
876                 public override Type GetElementType ()
877                 {
878                         throw new NotSupportedException ();
879                 }
880
881                 public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
882                 {
883                         check_created ();
884                         return created.GetEvent (name, bindingAttr);
885                 }
886
887                 /* Needed to keep signature compatibility with MS.NET */
888                 public override EventInfo[] GetEvents ()
889                 {
890                         return GetEvents (DefaultBindingFlags);
891                 }
892
893                 public override EventInfo[] GetEvents (BindingFlags bindingAttr)
894                 {
895                         if (is_created)
896                                 return created.GetEvents (bindingAttr);
897                         if (!IsCompilerContext)
898                                 throw new NotSupportedException ();
899                         return new EventInfo [0]; /*FIXME shouldn't we return the events here?*/
900                 }
901
902                 // This is only used from MonoGenericInst.initialize().
903                 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
904                 {
905                         if (events == null)
906                                 return new EventInfo [0];
907                         ArrayList l = new ArrayList ();
908                         bool match;
909                         MethodAttributes mattrs;
910                         MethodInfo accessor;
911
912                         foreach (EventBuilder eb in events) {
913                                 if (eb == null)
914                                         continue;
915                                 EventInfo c = get_event_info (eb);
916                                 match = false;
917                                 accessor = c.GetAddMethod (true);
918                                 if (accessor == null)
919                                         accessor = c.GetRemoveMethod (true);
920                                 if (accessor == null)
921                                         continue;
922                                 mattrs = accessor.Attributes;
923                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
924                                         if ((bindingAttr & BindingFlags.Public) != 0)
925                                                 match = true;
926                                 } else {
927                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
928                                                 match = true;
929                                 }
930                                 if (!match)
931                                         continue;
932                                 match = false;
933                                 if ((mattrs & MethodAttributes.Static) != 0) {
934                                         if ((bindingAttr & BindingFlags.Static) != 0)
935                                                 match = true;
936                                 } else {
937                                         if ((bindingAttr & BindingFlags.Instance) != 0)
938                                                 match = true;
939                                 }
940                                 if (!match)
941                                         continue;
942                                 l.Add (c);
943                         }
944                         EventInfo[] result = new EventInfo [l.Count];
945                         l.CopyTo (result);
946                         return result;
947                 }
948
949                 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
950                 {
951                         if (created != null)
952                                 return created.GetField (name, bindingAttr);
953
954                         if (fields == null)
955                                 return null;
956
957                         bool match;
958                         FieldAttributes mattrs;
959                         
960                         foreach (FieldInfo c in fields) {
961                                 if (c == null)
962                                         continue;
963                                 if (c.Name != name)
964                                         continue;
965                                 match = false;
966                                 mattrs = c.Attributes;
967                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
968                                         if ((bindingAttr & BindingFlags.Public) != 0)
969                                                 match = true;
970                                 } else {
971                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
972                                                 match = true;
973                                 }
974                                 if (!match)
975                                         continue;
976                                 match = false;
977                                 if ((mattrs & FieldAttributes.Static) != 0) {
978                                         if ((bindingAttr & BindingFlags.Static) != 0)
979                                                 match = true;
980                                 } else {
981                                         if ((bindingAttr & BindingFlags.Instance) != 0)
982                                                 match = true;
983                                 }
984                                 if (!match)
985                                         continue;
986                                 return c;
987                         }
988                         return null;
989                 }
990
991                 public override FieldInfo[] GetFields (BindingFlags bindingAttr)
992                 {
993                         if (created != null)
994                                 return created.GetFields (bindingAttr);
995
996                         if (fields == null)
997                                 return new FieldInfo [0];
998                         ArrayList l = new ArrayList ();
999                         bool match;
1000                         FieldAttributes mattrs;
1001                         
1002                         foreach (FieldInfo c in fields) {
1003                                 if (c == null)
1004                                         continue;
1005                                 match = false;
1006                                 mattrs = c.Attributes;
1007                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
1008                                         if ((bindingAttr & BindingFlags.Public) != 0)
1009                                                 match = true;
1010                                 } else {
1011                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1012                                                 match = true;
1013                                 }
1014                                 if (!match)
1015                                         continue;
1016                                 match = false;
1017                                 if ((mattrs & FieldAttributes.Static) != 0) {
1018                                         if ((bindingAttr & BindingFlags.Static) != 0)
1019                                                 match = true;
1020                                 } else {
1021                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1022                                                 match = true;
1023                                 }
1024                                 if (!match)
1025                                         continue;
1026                                 l.Add (c);
1027                         }
1028                         FieldInfo[] result = new FieldInfo [l.Count];
1029                         l.CopyTo (result);
1030                         return result;
1031                 }
1032
1033                 public override Type GetInterface (string name, bool ignoreCase)
1034                 {
1035                         check_created ();
1036                         return created.GetInterface (name, ignoreCase);
1037                 }
1038                 
1039                 public override Type[] GetInterfaces ()
1040                 {
1041                         if (is_created)
1042                                 return created.GetInterfaces ();
1043
1044                         if (interfaces != null) {
1045                                 Type[] ret = new Type [interfaces.Length];
1046                                 interfaces.CopyTo (ret, 0);
1047                                 return ret;
1048                         } else {
1049                                 return Type.EmptyTypes;
1050                         }
1051                 }
1052
1053                 public override MemberInfo[] GetMember (string name, MemberTypes type,
1054                                                                                                 BindingFlags bindingAttr)
1055                 {
1056                         check_created ();
1057                         return created.GetMember (name, type, bindingAttr);
1058                 }
1059
1060                 public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
1061                 {
1062                         check_created ();
1063                         return created.GetMembers (bindingAttr);
1064                 }
1065
1066                 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type)
1067                 {
1068                         MethodInfo[] candidates;
1069                         bool match;
1070                         MethodAttributes mattrs;
1071
1072                         if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
1073                                 MethodInfo [] parent_methods = parent.GetMethods (bindingAttr);
1074                                 ArrayList parent_candidates = new ArrayList (parent_methods.Length);
1075
1076                                 bool flatten = (bindingAttr & BindingFlags.FlattenHierarchy) != 0;
1077
1078                                 for (int i = 0; i < parent_methods.Length; i++) {
1079                                         MethodInfo m = parent_methods [i];
1080
1081                                         mattrs = m.Attributes;
1082
1083                                         if (m.IsStatic && !flatten)
1084                                                 continue;
1085
1086                                         switch (mattrs & MethodAttributes.MemberAccessMask) {
1087                                         case MethodAttributes.Public:
1088                                                 match = (bindingAttr & BindingFlags.Public) != 0;
1089                                                 break;
1090                                         case MethodAttributes.Assembly:
1091                                                 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1092                                                 break;
1093                                         case MethodAttributes.Private:
1094                                                 match = false;
1095                                                 break;
1096                                         default:
1097                                                 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1098                                                 break;
1099                                         }
1100
1101                                         if (match)
1102                                                 parent_candidates.Add (m);
1103                                 }
1104
1105                                 if (methods == null) {
1106                                         candidates = new MethodInfo [parent_candidates.Count];
1107                                         parent_candidates.CopyTo (candidates);
1108                                 } else {
1109                                         candidates = new MethodInfo [methods.Length + parent_candidates.Count];
1110                                         parent_candidates.CopyTo (candidates, 0);
1111                                         methods.CopyTo (candidates, parent_candidates.Count);
1112                                 }
1113                         }
1114                         else
1115                                 candidates = methods;
1116
1117                         if (candidates == null)
1118                                 return new MethodInfo [0];
1119
1120                         ArrayList l = new ArrayList ();
1121
1122                         foreach (MethodInfo c in candidates) {
1123                                 if (c == null)
1124                                         continue;
1125                                 if (name != null) {
1126                                         if (String.Compare (c.Name, name, ignoreCase) != 0)
1127                                                 continue;
1128                                 }
1129                                 match = false;
1130                                 mattrs = c.Attributes;
1131                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1132                                         if ((bindingAttr & BindingFlags.Public) != 0)
1133                                                 match = true;
1134                                 } else {
1135                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1136                                                 match = true;
1137                                 }
1138                                 if (!match)
1139                                         continue;
1140                                 match = false;
1141                                 if ((mattrs & MethodAttributes.Static) != 0) {
1142                                         if ((bindingAttr & BindingFlags.Static) != 0)
1143                                                 match = true;
1144                                 } else {
1145                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1146                                                 match = true;
1147                                 }
1148                                 if (!match)
1149                                         continue;
1150                                 l.Add (c);
1151                         }
1152
1153                         MethodInfo[] result = new MethodInfo [l.Count];
1154                         l.CopyTo (result);
1155                         return result;
1156                 }
1157
1158                 public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
1159                 {
1160                         return GetMethodsByName (null, bindingAttr, false, this);
1161                 }
1162
1163                 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
1164                                                              Binder binder,
1165                                                              CallingConventions callConvention,
1166                                                              Type[] types, ParameterModifier[] modifiers)
1167                 {
1168                         check_created ();
1169
1170                         bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
1171                         MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
1172                         MethodInfo found = null;
1173                         MethodBase[] match;
1174                         int typesLen = (types != null) ? types.Length : 0;
1175                         int count = 0;
1176                         
1177                         foreach (MethodInfo m in methods) {
1178                                 // Under MS.NET, Standard|HasThis matches Standard...
1179                                 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1180                                         continue;
1181                                 found = m;
1182                                 count++;
1183                         }
1184
1185                         if (count == 0)
1186                                 return null;
1187                         
1188                         if (count == 1 && typesLen == 0) 
1189                                 return found;
1190
1191                         match = new MethodBase [count];
1192                         if (count == 1)
1193                                 match [0] = found;
1194                         else {
1195                                 count = 0;
1196                                 foreach (MethodInfo m in methods) {
1197                                         if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1198                                                 continue;
1199                                         match [count++] = m;
1200                                 }
1201                         }
1202                         
1203                         if (types == null) 
1204                                 return (MethodInfo) Binder.FindMostDerivedMatch (match);
1205
1206                         if (binder == null)
1207                                 binder = Binder.DefaultBinder;
1208                         
1209                         return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
1210                 }
1211
1212                 public override Type GetNestedType (string name, BindingFlags bindingAttr)
1213                 {
1214                         check_created ();
1215
1216                         if (subtypes == null)
1217                                 return null;
1218
1219                         foreach (TypeBuilder t in subtypes) {
1220                                 if (!t.is_created)
1221                                         continue;
1222                                 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1223                                         if ((bindingAttr & BindingFlags.Public) == 0)
1224                                                 continue;
1225                                 } else {
1226                                         if ((bindingAttr & BindingFlags.NonPublic) == 0)
1227                                                 continue;
1228                                 }
1229                                 if (t.Name == name)
1230                                         return t.created;
1231                         }
1232
1233                         return null;
1234                 }
1235
1236                 public override Type[] GetNestedTypes (BindingFlags bindingAttr)
1237                 {
1238                         if (!is_created && !IsCompilerContext)
1239                                 throw new NotSupportedException ();
1240
1241                         bool match;
1242                         ArrayList result = new ArrayList ();
1243
1244                         if (subtypes == null)
1245                                 return Type.EmptyTypes;
1246                         foreach (TypeBuilder t in subtypes) {
1247                                 match = false;
1248                                 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1249                                         if ((bindingAttr & BindingFlags.Public) != 0)
1250                                                 match = true;
1251                                 } else {
1252                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1253                                                 match = true;
1254                                 }
1255                                 if (!match)
1256                                         continue;
1257                                 result.Add (t);
1258                         }
1259                         Type[] r = new Type [result.Count];
1260                         result.CopyTo (r);
1261                         return r;
1262                 }
1263
1264                 public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
1265                 {
1266                         if (is_created)
1267                                 return created.GetProperties (bindingAttr);
1268
1269                         if (properties == null)
1270                                 return new PropertyInfo [0];
1271                         ArrayList l = new ArrayList ();
1272                         bool match;
1273                         MethodAttributes mattrs;
1274                         MethodInfo accessor;
1275                         
1276                         foreach (PropertyInfo c in properties) {
1277                                 match = false;
1278                                 accessor = c.GetGetMethod (true);
1279                                 if (accessor == null)
1280                                         accessor = c.GetSetMethod (true);
1281                                 if (accessor == null)
1282                                         continue;
1283                                 mattrs = accessor.Attributes;
1284                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1285                                         if ((bindingAttr & BindingFlags.Public) != 0)
1286                                                 match = true;
1287                                 } else {
1288                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1289                                                 match = true;
1290                                 }
1291                                 if (!match)
1292                                         continue;
1293                                 match = false;
1294                                 if ((mattrs & MethodAttributes.Static) != 0) {
1295                                         if ((bindingAttr & BindingFlags.Static) != 0)
1296                                                 match = true;
1297                                 } else {
1298                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1299                                                 match = true;
1300                                 }
1301                                 if (!match)
1302                                         continue;
1303                                 l.Add (c);
1304                         }
1305                         PropertyInfo[] result = new PropertyInfo [l.Count];
1306                         l.CopyTo (result);
1307                         return result;
1308                 }
1309                 
1310                 protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
1311                 {
1312                         throw not_supported ();
1313                 }
1314
1315                 protected override bool HasElementTypeImpl ()
1316                 {
1317                         // a TypeBuilder can never represent an array, pointer
1318                         if (!is_created)
1319                                 return false;
1320
1321                         return created.HasElementType;
1322                 }
1323
1324                 public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
1325                 {
1326                         check_created ();
1327                         return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1328                 }
1329
1330                 protected override bool IsArrayImpl ()
1331                 {
1332                         return false; /*A TypeBuilder never represents a non typedef type.*/
1333                 }
1334
1335                 protected override bool IsByRefImpl ()
1336                 {
1337                         return false; /*A TypeBuilder never represents a non typedef type.*/
1338                 }
1339
1340                 protected override bool IsCOMObjectImpl ()
1341                 {
1342                         return ((GetAttributeFlagsImpl () & TypeAttributes.Import) != 0);
1343                 }
1344
1345                 protected override bool IsPointerImpl ()
1346                 {
1347                         return false; /*A TypeBuilder never represents a non typedef type.*/
1348                 }
1349
1350                 protected override bool IsPrimitiveImpl ()
1351                 {
1352                         // FIXME
1353                         return false;
1354                 }
1355
1356                 // FIXME: I doubt just removing this still works.
1357                 protected override bool IsValueTypeImpl ()
1358                 {
1359                         return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
1360                                 this != pmodule.assemblyb.corlib_value_type &&
1361                                 this != pmodule.assemblyb.corlib_enum_type);
1362                 }
1363                 
1364                 public override Type MakeArrayType ()
1365                 {
1366                         return new ArrayType (this, 0);
1367                 }
1368
1369                 public override Type MakeArrayType (int rank)
1370                 {
1371                         if (rank < 1)
1372                                 throw new IndexOutOfRangeException ();
1373                         return new ArrayType (this, rank);
1374                 }
1375
1376                 public override Type MakeByRefType ()
1377                 {
1378                         return new ByRefType (this);
1379                 }
1380
1381                 public override Type MakeGenericType (params Type [] typeArguments)
1382                 {
1383                         //return base.MakeGenericType (typeArguments);
1384
1385                         if (!IsGenericTypeDefinition)
1386                                 throw new InvalidOperationException ("not a generic type definition");
1387                         if (typeArguments == null)
1388                                 throw new ArgumentNullException ("typeArguments");
1389
1390                         if (generic_params.Length != typeArguments.Length)
1391                                 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");
1392
1393                         foreach (Type t in typeArguments) {
1394                                 if (t == null)
1395                                         throw new ArgumentNullException ("typeArguments");                              
1396                         }
1397
1398                         Type[] copy = new Type [typeArguments.Length];
1399                         typeArguments.CopyTo (copy, 0);
1400                         return pmodule.assemblyb.MakeGenericType (this, copy);
1401                 }
1402
1403                 public override Type MakePointerType ()
1404                 {
1405                         return new PointerType (this);
1406                 }
1407
1408                 public override RuntimeTypeHandle TypeHandle {
1409                         get {
1410                                 check_created ();
1411                                 return created.TypeHandle;
1412                         }
1413                 }
1414                 
1415                 //
1416                 // Used internally by mcs only
1417                 //
1418                 internal void SetCharSet (TypeAttributes ta)
1419                 {
1420                         this.attrs = ta;
1421                 }
1422
1423                 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
1424                 {
1425                         if (customBuilder == null)
1426                                 throw new ArgumentNullException ("customBuilder");
1427
1428                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
1429                         if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1430                                 byte[] data = customBuilder.Data;
1431                                 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1432                                 layout_kind = (int)data [2];
1433                                 layout_kind |= ((int)data [3]) << 8;
1434                                 attrs &= ~TypeAttributes.LayoutMask;
1435                                 switch ((LayoutKind)layout_kind) {
1436                                 case LayoutKind.Auto:
1437                                         attrs |= TypeAttributes.AutoLayout;
1438                                         break;
1439                                 case LayoutKind.Explicit:
1440                                         attrs |= TypeAttributes.ExplicitLayout;
1441                                         break;
1442                                 case LayoutKind.Sequential:
1443                                         attrs |= TypeAttributes.SequentialLayout;
1444                                         break;
1445                                 default:
1446                                         // we should ignore it since it can be any value anyway...
1447                                         throw new Exception ("Error in customattr");
1448                                 }
1449                                 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
1450                                 int pos = 6;
1451                                 if (first_type_name == "System.Int16")
1452                                         pos = 4;
1453                                 int nnamed = (int)data [pos++];
1454                                 nnamed |= ((int)data [pos++]) << 8;
1455                                 for (int i = 0; i < nnamed; ++i) {
1456                                         //byte named_type = data [pos++];
1457                                         pos ++;
1458                                         byte type = data [pos++];
1459                                         int len;
1460                                         string named_name;
1461
1462                                         if (type == 0x55) {
1463                                                 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1464                                                 //string named_typename = 
1465                                                 CustomAttributeBuilder.string_from_bytes (data, pos, len);
1466                                                 pos += len;
1467                                                 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1468                                                 //        See related code/FIXME in mono/mono/metadata/reflection.c
1469                                         }
1470
1471                                         len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1472                                         named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1473                                         pos += len;
1474                                         /* all the fields are integers in StructLayout */
1475                                         int value = (int)data [pos++];
1476                                         value |= ((int)data [pos++]) << 8;
1477                                         value |= ((int)data [pos++]) << 16;
1478                                         value |= ((int)data [pos++]) << 24;
1479                                         switch (named_name) {
1480                                         case "CharSet":
1481                                                 switch ((CharSet)value) {
1482                                                 case CharSet.None:
1483                                                 case CharSet.Ansi:
1484                                                         attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
1485                                                         break;
1486                                                 case CharSet.Unicode:
1487                                                         attrs &= ~TypeAttributes.AutoClass;
1488                                                         attrs |= TypeAttributes.UnicodeClass;
1489                                                         break;
1490                                                 case CharSet.Auto:
1491                                                         attrs &= ~TypeAttributes.UnicodeClass;
1492                                                         attrs |= TypeAttributes.AutoClass;
1493                                                         break;
1494                                                 default:
1495                                                         break; // error out...
1496                                                 }
1497                                                 break;
1498                                         case "Pack":
1499                                                 packing_size = (PackingSize)value;
1500                                                 break;
1501                                         case "Size":
1502                                                 class_size = value;
1503                                                 break;
1504                                         default:
1505                                                 break; // error out...
1506                                         }
1507                                 }
1508                                 return;
1509                         } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
1510                                 attrs |= TypeAttributes.SpecialName;
1511                                 return;
1512                         } else if (attrname == "System.SerializableAttribute") {
1513                                 attrs |= TypeAttributes.Serializable;
1514                                 return;
1515                         } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
1516                                 attrs |= TypeAttributes.Import;
1517                                 return;
1518                         } else if (attrname == "System.Security.SuppressUnmanagedCodeSecurityAttribute") {
1519                                 attrs |= TypeAttributes.HasSecurity;
1520                         }
1521
1522                         if (cattrs != null) {
1523                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1524                                 cattrs.CopyTo (new_array, 0);
1525                                 new_array [cattrs.Length] = customBuilder;
1526                                 cattrs = new_array;
1527                         } else {
1528                                 cattrs = new CustomAttributeBuilder [1];
1529                                 cattrs [0] = customBuilder;
1530                         }
1531                 }
1532
1533                 [ComVisible (true)]
1534                 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
1535                 {
1536                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1537                 }
1538
1539                 public EventBuilder DefineEvent (string name, EventAttributes attributes, Type eventtype)
1540                 {
1541                         check_name ("name", name);
1542                         if (eventtype == null)
1543                                 throw new ArgumentNullException ("type");
1544                         check_not_created ();
1545
1546                         EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1547                         if (events != null) {
1548                                 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1549                                 System.Array.Copy (events, new_events, events.Length);
1550                                 new_events [events.Length] = res;
1551                                 events = new_events;
1552                         } else {
1553                                 events = new EventBuilder [1];
1554                                 events [0] = res;
1555                         }
1556                         return res;
1557                 }
1558
1559                 public FieldBuilder DefineInitializedData (string name, byte[] data, FieldAttributes attributes) {
1560                         if (data == null)
1561                                 throw new ArgumentNullException ("data");
1562
1563                         FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1564                         res.SetRVAData (data);
1565                         return res;
1566                 }
1567
1568                 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
1569                 {
1570                         if (name == null)
1571                                 throw new ArgumentNullException ("name");
1572                         if (name.Length == 0)
1573                                 throw new ArgumentException ("Empty name is not legal", "name");
1574                         if ((size <= 0) || (size > 0x3f0000))
1575                                 throw new ArgumentException ("Data size must be > 0 and < 0x3f0000");
1576                         check_not_created ();
1577
1578                         string typeName = "$ArrayType$" + size;
1579                         Type datablobtype = pmodule.GetRegisteredType (fullname + "+" + typeName);
1580                         if (datablobtype == null) {
1581                                 TypeBuilder tb = DefineNestedType (typeName,
1582                                         TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1583                                         pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1584                                 tb.CreateType ();
1585                                 datablobtype = tb;
1586                         }
1587                         return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1588                 }
1589
1590                 public TypeToken TypeToken {
1591                         get {
1592                                 return new TypeToken (0x02000000 | table_idx);
1593                         }
1594                 }
1595
1596                 public void SetParent (Type parent)
1597                 {
1598                         check_not_created ();
1599
1600                         if (parent == null) {
1601                                 if ((attrs & TypeAttributes.Interface) != 0) {
1602                                         if ((attrs & TypeAttributes.Abstract) == 0)
1603                                                 throw new InvalidOperationException ("Interface must be declared abstract.");
1604                                         this.parent = null;
1605                                 } else {
1606                                         this.parent = typeof (object);
1607                                 }
1608                         } else {
1609                                 this.parent = parent;
1610                         }
1611
1612                         // will just set the parent-related bits if called a second time
1613                         setup_internal_class (this);
1614                 }
1615
1616                 internal int get_next_table_index (object obj, int table, bool inc) {
1617                         return pmodule.get_next_table_index (obj, table, inc);
1618                 }
1619
1620                 [ComVisible (true)]
1621                 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1622                 {
1623                         if (created == null)
1624                                 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1625
1626                         return created.GetInterfaceMap (interfaceType);
1627                 }
1628
1629                 internal override bool IsCompilerContext {
1630                         get {
1631                                 return pmodule.assemblyb.IsCompilerContext;
1632                         }
1633                 }
1634
1635                 internal bool is_created {
1636                         get {
1637                                 return created != null;
1638                         }
1639                 }
1640
1641                 private Exception not_supported ()
1642                 {
1643                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1644                 }
1645
1646                 private void check_not_created ()
1647                 {
1648                         if (is_created)
1649                                 throw new InvalidOperationException ("Unable to change after type has been created.");
1650                 }
1651
1652                 private void check_created ()
1653                 {
1654                         if (!is_created)
1655                                 throw not_supported ();
1656                 }
1657
1658                 private void check_name (string argName, string name)
1659                 {
1660                         if (name == null)
1661                                 throw new ArgumentNullException (argName);
1662                         if (name.Length == 0)
1663                                 throw new ArgumentException ("Empty name is not legal", argName);
1664                         if (name [0] == ((char)0))
1665                                 throw new ArgumentException ("Illegal name", argName);
1666                 }
1667
1668                 public override String ToString ()
1669                 {
1670                         return FullName;
1671                 }
1672
1673                 [MonoTODO]
1674                 public override bool IsAssignableFrom (Type c)
1675                 {
1676                         return base.IsAssignableFrom (c);
1677                 }
1678
1679                 [ComVisible (true)]
1680                 [MonoTODO]
1681                 public override bool IsSubclassOf (Type c)
1682                 {
1683                         return base.IsSubclassOf (c);
1684                 }
1685
1686                 [MonoTODO ("arrays")]
1687                 internal bool IsAssignableTo (Type c)
1688                 {
1689                         if (c == this)
1690                                 return true;
1691
1692                         if (c.IsInterface) {
1693                                 if (parent != null && is_created) {
1694                                         if (c.IsAssignableFrom (parent))
1695                                                 return true;
1696                                 }
1697
1698                                 if (interfaces == null)
1699                                         return false;
1700                                 foreach (Type t in interfaces)
1701                                         if (c.IsAssignableFrom (t))
1702                                                 return true;
1703                                 if (!is_created)
1704                                         return false;
1705                         }
1706
1707                         if (parent == null)
1708                                 return c == typeof (object);
1709                         else
1710                                 return c.IsAssignableFrom (parent);
1711                 }
1712
1713                 public bool IsCreated ()
1714                 {
1715                         return is_created;
1716                 }
1717
1718                 public override Type[] GetGenericArguments ()
1719                 {
1720                         if (generic_params == null)
1721                                 return null;
1722                         Type[] args = new Type [generic_params.Length];
1723                         generic_params.CopyTo (args, 0);
1724                         return args;
1725                 }
1726
1727                 public override Type GetGenericTypeDefinition ()
1728                 {
1729                         if (generic_params == null)
1730                                 throw new InvalidOperationException ("Type is not generic");
1731                         return this;
1732                 }
1733
1734                 public override bool ContainsGenericParameters {
1735                         get {
1736                                 return generic_params != null;
1737                         }
1738                 }
1739
1740                 public extern override bool IsGenericParameter {
1741                         [MethodImplAttribute(MethodImplOptions.InternalCall)]
1742                         get;
1743                 }
1744
1745                 public override GenericParameterAttributes GenericParameterAttributes {
1746                         get { return GenericParameterAttributes.None; }
1747                 }
1748
1749                 public override bool IsGenericTypeDefinition {
1750                         get {
1751                                 return generic_params != null;
1752                         }
1753                 }
1754
1755                 public override bool IsGenericType {
1756                         get { return IsGenericTypeDefinition; }
1757                 }
1758
1759                 [MonoTODO]
1760                 public override int GenericParameterPosition {
1761                         get {
1762                                 return 0;
1763                         }
1764                 }
1765
1766                 public override MethodBase DeclaringMethod {
1767                         get {
1768                                 return null;
1769                         }
1770                 }
1771
1772                 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1773                 {
1774                         if (names == null)
1775                                 throw new ArgumentNullException ("names");
1776                         if (names.Length == 0)
1777                                 throw new ArgumentException ("names");
1778
1779                         setup_generic_class ();
1780
1781                         generic_params = new GenericTypeParameterBuilder [names.Length];
1782                         for (int i = 0; i < names.Length; i++) {
1783                                 string item = names [i];
1784                                 if (item == null)
1785                                         throw new ArgumentNullException ("names");
1786                                 generic_params [i] = new GenericTypeParameterBuilder (this, null, item, i);
1787                         }
1788
1789                         return generic_params;
1790                 }
1791
1792                 public static ConstructorInfo GetConstructor (Type type, ConstructorInfo constructor)
1793                 {
1794                         /*FIXME I would expect the same checks of GetMethod here*/
1795                         if (type == null)
1796                                 throw new ArgumentException ("Type is not generic", "type");
1797
1798                         if (!type.IsGenericType)
1799                                 throw new ArgumentException ("Type is not a generic type", "type");
1800
1801                         if (type.IsGenericTypeDefinition)
1802                                 throw new ArgumentException ("Type cannot be a generic type definition", "type");
1803
1804                         if (constructor == null)
1805                                 throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException
1806
1807                         ConstructorInfo res = type.GetConstructor (constructor);
1808                         if (res == null)
1809                                 throw new ArgumentException ("constructor not found");
1810
1811                         return res;
1812                 }
1813
1814                 static bool IsValidGetMethodType (Type type)
1815                 {
1816                         if (type is TypeBuilder || type is MonoGenericClass)
1817                                 return true;
1818                         /*GetMethod() must work with TypeBuilders after CreateType() was called.*/
1819                         if (type.Module is ModuleBuilder)
1820                                 return true;
1821                         if (type.IsGenericParameter)
1822                                 return false;
1823
1824                         Type[] inst = type.GetGenericArguments ();
1825                         if (inst == null)
1826                                 return false;
1827                         for (int i = 0; i < inst.Length; ++i) {
1828                                 if (IsValidGetMethodType (inst [i]))
1829                                         return true;
1830                         }
1831                         return false;
1832                 }
1833
1834                 public static MethodInfo GetMethod (Type type, MethodInfo method)
1835                 {
1836                         if (!IsValidGetMethodType (type))
1837                                 throw new ArgumentException ("type is not TypeBuilder but " + type.GetType (), "type");
1838
1839                         if (type is TypeBuilder && type.ContainsGenericParameters)
1840                                 type = type.MakeGenericType (type.GetGenericArguments ());
1841
1842                         if (!type.IsGenericType)
1843                                 throw new ArgumentException ("type is not a generic type", "type");
1844
1845                         if (!method.DeclaringType.IsGenericTypeDefinition)
1846                                 throw new ArgumentException ("method declaring type is not a generic type definition", "method");
1847                         if (method.DeclaringType != type.GetGenericTypeDefinition ())
1848                                 throw new ArgumentException ("method declaring type is not the generic type definition of type", "method");
1849                         if (method == null)
1850                                 throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException
1851
1852                         MethodInfo res = type.GetMethod (method);
1853                         if (res == null)
1854                                 throw new ArgumentException (String.Format ("method {0} not found in type {1}", method.Name, type));
1855                                 
1856                         return res;
1857                 }
1858
1859                 public static FieldInfo GetField (Type type, FieldInfo field)
1860                 {
1861                         if (!type.IsGenericType)
1862                                 throw new ArgumentException ("Type is not a generic type", "type");
1863
1864                         if (type.IsGenericTypeDefinition)
1865                                 throw new ArgumentException ("Type cannot be a generic type definition", "type");
1866
1867                         FieldInfo res = type.GetField (field);
1868                         if (res == null)
1869                                 throw new System.Exception ("field not found");
1870                         else
1871                                 return res;
1872                 }
1873
1874                 void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1875                 {
1876                         throw new NotImplementedException ();
1877                 }
1878
1879                 void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1880                 {
1881                         throw new NotImplementedException ();
1882                 }
1883
1884                 void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
1885                 {
1886                         throw new NotImplementedException ();
1887                 }
1888
1889                 void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1890                 {
1891                         throw new NotImplementedException ();
1892                 }
1893         }
1894 }