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