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