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