Merge pull request #1909 from esdrubal/reflection
[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 = 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                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packSize,
452                                                      int typeSize)
453                 {
454                         return DefineNestedType (name, attr, parent, null, packSize, typeSize);
455                 }
456
457                 [ComVisible (true)]
458                 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
459                 {
460                         return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
461                 }
462
463                 [ComVisible (true)]
464                 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
465                 {
466                         check_not_created ();
467                         ConstructorBuilder cb = new ConstructorBuilder (this, attributes,
468                                 callingConvention, parameterTypes, requiredCustomModifiers,
469                                 optionalCustomModifiers);
470                         if (ctors != null) {
471                                 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
472                                 System.Array.Copy (ctors, new_ctors, ctors.Length);
473                                 new_ctors [ctors.Length] = cb;
474                                 ctors = new_ctors;
475                         } else {
476                                 ctors = new ConstructorBuilder [1];
477                                 ctors [0] = cb;
478                         }
479                         return cb;
480                 }
481
482                 [ComVisible (true)]
483                 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
484                 {
485                         Type parent_type, old_parent_type;
486
487                         if (parent != null)
488                                 parent_type = parent;
489                         else
490                                 parent_type = pmodule.assemblyb.corlib_object_type;
491
492                         old_parent_type = parent_type;
493                         parent_type = parent_type.InternalResolve ();
494                         /*This avoids corlib to have self references.*/
495                         if (parent_type == typeof (object) || parent_type == typeof (ValueType))
496                                 parent_type = old_parent_type;
497
498                         ConstructorInfo parent_constructor =
499                                 parent_type.GetConstructor (
500                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
501                                         null, Type.EmptyTypes, null);
502                         if (parent_constructor == null) {
503                                 throw new NotSupportedException ("Parent does"
504                                         + " not have a default constructor."
505                                         + " The default constructor must be"
506                                         + " explicitly defined.");
507                         }
508
509                         ConstructorBuilder cb = DefineConstructor (attributes, 
510                                 CallingConventions.Standard, Type.EmptyTypes);
511                         ILGenerator ig = cb.GetILGenerator ();
512                         ig.Emit (OpCodes.Ldarg_0);
513                         ig.Emit (OpCodes.Call, parent_constructor);
514                         ig.Emit (OpCodes.Ret);
515                         return cb;
516                 }
517
518                 private void append_method (MethodBuilder mb)
519                 {
520                         if (methods != null) {
521                                 if (methods.Length == num_methods) {
522                                         MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
523                                         System.Array.Copy (methods, new_methods, num_methods);
524                                         methods = new_methods;
525                                 }
526                         } else {
527                                 methods = new MethodBuilder [1];
528                         }
529                         methods [num_methods] = mb;
530                         num_methods ++;
531                 }
532
533                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
534                 {
535                         return DefineMethod (name, attributes, CallingConventions.Standard,
536                                 returnType, parameterTypes);
537                 }
538
539                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
540                 {
541                         return DefineMethod (name, attributes, callingConvention, returnType,
542                                 null, null, parameterTypes, null, null);
543                 }
544
545                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
546                 {
547                         check_name ("name", name);
548                         check_not_created ();
549                         if (IsInterface && (
550                                 !((attributes & MethodAttributes.Abstract) != 0) || 
551                                 !((attributes & MethodAttributes.Virtual) != 0)) &&
552                                 !(((attributes & MethodAttributes.Static) != 0)))
553                                 throw new ArgumentException ("Interface method must be abstract and virtual.");
554
555                         if (returnType == null)
556                                 returnType = pmodule.assemblyb.corlib_void_type;
557                         MethodBuilder res = new MethodBuilder (this, name, attributes, 
558                                 callingConvention, returnType,
559                                 returnTypeRequiredCustomModifiers,
560                                 returnTypeOptionalCustomModifiers, parameterTypes,
561                                 parameterTypeRequiredCustomModifiers,
562                                 parameterTypeOptionalCustomModifiers);
563                         append_method (res);
564                         return res;
565                 }
566
567                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
568                 {
569                         return DefinePInvokeMethod (name, dllName, entryName, attributes,
570                                 callingConvention, returnType, null, null, parameterTypes,
571                                 null, null, nativeCallConv, nativeCharSet);
572                 }
573
574                 public MethodBuilder DefinePInvokeMethod (
575                                                 string name, 
576                                                 string dllName, 
577                                                 string entryName, MethodAttributes attributes, 
578                                                 CallingConventions callingConvention, 
579                                                 Type returnType, 
580                                                 Type[] returnTypeRequiredCustomModifiers, 
581                                                 Type[] returnTypeOptionalCustomModifiers, 
582                                                 Type[] parameterTypes, 
583                                                 Type[][] parameterTypeRequiredCustomModifiers, 
584                                                 Type[][] parameterTypeOptionalCustomModifiers, 
585                                                 CallingConvention nativeCallConv, 
586                                                 CharSet nativeCharSet)
587                 {
588                         check_name ("name", name);
589                         check_name ("dllName", dllName);
590                         check_name ("entryName", entryName);
591                         if ((attributes & MethodAttributes.Abstract) != 0)
592                                 throw new ArgumentException ("PInvoke methods must be static and native and cannot be abstract.");
593                         if (IsInterface)
594                                 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
595                         check_not_created ();
596
597                         MethodBuilder res 
598                                 = new MethodBuilder (
599                                                 this, 
600                                                 name, 
601                                                 attributes, 
602                                                 callingConvention,
603                                                 returnType, 
604                                                 returnTypeRequiredCustomModifiers, 
605                                                 returnTypeOptionalCustomModifiers, 
606                                                 parameterTypes, 
607                                                 parameterTypeRequiredCustomModifiers, 
608                                                 parameterTypeOptionalCustomModifiers,
609                                                 dllName, 
610                                                 entryName, 
611                                                 nativeCallConv, 
612                                                 nativeCharSet);
613                         append_method (res);
614                         return res;
615                 }
616
617                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
618                         return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
619                                 nativeCallConv, nativeCharSet);
620                 }
621
622                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes)
623                 {
624                         return DefineMethod (name, attributes, CallingConventions.Standard);
625                 }
626
627                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention)
628                 {
629                         return DefineMethod (name, attributes, callingConvention, null, null);
630                 }
631
632                 public void DefineMethodOverride (MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
633                 {
634                         if (methodInfoBody == null)
635                                 throw new ArgumentNullException ("methodInfoBody");
636                         if (methodInfoDeclaration == null)
637                                 throw new ArgumentNullException ("methodInfoDeclaration");
638                         check_not_created ();
639                         if (methodInfoBody.DeclaringType != this)
640                                 throw new ArgumentException ("method body must belong to this type");
641
642                         if (methodInfoBody is MethodBuilder) {
643                                 MethodBuilder mb = (MethodBuilder)methodInfoBody;
644                                 mb.set_override (methodInfoDeclaration);
645                         }
646                 }
647
648                 public FieldBuilder DefineField (string fieldName, Type type, FieldAttributes attributes)
649                 {
650                         return DefineField (fieldName, type, null, null, attributes);
651                 }
652
653                 public FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
654                 {
655                         check_name ("fieldName", fieldName);
656                         if (type == typeof (void))
657                                 throw new ArgumentException ("Bad field type in defining field.");
658                         check_not_created ();
659
660                         FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomModifiers, optionalCustomModifiers);
661                         if (fields != null) {
662                                 if (fields.Length == num_fields) {
663                                         FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
664                                         System.Array.Copy (fields, new_fields, num_fields);
665                                         fields = new_fields;
666                                 }
667                                 fields [num_fields] = res;
668                                 num_fields ++;
669                         } else {
670                                 fields = new FieldBuilder [1];
671                                 fields [0] = res;
672                                 num_fields ++;
673                                 create_internal_class (this);
674                         }
675
676                         if (IsEnum) {
677                                 if (underlying_type == null && (attributes & FieldAttributes.Static) == 0)
678                                         underlying_type = type;
679                         }
680
681                         return res;
682                 }
683
684                 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
685                 {
686                         return DefineProperty (name, attributes, 0, returnType, null, null, parameterTypes, null, null);
687                 }
688                 
689                 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
690                 {
691                         return DefineProperty (name, attributes, callingConvention, returnType , null, null, parameterTypes, null, null);
692                 }       
693
694                 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
695                 {
696                         return DefineProperty (name, attributes, 0, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
697                 }
698                 
699                 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
700                 {
701                         check_name ("name", name);
702                         if (parameterTypes != null)
703                                 foreach (Type param in parameterTypes)
704                                         if (param == null)
705                                                 throw new ArgumentNullException ("parameterTypes");
706                         check_not_created ();
707
708                         PropertyBuilder res = new PropertyBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
709
710                         if (properties != null) {
711                                 Array.Resize (ref properties, properties.Length + 1);
712                                 properties [properties.Length - 1] = res;
713                         } else {
714                                 properties = new PropertyBuilder [1] { res };
715                         }
716                         return res;
717                 }
718
719                 [ComVisible (true)]
720                 public ConstructorBuilder DefineTypeInitializer()
721                 {
722                         return DefineConstructor (MethodAttributes.Public |
723                                 MethodAttributes.Static | MethodAttributes.SpecialName |
724                                 MethodAttributes.RTSpecialName, CallingConventions.Standard,
725                                 null);
726                 }
727
728                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
729                 private extern TypeInfo create_runtime_class (TypeBuilder tb);
730
731                 private bool is_nested_in (Type t)
732                 {
733                         while (t != null) {
734                                 if (t == this)
735                                         return true;
736                                 else
737                                         t = t.DeclaringType;
738                         }
739                         return false;
740                 }
741
742                 // Return whenever this type has a ctor defined using DefineMethod ()
743                 private bool has_ctor_method () {
744                         MethodAttributes ctor_attrs = MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
745
746                         for (int i = 0; i < num_methods; ++i) {
747                                 MethodBuilder mb = (MethodBuilder)(methods[i]);
748
749                                 if (mb.Name == ConstructorInfo.ConstructorName && (mb.Attributes & ctor_attrs) == ctor_attrs)
750                                         return true;
751                         }
752
753                         return false;
754             }
755
756                 public Type CreateType ()
757                 {
758                         return CreateTypeInfo ();
759                 }
760                 
761                 public
762                 TypeInfo CreateTypeInfo ()
763                 {
764                         /* handle nesting_type */
765                         if (createTypeCalled)
766                                 return created;
767
768                         if (!IsInterface && (parent == null) && (this != pmodule.assemblyb.corlib_object_type) && (FullName != "<Module>")) {
769                                 SetParent (pmodule.assemblyb.corlib_object_type);
770                         }
771
772                         create_generic_class ();
773
774                         // Fire TypeResolve events for fields whose type is an unfinished
775                         // value type.
776                         if (fields != null) {
777                                 foreach (FieldBuilder fb in fields) {
778                                         if (fb == null)
779                                                 continue;
780                                         Type ft = fb.FieldType;
781                                         if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
782                                                 TypeBuilder tb = (TypeBuilder)ft;
783                                                 if (!tb.is_created) {
784                                                         AppDomain.CurrentDomain.DoTypeResolve (tb);
785                                                         if (!tb.is_created) {
786                                                                 // FIXME: We should throw an exception here,
787                                                                 // but mcs expects that the type is created
788                                                                 // even if the exception is thrown
789                                                                 //throw new TypeLoadException ("Could not load type " + tb);
790                                                         }
791                                                 }
792                                         }
793                                 }
794                         }
795
796                         //
797                         // On classes, define a default constructor if not provided
798                         //
799                         if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") && 
800                                 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ())
801                                 DefineDefaultConstructor (MethodAttributes.Public);
802
803                         createTypeCalled = true;
804
805                         if ((parent != null) && parent.IsSealed)
806                                 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
807
808                         if (parent == pmodule.assemblyb.corlib_enum_type && methods != null)
809                                 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is an enum with methods.");
810                         if (interfaces != null) {
811                                 foreach (var iface in interfaces) {
812                                         if (iface.IsNestedPrivate && iface.Assembly != Assembly)
813                                                 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is implements the inaccessible interface '" + iface.FullName + "'.");
814                                 }
815                         }
816
817                         if (methods != null) {
818                                 bool is_concrete = !IsAbstract;
819                                 for (int i = 0; i < num_methods; ++i) {
820                                         MethodBuilder mb = (MethodBuilder)(methods[i]);
821                                         if (is_concrete && mb.IsAbstract)
822                                                 throw new InvalidOperationException ("Type is concrete but has abstract method " + mb);
823                                         mb.check_override ();
824                                         mb.fixup ();
825                                 }
826                         }
827
828                         if (ctors != null){
829                                 foreach (ConstructorBuilder ctor in ctors) 
830                                         ctor.fixup ();
831                         }
832
833                         created = create_runtime_class (this);
834                         if (created != null)
835                                 return created;
836                         return this;
837                 }
838
839                 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
840                 {
841                         symbolWriter.OpenNamespace (this.Namespace);
842
843                         if (methods != null) {
844                                 for (int i = 0; i < num_methods; ++i) {
845                                         MethodBuilder metb = (MethodBuilder) methods[i]; 
846                                         metb.GenerateDebugInfo (symbolWriter);
847                                 }
848                         }
849
850                         if (ctors != null) {
851                                 foreach (ConstructorBuilder ctor in ctors)
852                                         ctor.GenerateDebugInfo (symbolWriter);
853                         }
854                         
855                         symbolWriter.CloseNamespace ();
856
857                         if (subtypes != null) {
858                                 for (int i = 0; i < subtypes.Length; ++i)
859                                         subtypes [i].GenerateDebugInfo (symbolWriter);
860                         }
861                 }
862
863                 [ComVisible (true)]
864                 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
865                 {
866                         if (is_created)
867                                 return created.GetConstructors (bindingAttr);
868
869                         throw new NotSupportedException ();
870                 }
871
872                 internal ConstructorInfo[] GetConstructorsInternal (BindingFlags bindingAttr)
873                 {
874                         if (ctors == null)
875                                 return new ConstructorInfo [0];
876                         ArrayList l = new ArrayList ();
877                         bool match;
878                         MethodAttributes mattrs;
879                         
880                         foreach (ConstructorBuilder c in ctors) {
881                                 match = false;
882                                 mattrs = c.Attributes;
883                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
884                                         if ((bindingAttr & BindingFlags.Public) != 0)
885                                                 match = true;
886                                 } else {
887                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
888                                                 match = true;
889                                 }
890                                 if (!match)
891                                         continue;
892                                 match = false;
893                                 if ((mattrs & MethodAttributes.Static) != 0) {
894                                         if ((bindingAttr & BindingFlags.Static) != 0)
895                                                 match = true;
896                                 } else {
897                                         if ((bindingAttr & BindingFlags.Instance) != 0)
898                                                 match = true;
899                                 }
900                                 if (!match)
901                                         continue;
902                                 l.Add (c);
903                         }
904                         ConstructorInfo[] result = new ConstructorInfo [l.Count];
905                         l.CopyTo (result);
906                         return result;
907                 }
908
909                 public override Type GetElementType ()
910                 {
911                         throw new NotSupportedException ();
912                 }
913
914                 public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
915                 {
916                         check_created ();
917                         return created.GetEvent (name, bindingAttr);
918                 }
919
920                 /* Needed to keep signature compatibility with MS.NET */
921                 public override EventInfo[] GetEvents ()
922                 {
923                         const BindingFlags DefaultBindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
924                         return GetEvents (DefaultBindingFlags);
925                 }
926
927                 public override EventInfo[] GetEvents (BindingFlags bindingAttr)
928                 {
929                         if (is_created)
930                                 return created.GetEvents (bindingAttr);
931                         throw new NotSupportedException ();
932                 }
933
934                 // This is only used from MonoGenericInst.initialize().
935                 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
936                 {
937                         if (events == null)
938                                 return new EventInfo [0];
939                         ArrayList l = new ArrayList ();
940                         bool match;
941                         MethodAttributes mattrs;
942                         MethodInfo accessor;
943
944                         foreach (EventBuilder eb in events) {
945                                 if (eb == null)
946                                         continue;
947                                 EventInfo c = get_event_info (eb);
948                                 match = false;
949                                 accessor = c.GetAddMethod (true);
950                                 if (accessor == null)
951                                         accessor = c.GetRemoveMethod (true);
952                                 if (accessor == null)
953                                         continue;
954                                 mattrs = accessor.Attributes;
955                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
956                                         if ((bindingAttr & BindingFlags.Public) != 0)
957                                                 match = true;
958                                 } else {
959                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
960                                                 match = true;
961                                 }
962                                 if (!match)
963                                         continue;
964                                 match = false;
965                                 if ((mattrs & MethodAttributes.Static) != 0) {
966                                         if ((bindingAttr & BindingFlags.Static) != 0)
967                                                 match = true;
968                                 } else {
969                                         if ((bindingAttr & BindingFlags.Instance) != 0)
970                                                 match = true;
971                                 }
972                                 if (!match)
973                                         continue;
974                                 l.Add (c);
975                         }
976                         EventInfo[] result = new EventInfo [l.Count];
977                         l.CopyTo (result);
978                         return result;
979                 }
980
981                 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
982                 {
983                         if (created != null)
984                                 return created.GetField (name, bindingAttr);
985
986                         if (fields == null)
987                                 return null;
988
989                         bool match;
990                         FieldAttributes mattrs;
991                         
992                         foreach (FieldInfo c in fields) {
993                                 if (c == null)
994                                         continue;
995                                 if (c.Name != name)
996                                         continue;
997                                 match = false;
998                                 mattrs = c.Attributes;
999                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
1000                                         if ((bindingAttr & BindingFlags.Public) != 0)
1001                                                 match = true;
1002                                 } else {
1003                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1004                                                 match = true;
1005                                 }
1006                                 if (!match)
1007                                         continue;
1008                                 match = false;
1009                                 if ((mattrs & FieldAttributes.Static) != 0) {
1010                                         if ((bindingAttr & BindingFlags.Static) != 0)
1011                                                 match = true;
1012                                 } else {
1013                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1014                                                 match = true;
1015                                 }
1016                                 if (!match)
1017                                         continue;
1018                                 return c;
1019                         }
1020                         return null;
1021                 }
1022
1023                 public override FieldInfo[] GetFields (BindingFlags bindingAttr)
1024                 {
1025                         if (created != null)
1026                                 return created.GetFields (bindingAttr);
1027
1028                         if (fields == null)
1029                                 return new FieldInfo [0];
1030                         ArrayList l = new ArrayList ();
1031                         bool match;
1032                         FieldAttributes mattrs;
1033                         
1034                         foreach (FieldInfo c in fields) {
1035                                 if (c == null)
1036                                         continue;
1037                                 match = false;
1038                                 mattrs = c.Attributes;
1039                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
1040                                         if ((bindingAttr & BindingFlags.Public) != 0)
1041                                                 match = true;
1042                                 } else {
1043                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1044                                                 match = true;
1045                                 }
1046                                 if (!match)
1047                                         continue;
1048                                 match = false;
1049                                 if ((mattrs & FieldAttributes.Static) != 0) {
1050                                         if ((bindingAttr & BindingFlags.Static) != 0)
1051                                                 match = true;
1052                                 } else {
1053                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1054                                                 match = true;
1055                                 }
1056                                 if (!match)
1057                                         continue;
1058                                 l.Add (c);
1059                         }
1060                         FieldInfo[] result = new FieldInfo [l.Count];
1061                         l.CopyTo (result);
1062                         return result;
1063                 }
1064
1065                 public override Type GetInterface (string name, bool ignoreCase)
1066                 {
1067                         check_created ();
1068                         return created.GetInterface (name, ignoreCase);
1069                 }
1070                 
1071                 public override Type[] GetInterfaces ()
1072                 {
1073                         if (is_created)
1074                                 return created.GetInterfaces ();
1075
1076                         if (interfaces != null) {
1077                                 Type[] ret = new Type [interfaces.Length];
1078                                 interfaces.CopyTo (ret, 0);
1079                                 return ret;
1080                         } else {
1081                                 return Type.EmptyTypes;
1082                         }
1083                 }
1084
1085                 public override MemberInfo[] GetMember (string name, MemberTypes type,
1086                                                                                                 BindingFlags bindingAttr)
1087                 {
1088                         check_created ();
1089                         return created.GetMember (name, type, bindingAttr);
1090                 }
1091
1092                 public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
1093                 {
1094                         check_created ();
1095                         return created.GetMembers (bindingAttr);
1096                 }
1097
1098                 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type)
1099                 {
1100                         MethodInfo[] candidates;
1101                         bool match;
1102                         MethodAttributes mattrs;
1103
1104                         if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
1105                                 MethodInfo [] parent_methods = parent.GetMethods (bindingAttr);
1106                                 ArrayList parent_candidates = new ArrayList (parent_methods.Length);
1107
1108                                 bool flatten = (bindingAttr & BindingFlags.FlattenHierarchy) != 0;
1109
1110                                 for (int i = 0; i < parent_methods.Length; i++) {
1111                                         MethodInfo m = parent_methods [i];
1112
1113                                         mattrs = m.Attributes;
1114
1115                                         if (m.IsStatic && !flatten)
1116                                                 continue;
1117
1118                                         switch (mattrs & MethodAttributes.MemberAccessMask) {
1119                                         case MethodAttributes.Public:
1120                                                 match = (bindingAttr & BindingFlags.Public) != 0;
1121                                                 break;
1122                                         case MethodAttributes.Assembly:
1123                                                 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1124                                                 break;
1125                                         case MethodAttributes.Private:
1126                                                 match = false;
1127                                                 break;
1128                                         default:
1129                                                 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1130                                                 break;
1131                                         }
1132
1133                                         if (match)
1134                                                 parent_candidates.Add (m);
1135                                 }
1136
1137                                 if (methods == null) {
1138                                         candidates = new MethodInfo [parent_candidates.Count];
1139                                         parent_candidates.CopyTo (candidates);
1140                                 } else {
1141                                         candidates = new MethodInfo [methods.Length + parent_candidates.Count];
1142                                         parent_candidates.CopyTo (candidates, 0);
1143                                         methods.CopyTo (candidates, parent_candidates.Count);
1144                                 }
1145                         }
1146                         else
1147                                 candidates = methods;
1148
1149                         if (candidates == null)
1150                                 return new MethodInfo [0];
1151
1152                         ArrayList l = new ArrayList ();
1153
1154                         foreach (MethodInfo c in candidates) {
1155                                 if (c == null)
1156                                         continue;
1157                                 if (name != null) {
1158                                         if (String.Compare (c.Name, name, ignoreCase) != 0)
1159                                                 continue;
1160                                 }
1161                                 match = false;
1162                                 mattrs = c.Attributes;
1163                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1164                                         if ((bindingAttr & BindingFlags.Public) != 0)
1165                                                 match = true;
1166                                 } else {
1167                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1168                                                 match = true;
1169                                 }
1170                                 if (!match)
1171                                         continue;
1172                                 match = false;
1173                                 if ((mattrs & MethodAttributes.Static) != 0) {
1174                                         if ((bindingAttr & BindingFlags.Static) != 0)
1175                                                 match = true;
1176                                 } else {
1177                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1178                                                 match = true;
1179                                 }
1180                                 if (!match)
1181                                         continue;
1182                                 l.Add (c);
1183                         }
1184
1185                         MethodInfo[] result = new MethodInfo [l.Count];
1186                         l.CopyTo (result);
1187                         return result;
1188                 }
1189
1190                 public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
1191                 {
1192                         return GetMethodsByName (null, bindingAttr, false, this);
1193                 }
1194
1195                 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
1196                                                              Binder binder,
1197                                                              CallingConventions callConvention,
1198                                                              Type[] types, ParameterModifier[] modifiers)
1199                 {
1200                         check_created ();
1201
1202                         if (types == null)
1203                                 return created.GetMethod (name, bindingAttr);
1204
1205                         return created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
1206                 }
1207
1208                 public override Type GetNestedType (string name, BindingFlags bindingAttr)
1209                 {
1210                         check_created ();
1211
1212                         if (subtypes == null)
1213                                 return null;
1214
1215                         foreach (TypeBuilder t in subtypes) {
1216                                 if (!t.is_created)
1217                                         continue;
1218                                 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1219                                         if ((bindingAttr & BindingFlags.Public) == 0)
1220                                                 continue;
1221                                 } else {
1222                                         if ((bindingAttr & BindingFlags.NonPublic) == 0)
1223                                                 continue;
1224                                 }
1225                                 if (t.Name == name)
1226                                         return t.created;
1227                         }
1228
1229                         return null;
1230                 }
1231
1232                 public override Type[] GetNestedTypes (BindingFlags bindingAttr)
1233                 {
1234                         if (!is_created)
1235                                 throw new NotSupportedException ();
1236
1237                         bool match;
1238                         ArrayList result = new ArrayList ();
1239
1240                         if (subtypes == null)
1241                                 return Type.EmptyTypes;
1242                         foreach (TypeBuilder t in subtypes) {
1243                                 match = false;
1244                                 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1245                                         if ((bindingAttr & BindingFlags.Public) != 0)
1246                                                 match = true;
1247                                 } else {
1248                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1249                                                 match = true;
1250                                 }
1251                                 if (!match)
1252                                         continue;
1253                                 result.Add (t);
1254                         }
1255                         Type[] r = new Type [result.Count];
1256                         result.CopyTo (r);
1257                         return r;
1258                 }
1259
1260                 public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
1261                 {
1262                         if (is_created)
1263                                 return created.GetProperties (bindingAttr);
1264
1265                         if (properties == null)
1266                                 return new PropertyInfo [0];
1267                         ArrayList l = new ArrayList ();
1268                         bool match;
1269                         MethodAttributes mattrs;
1270                         MethodInfo accessor;
1271                         
1272                         foreach (PropertyInfo c in properties) {
1273                                 match = false;
1274                                 accessor = c.GetGetMethod (true);
1275                                 if (accessor == null)
1276                                         accessor = c.GetSetMethod (true);
1277                                 if (accessor == null)
1278                                         continue;
1279                                 mattrs = accessor.Attributes;
1280                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1281                                         if ((bindingAttr & BindingFlags.Public) != 0)
1282                                                 match = true;
1283                                 } else {
1284                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1285                                                 match = true;
1286                                 }
1287                                 if (!match)
1288                                         continue;
1289                                 match = false;
1290                                 if ((mattrs & MethodAttributes.Static) != 0) {
1291                                         if ((bindingAttr & BindingFlags.Static) != 0)
1292                                                 match = true;
1293                                 } else {
1294                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1295                                                 match = true;
1296                                 }
1297                                 if (!match)
1298                                         continue;
1299                                 l.Add (c);
1300                         }
1301                         PropertyInfo[] result = new PropertyInfo [l.Count];
1302                         l.CopyTo (result);
1303                         return result;
1304                 }
1305                 
1306                 protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
1307                 {
1308                         throw not_supported ();
1309                 }
1310
1311                 protected override bool HasElementTypeImpl ()
1312                 {
1313                         // a TypeBuilder can never represent an array, pointer
1314                         if (!is_created)
1315                                 return false;
1316
1317                         return created.HasElementType;
1318                 }
1319
1320                 public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
1321                 {
1322                         check_created ();
1323                         return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1324                 }
1325
1326                 protected override bool IsArrayImpl ()
1327                 {
1328                         return false; /*A TypeBuilder never represents a non typedef type.*/
1329                 }
1330
1331                 protected override bool IsByRefImpl ()
1332                 {
1333                         return false; /*A TypeBuilder never represents a non typedef type.*/
1334                 }
1335
1336                 protected override bool IsCOMObjectImpl ()
1337                 {
1338                         return ((GetAttributeFlagsImpl () & TypeAttributes.Import) != 0);
1339                 }
1340
1341                 protected override bool IsPointerImpl ()
1342                 {
1343                         return false; /*A TypeBuilder never represents a non typedef type.*/
1344                 }
1345
1346                 protected override bool IsPrimitiveImpl ()
1347                 {
1348                         // FIXME
1349                         return false;
1350                 }
1351
1352                 // FIXME: I doubt just removing this still works.
1353                 protected override bool IsValueTypeImpl ()
1354                 {
1355                         if (this == pmodule.assemblyb.corlib_value_type || this == pmodule.assemblyb.corlib_enum_type)
1356                                 return false;
1357                         Type parent_type = parent;
1358                         while (parent_type != null) {
1359                                 if (parent_type == pmodule.assemblyb.corlib_value_type)
1360                                         return true;
1361                                 parent_type = parent_type.BaseType;
1362                         }
1363                         return false;
1364                 }
1365                 
1366                 public override Type MakeArrayType ()
1367                 {
1368                         return new ArrayType (this, 0);
1369                 }
1370
1371                 public override Type MakeArrayType (int rank)
1372                 {
1373                         if (rank < 1)
1374                                 throw new IndexOutOfRangeException ();
1375                         return new ArrayType (this, rank);
1376                 }
1377
1378                 public override Type MakeByRefType ()
1379                 {
1380                         return new ByRefType (this);
1381                 }
1382
1383                 public override Type MakeGenericType (params Type [] typeArguments)
1384                 {
1385                         //return base.MakeGenericType (typeArguments);
1386
1387                         if (!IsGenericTypeDefinition)
1388                                 throw new InvalidOperationException ("not a generic type definition");
1389                         if (typeArguments == null)
1390                                 throw new ArgumentNullException ("typeArguments");
1391
1392                         if (generic_params.Length != typeArguments.Length)
1393                                 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");
1394
1395                         foreach (Type t in typeArguments) {
1396                                 if (t == null)
1397                                         throw new ArgumentNullException ("typeArguments");                              
1398                         }
1399
1400                         Type[] copy = new Type [typeArguments.Length];
1401                         typeArguments.CopyTo (copy, 0);
1402                         return pmodule.assemblyb.MakeGenericType (this, copy);
1403                 }
1404
1405                 public override Type MakePointerType ()
1406                 {
1407                         return new PointerType (this);
1408                 }
1409
1410                 public override RuntimeTypeHandle TypeHandle {
1411                         get {
1412                                 check_created ();
1413                                 return created.TypeHandle;
1414                         }
1415                 }
1416                 
1417                 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
1418                 {
1419                         if (customBuilder == null)
1420                                 throw new ArgumentNullException ("customBuilder");
1421
1422                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
1423                         if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1424                                 byte[] data = customBuilder.Data;
1425                                 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1426                                 layout_kind = (int)data [2];
1427                                 layout_kind |= ((int)data [3]) << 8;
1428                                 attrs &= ~TypeAttributes.LayoutMask;
1429                                 switch ((LayoutKind)layout_kind) {
1430                                 case LayoutKind.Auto:
1431                                         attrs |= TypeAttributes.AutoLayout;
1432                                         break;
1433                                 case LayoutKind.Explicit:
1434                                         attrs |= TypeAttributes.ExplicitLayout;
1435                                         break;
1436                                 case LayoutKind.Sequential:
1437                                         attrs |= TypeAttributes.SequentialLayout;
1438                                         break;
1439                                 default:
1440                                         // we should ignore it since it can be any value anyway...
1441                                         throw new Exception ("Error in customattr");
1442                                 }
1443                                 
1444                                 var ctor_type = customBuilder.Ctor is ConstructorBuilder ? ((ConstructorBuilder)customBuilder.Ctor).parameters[0] : customBuilder.Ctor.GetParametersInternal()[0].ParameterType;
1445                                 int pos = 6;
1446                                 if (ctor_type.FullName == "System.Int16")
1447                                         pos = 4;
1448                                 int nnamed = (int)data [pos++];
1449                                 nnamed |= ((int)data [pos++]) << 8;
1450                                 for (int i = 0; i < nnamed; ++i) {
1451                                         //byte named_type = data [pos++];
1452                                         pos ++;
1453                                         byte type = data [pos++];
1454                                         int len;
1455                                         string named_name;
1456
1457                                         if (type == 0x55) {
1458                                                 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1459                                                 //string named_typename = 
1460                                                 CustomAttributeBuilder.string_from_bytes (data, pos, len);
1461                                                 pos += len;
1462                                                 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1463                                                 //        See related code/FIXME in mono/mono/metadata/reflection.c
1464                                         }
1465
1466                                         len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1467                                         named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1468                                         pos += len;
1469                                         /* all the fields are integers in StructLayout */
1470                                         int value = (int)data [pos++];
1471                                         value |= ((int)data [pos++]) << 8;
1472                                         value |= ((int)data [pos++]) << 16;
1473                                         value |= ((int)data [pos++]) << 24;
1474                                         switch (named_name) {
1475                                         case "CharSet":
1476                                                 switch ((CharSet)value) {
1477                                                 case CharSet.None:
1478                                                 case CharSet.Ansi:
1479                                                         attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
1480                                                         break;
1481                                                 case CharSet.Unicode:
1482                                                         attrs &= ~TypeAttributes.AutoClass;
1483                                                         attrs |= TypeAttributes.UnicodeClass;
1484                                                         break;
1485                                                 case CharSet.Auto:
1486                                                         attrs &= ~TypeAttributes.UnicodeClass;
1487                                                         attrs |= TypeAttributes.AutoClass;
1488                                                         break;
1489                                                 default:
1490                                                         break; // error out...
1491                                                 }
1492                                                 break;
1493                                         case "Pack":
1494                                                 packing_size = (PackingSize)value;
1495                                                 break;
1496                                         case "Size":
1497                                                 class_size = value;
1498                                                 break;
1499                                         default:
1500                                                 break; // error out...
1501                                         }
1502                                 }
1503                                 return;
1504                         } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
1505                                 attrs |= TypeAttributes.SpecialName;
1506                                 return;
1507                         } else if (attrname == "System.SerializableAttribute") {
1508                                 attrs |= TypeAttributes.Serializable;
1509                                 return;
1510                         } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
1511                                 attrs |= TypeAttributes.Import;
1512                                 return;
1513                         } else if (attrname == "System.Security.SuppressUnmanagedCodeSecurityAttribute") {
1514                                 attrs |= TypeAttributes.HasSecurity;
1515                         }
1516
1517                         if (cattrs != null) {
1518                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1519                                 cattrs.CopyTo (new_array, 0);
1520                                 new_array [cattrs.Length] = customBuilder;
1521                                 cattrs = new_array;
1522                         } else {
1523                                 cattrs = new CustomAttributeBuilder [1];
1524                                 cattrs [0] = customBuilder;
1525                         }
1526                 }
1527
1528                 [ComVisible (true)]
1529                 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
1530                 {
1531                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1532                 }
1533
1534                 public EventBuilder DefineEvent (string name, EventAttributes attributes, Type eventtype)
1535                 {
1536                         check_name ("name", name);
1537                         if (eventtype == null)
1538                                 throw new ArgumentNullException ("type");
1539                         check_not_created ();
1540
1541                         EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1542                         if (events != null) {
1543                                 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1544                                 System.Array.Copy (events, new_events, events.Length);
1545                                 new_events [events.Length] = res;
1546                                 events = new_events;
1547                         } else {
1548                                 events = new EventBuilder [1];
1549                                 events [0] = res;
1550                         }
1551                         return res;
1552                 }
1553
1554                 public FieldBuilder DefineInitializedData (string name, byte[] data, FieldAttributes attributes) {
1555                         if (data == null)
1556                                 throw new ArgumentNullException ("data");
1557
1558                         FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1559                         res.SetRVAData (data);
1560                         return res;
1561                 }
1562
1563                 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
1564                 {
1565                         if (name == null)
1566                                 throw new ArgumentNullException ("name");
1567                         if (name.Length == 0)
1568                                 throw new ArgumentException ("Empty name is not legal", "name");
1569                         if ((size <= 0) || (size > 0x3f0000))
1570                                 throw new ArgumentException ("Data size must be > 0 and < 0x3f0000");
1571                         check_not_created ();
1572
1573                         string typeName = "$ArrayType$" + size;
1574                         Type datablobtype = pmodule.GetRegisteredType (fullname + "+" + typeName);
1575                         if (datablobtype == null) {
1576                                 TypeBuilder tb = DefineNestedType (typeName,
1577                                         TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1578                                         pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1579                                 tb.CreateType ();
1580                                 datablobtype = tb;
1581                         }
1582                         return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1583                 }
1584
1585                 public TypeToken TypeToken {
1586                         get {
1587                                 return new TypeToken (0x02000000 | table_idx);
1588                         }
1589                 }
1590
1591                 public void SetParent (Type parent)
1592                 {
1593                         check_not_created ();
1594
1595                         if (parent == null) {
1596                                 if ((attrs & TypeAttributes.Interface) != 0) {
1597                                         if ((attrs & TypeAttributes.Abstract) == 0)
1598                                                 throw new InvalidOperationException ("Interface must be declared abstract.");
1599                                         this.parent = null;
1600                                 } else {
1601                                         this.parent = typeof (object);
1602                                 }
1603                         } else {
1604                                 this.parent = parent;
1605                         }
1606
1607                         // will just set the parent-related bits if called a second time
1608                         setup_internal_class (this);
1609                 }
1610
1611                 internal int get_next_table_index (object obj, int table, bool inc) {
1612                         return pmodule.get_next_table_index (obj, table, inc);
1613                 }
1614
1615                 [ComVisible (true)]
1616                 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1617                 {
1618                         if (created == null)
1619                                 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1620
1621                         return created.GetInterfaceMap (interfaceType);
1622                 }
1623
1624                 internal override Type InternalResolve ()
1625                 {
1626                         check_created ();
1627                         return created;
1628                 }
1629
1630                 internal bool is_created {
1631                         get {
1632                                 return createTypeCalled;
1633                         }
1634                 }
1635
1636                 private Exception not_supported ()
1637                 {
1638                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1639                 }
1640
1641                 private void check_not_created ()
1642                 {
1643                         if (is_created)
1644                                 throw new InvalidOperationException ("Unable to change after type has been created.");
1645                 }
1646
1647                 private void check_created ()
1648                 {
1649                         if (!is_created)
1650                                 throw not_supported ();
1651                 }
1652
1653                 private void check_name (string argName, string name)
1654                 {
1655                         if (name == null)
1656                                 throw new ArgumentNullException (argName);
1657                         if (name.Length == 0)
1658                                 throw new ArgumentException ("Empty name is not legal", argName);
1659                         if (name [0] == ((char)0))
1660                                 throw new ArgumentException ("Illegal name", argName);
1661                 }
1662
1663                 public override String ToString ()
1664                 {
1665                         return FullName;
1666                 }
1667
1668                 [MonoTODO]
1669                 public override bool IsAssignableFrom (Type c)
1670                 {
1671                         return base.IsAssignableFrom (c);
1672                 }
1673
1674                 [MonoTODO ("arrays")]
1675                 internal bool IsAssignableTo (Type c)
1676                 {
1677                         if (c == this)
1678                                 return true;
1679
1680                         if (c.IsInterface) {
1681                                 if (parent != null && is_created) {
1682                                         if (c.IsAssignableFrom (parent))
1683                                                 return true;
1684                                 }
1685
1686                                 if (interfaces == null)
1687                                         return false;
1688                                 foreach (Type t in interfaces)
1689                                         if (c.IsAssignableFrom (t))
1690                                                 return true;
1691                                 if (!is_created)
1692                                         return false;
1693                         }
1694
1695                         if (parent == null)
1696                                 return c == typeof (object);
1697                         else
1698                                 return c.IsAssignableFrom (parent);
1699                 }
1700
1701                 public bool IsCreated ()
1702                 {
1703                         return is_created;
1704                 }
1705
1706                 public override Type[] GetGenericArguments ()
1707                 {
1708                         if (generic_params == null)
1709                                 return null;
1710                         Type[] args = new Type [generic_params.Length];
1711                         generic_params.CopyTo (args, 0);
1712                         return args;
1713                 }
1714
1715                 public override Type GetGenericTypeDefinition ()
1716                 {
1717                         if (generic_params == null)
1718                                 throw new InvalidOperationException ("Type is not generic");
1719                         return this;
1720                 }
1721
1722                 public override bool ContainsGenericParameters {
1723                         get {
1724                                 return generic_params != null;
1725                         }
1726                 }
1727
1728                 public extern override bool IsGenericParameter {
1729                         [MethodImplAttribute(MethodImplOptions.InternalCall)]
1730                         get;
1731                 }
1732
1733                 public override GenericParameterAttributes GenericParameterAttributes {
1734                         get { return GenericParameterAttributes.None; }
1735                 }
1736
1737                 public override bool IsGenericTypeDefinition {
1738                         get {
1739                                 return generic_params != null;
1740                         }
1741                 }
1742
1743                 public override bool IsGenericType {
1744                         get { return IsGenericTypeDefinition; }
1745                 }
1746
1747                 [MonoTODO]
1748                 public override int GenericParameterPosition {
1749                         get {
1750                                 return 0;
1751                         }
1752                 }
1753
1754                 public override MethodBase DeclaringMethod {
1755                         get {
1756                                 return null;
1757                         }
1758                 }
1759
1760                 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1761                 {
1762                         if (names == null)
1763                                 throw new ArgumentNullException ("names");
1764                         if (names.Length == 0)
1765                                 throw new ArgumentException ("names");
1766
1767                         setup_generic_class ();
1768
1769                         generic_params = new GenericTypeParameterBuilder [names.Length];
1770                         for (int i = 0; i < names.Length; i++) {
1771                                 string item = names [i];
1772                                 if (item == null)
1773                                         throw new ArgumentNullException ("names");
1774                                 generic_params [i] = new GenericTypeParameterBuilder (this, null, item, i);
1775                         }
1776
1777                         return generic_params;
1778                 }
1779
1780                 public static ConstructorInfo GetConstructor (Type type, ConstructorInfo constructor)
1781                 {
1782                         /*FIXME I would expect the same checks of GetMethod here*/
1783                         if (type == null)
1784                                 throw new ArgumentException ("Type is not generic", "type");
1785
1786                         if (!type.IsGenericType)
1787                                 throw new ArgumentException ("Type is not a generic type", "type");
1788
1789                         if (type.IsGenericTypeDefinition)
1790                                 throw new ArgumentException ("Type cannot be a generic type definition", "type");
1791
1792                         if (constructor == null)
1793                                 throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException
1794
1795                         if (!constructor.DeclaringType.IsGenericTypeDefinition)
1796                                 throw new ArgumentException ("constructor declaring type is not a generic type definition", "constructor");
1797                         if (constructor.DeclaringType != type.GetGenericTypeDefinition ())
1798                                 throw new ArgumentException ("constructor declaring type is not the generic type definition of type", "constructor");
1799
1800                         ConstructorInfo res = type.GetConstructor (constructor);
1801                         if (res == null)
1802                                 throw new ArgumentException ("constructor not found");
1803
1804                         return res;
1805                 }
1806
1807                 static bool IsValidGetMethodType (Type type)
1808                 {
1809                         if (type is TypeBuilder || type is MonoGenericClass)
1810                                 return true;
1811                         /*GetMethod() must work with TypeBuilders after CreateType() was called.*/
1812                         if (type.Module is ModuleBuilder)
1813                                 return true;
1814                         if (type.IsGenericParameter)
1815                                 return false;
1816
1817                         Type[] inst = type.GetGenericArguments ();
1818                         if (inst == null)
1819                                 return false;
1820                         for (int i = 0; i < inst.Length; ++i) {
1821                                 if (IsValidGetMethodType (inst [i]))
1822                                         return true;
1823                         }
1824                         return false;
1825                 }
1826
1827                 public static MethodInfo GetMethod (Type type, MethodInfo method)
1828                 {
1829                         if (!IsValidGetMethodType (type))
1830                                 throw new ArgumentException ("type is not TypeBuilder but " + type.GetType (), "type");
1831
1832                         if (type is TypeBuilder && type.ContainsGenericParameters)
1833                                 type = type.MakeGenericType (type.GetGenericArguments ());
1834
1835                         if (!type.IsGenericType)
1836                                 throw new ArgumentException ("type is not a generic type", "type");
1837
1838                         if (!method.DeclaringType.IsGenericTypeDefinition)
1839                                 throw new ArgumentException ("method declaring type is not a generic type definition", "method");
1840                         if (method.DeclaringType != type.GetGenericTypeDefinition ())
1841                                 throw new ArgumentException ("method declaring type is not the generic type definition of type", "method");
1842                         if (method == null)
1843                                 throw new NullReferenceException (); //MS raises this instead of an ArgumentNullException
1844
1845                         MethodInfo res = type.GetMethod (method);
1846                         if (res == null)
1847                                 throw new ArgumentException (String.Format ("method {0} not found in type {1}", method.Name, type));
1848                                 
1849                         return res;
1850                 }
1851
1852                 public static FieldInfo GetField (Type type, FieldInfo field)
1853                 {
1854                         if (!type.IsGenericType)
1855                                 throw new ArgumentException ("Type is not a generic type", "type");
1856
1857                         if (type.IsGenericTypeDefinition)
1858                                 throw new ArgumentException ("Type cannot be a generic type definition", "type");
1859
1860                         if (field is FieldOnTypeBuilderInst)
1861                                 throw new ArgumentException ("The specified field must be declared on a generic type definition.", "field");
1862
1863                         if (field.DeclaringType != type.GetGenericTypeDefinition ())
1864                                 throw new ArgumentException ("field declaring type is not the generic type definition of type", "method");
1865
1866                         FieldInfo res = type.GetField (field);
1867                         if (res == null)
1868                                 throw new System.Exception ("field not found");
1869                         else
1870                                 return res;
1871                 }
1872
1873
1874                 void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1875                 {
1876                         throw new NotImplementedException ();
1877                 }
1878
1879                 void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1880                 {
1881                         throw new NotImplementedException ();
1882                 }
1883
1884                 void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
1885                 {
1886                         throw new NotImplementedException ();
1887                 }
1888
1889                 void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1890                 {
1891                         throw new NotImplementedException ();
1892                 }
1893
1894                 internal override bool IsUserType {
1895                         get {
1896                                 return false;
1897                         }
1898                 }
1899
1900                 public override bool IsConstructedGenericType {
1901                         get { return false; }
1902                 }
1903
1904                 public override bool IsAssignableFrom (TypeInfo typeInfo)
1905                 {
1906                         return base.IsAssignableFrom (typeInfo);
1907                 }
1908         }
1909 }
1910 #endif