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