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