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