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