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