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