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