2004-01-08 Zoltan Varga <vargaz@freemail.hu>
[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 //
7 // (C) 2001 Ximian, Inc.  http://www.ximian.com
8 //
9
10 using System;
11 using System.Text;
12 using System.Reflection;
13 using System.Reflection.Emit;
14 using System.Runtime.CompilerServices;
15 using System.Runtime.InteropServices;
16 using System.Globalization;
17 using System.Collections;
18 using System.Security;
19 using System.Security.Permissions;
20
21 namespace System.Reflection.Emit {
22
23         public sealed class TypeBuilder : Type {
24         private string tname;
25         private string nspace;
26         private Type parent;
27         private Type nesting_type;
28         private Type[] interfaces;
29         private int num_methods;
30         private MethodBuilder[] methods;
31         private ConstructorBuilder[] ctors;
32         private PropertyBuilder[] properties;
33         private int num_fields;
34         private FieldBuilder[] fields;
35         private EventBuilder[] events;
36         private CustomAttributeBuilder[] cattrs;
37         internal TypeBuilder[] subtypes;
38         private TypeAttributes attrs;
39         private int table_idx;
40         private ModuleBuilder pmodule;
41         private int class_size;
42         private PackingSize packing_size;
43         private MonoGenericParam[] generic_params;
44         private Type created;
45         string fullname;
46
47         public const int UnspecifiedTypeSize = 0;
48
49                 protected override TypeAttributes GetAttributeFlagsImpl () {
50                         return attrs;
51                 }
52                 
53                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
54                 private extern void setup_internal_class (TypeBuilder tb);
55                 
56                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
57                 private extern void create_internal_class (TypeBuilder tb);
58                 
59                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
60                 private extern void setup_generic_class (TypeBuilder tb);
61
62                 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr) {
63                         this.parent = null;
64                         this.attrs = attr;
65                         this.class_size = -1;
66                         fullname = this.tname = "<Module>";
67                         this.nspace = "";
68                         pmodule = mb;
69                         setup_internal_class (this);
70                 }
71
72                 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type) {
73                         int sep_index;
74                         this.parent = parent;
75                         this.attrs = attr;
76                         this.class_size = type_size;
77                         this.packing_size = packing_size;
78                         this.nesting_type = nesting_type;
79                         sep_index = name.LastIndexOf('.');
80                         if (sep_index != -1) {
81                                 this.tname = name.Substring (sep_index + 1);
82                                 this.nspace = name.Substring (0, sep_index);
83                         } else {
84                                 this.tname = name;
85                                 this.nspace = "";
86                         }
87                         if (interfaces != null) {
88                                 this.interfaces = new Type[interfaces.Length];
89                                 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
90                         }
91                         pmodule = mb;
92                         // skip .<Module> ?
93                         table_idx = mb.get_next_table_index (this, 0x02, true);
94                         setup_internal_class (this);
95                         fullname = GetFullName ();
96                 }
97
98                 public override Assembly Assembly {
99                         get {return pmodule.Assembly;}
100                 }
101
102                 public override string AssemblyQualifiedName {
103                         get {
104                                 return fullname + ", " + Assembly.GetName().FullName;
105                         }
106                 }
107                 public override Type BaseType {
108                         get {
109                                 return parent;
110                         }
111                 }
112                 public override Type DeclaringType {get {return nesting_type;}}
113
114 /*              public override bool IsSubclassOf (Type c)
115                 {
116                         Type t;
117                         if (c == null)
118                                 return false;
119                         if (c == this)
120                                 return false;
121                         t = parent;
122                         while (t != null) {
123                                 if (c == t)
124                                         return true;
125                                 t = t.BaseType;
126                         }
127                         return false;
128                 }*/
129
130                 [MonoTODO]
131                 public override Type UnderlyingSystemType {
132                         get {
133                                 // This should return the type itself for non-enum types but 
134                                 // that breaks mcs.
135                                 if (fields != null) {
136                                         foreach (FieldBuilder f in fields) {
137                                                 if ((f != null) && (f.Attributes & FieldAttributes.Static) == 0)
138                                                         return f.FieldType;
139                                         }
140                                 }
141                                 throw new InvalidOperationException ("Underlying type information on enumeration is not specified.");
142                         }
143                 }
144
145                 string GetFullName () {
146                         if (nesting_type != null)
147                                 return String.Concat (nesting_type.FullName, "+", tname);
148                         if ((nspace != null) && (nspace.Length > 0))
149                                 return String.Concat (nspace, ".", tname);
150                         return tname;
151                 }
152         
153                 public override string FullName {
154                         get {
155                                 return fullname;
156                         }
157                 }
158         
159                 public override Guid GUID {
160                         get {
161                             throw not_supported ();
162                         }
163                 }
164
165                 public override Module Module {
166                         get {return pmodule;}
167                 }
168                 public override string Name {
169                         get {return tname;}
170                 }
171                 public override string Namespace {
172                         get {return nspace;}
173                 }
174                 public PackingSize PackingSize {
175                         get {return packing_size;}
176                 }
177                 public int Size {
178                         get { return class_size; }
179                 }
180                 public override Type ReflectedType {get {return nesting_type;}}
181
182                 [MonoTODO]
183                 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
184                         throw new NotImplementedException ();
185                 }
186
187                 public void AddInterfaceImplementation( Type interfaceType) {
188                         if (interfaceType == null)
189                                 throw new ArgumentNullException ("interfaceType");
190                         if (is_created)
191                                 throw not_after_created ();
192
193                         if (interfaces != null) {
194                                 // Check for duplicates
195                                 foreach (Type t in interfaces)
196                                         if (t == interfaceType)
197                                                 return;
198
199                                 Type[] ifnew = new Type [interfaces.Length + 1];
200                                 interfaces.CopyTo (ifnew, 0);
201                                 ifnew [interfaces.Length] = interfaceType;
202                                 interfaces = ifnew;
203                         } else {
204                                 interfaces = new Type [1];
205                                 interfaces [0] = interfaceType;
206                         }
207                 }
208
209                 [MonoTODO]
210                 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
211                                                                        CallingConventions callConvention, Type[] types,
212                                                                        ParameterModifier[] modifiers)
213                 {
214                         if (ctors == null)
215                                 return null;
216
217                         ConstructorBuilder found = null;
218                         int count = 0;
219                         
220                         foreach (ConstructorBuilder cb in ctors){
221                                 if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
222                                         continue;
223                                 found = cb;
224                                 count++;
225                         }
226
227                         if (count == 0)
228                                 return null;
229                         if (types == null){
230                                 if (count > 1)
231                                         throw new AmbiguousMatchException ();
232                                 return found;
233                         }
234                         MethodBase[] match = new MethodBase [count];
235                         if (count == 1)
236                                 match [0] = found;
237                         else {
238                                 count = 0;
239                                 foreach (ConstructorInfo m in ctors) {
240                                         if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
241                                                 continue;
242                                         match [count++] = m;
243                                 }
244                         }
245                         if (binder == null)
246                                 binder = Binder.DefaultBinder;
247                         return (ConstructorInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
248                 }
249
250                 public override bool IsDefined( Type attributeType, bool inherit)
251                 {
252                         /*
253                          * MS throws NotSupported here, but we can't because some corlib
254                          * classes make calls to IsDefined.
255                          */
256                         return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
257                 }
258                 
259                 public override object[] GetCustomAttributes(bool inherit)
260                 {
261                         throw not_supported ();
262                 }
263                 
264                 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
265                 {
266                         throw not_supported ();
267                 }
268
269                 public TypeBuilder DefineNestedType (string name) {
270                         return DefineNestedType (name, TypeAttributes.NestedPrivate, pmodule.assemblyb.corlib_object_type, null);
271                 }
272
273                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr) {
274                         return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
275                 }
276
277                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) {
278                         return DefineNestedType (name, attr, parent, null);
279                 }
280
281                 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
282                                                       PackingSize packsize, int typesize)
283                 {
284                         check_name ("name", name);
285                         // Visibility must be NestedXXX
286                         /* This breaks mcs
287                         if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
288                                 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
289                                 throw new ArgumentException ("attr", "Bad type flags for nested type.");
290                         */
291                         if (interfaces != null)
292                                 foreach (Type iface in interfaces)
293                                         if (iface == null)
294                                                 throw new ArgumentNullException ("interfaces");
295
296                         TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packsize, typesize, this);
297                         res.fullname = res.GetFullName ();
298                         pmodule.RegisterTypeName (res, res.fullname);
299                         if (subtypes != null) {
300                                 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
301                                 System.Array.Copy (subtypes, new_types, subtypes.Length);
302                                 new_types [subtypes.Length] = res;
303                                 subtypes = new_types;
304                         } else {
305                                 subtypes = new TypeBuilder [1];
306                                 subtypes [0] = res;
307                         }
308                         return res;
309                 }
310
311                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
312                         return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
313                 }
314
315                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
316                         return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typesize);
317                 }
318
319                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
320                         return DefineNestedType (name, attr, parent, null, packsize, UnspecifiedTypeSize);
321                 }
322
323                 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) {
324                         return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
325                 }
326
327 #if NET_1_2
328                 public
329 #else
330                 internal
331 #endif
332                 ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
333                 {
334                         if (is_created)
335                                 throw not_after_created ();
336                         ConstructorBuilder cb = new ConstructorBuilder (this, attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
337                         if (ctors != null) {
338                                 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
339                                 System.Array.Copy (ctors, new_ctors, ctors.Length);
340                                 new_ctors [ctors.Length] = cb;
341                                 ctors = new_ctors;
342                         } else {
343                                 ctors = new ConstructorBuilder [1];
344                                 ctors [0] = cb;
345                         }
346                         return cb;
347                 }
348
349                 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
350                 {
351                         ConstructorBuilder cb = DefineConstructor (attributes, CallingConventions.Standard, new Type [0]);
352
353                         Type parent_type;
354
355                         if (parent != null)
356                                 parent_type = parent;
357                         else
358                                 parent_type = pmodule.assemblyb.corlib_object_type;
359
360                         ConstructorInfo parent_constructor =
361                                 parent_type.GetConstructor (
362                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
363                                         null, Type.EmptyTypes, null);
364
365                         ILGenerator ig = cb.GetILGenerator ();
366                         if (parent_constructor != null){
367                                 ig.Emit (OpCodes.Ldarg_0);
368                                 ig.Emit (OpCodes.Call, parent_constructor);
369                         }
370                         ig.Emit (OpCodes.Ret);
371                         return cb;
372                 }
373
374                 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
375                         return DefineMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
376                 }
377
378                 private void append_method (MethodBuilder mb) {
379                         if (methods != null) {
380                                 if (methods.Length == num_methods) {
381                                         MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
382                                         System.Array.Copy (methods, new_methods, num_methods);
383                                         methods = new_methods;
384                                 }
385                         } else {
386                                 methods = new MethodBuilder [1];
387                         }
388                         methods [num_methods] = mb;
389                         num_methods ++;
390                 }
391
392                 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
393                         return DefineMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
394                 }
395
396 #if NET_1_2
397                 public
398 #else
399                 internal
400 #endif
401                 MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
402                         check_name ("name", name);
403                         if (is_created)
404                                 throw not_after_created ();
405                         if (IsInterface && (
406                                 !((attributes & MethodAttributes.Abstract) != 0) || 
407                                 !((attributes & MethodAttributes.Virtual) != 0)))
408                                 throw new ArgumentException ("attributes", "Interface method must be abstract and virtual.");
409
410                         if (returnType == null)
411                                 returnType = pmodule.assemblyb.corlib_void_type;
412                         MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
413                         append_method (res);
414                         return res;
415                 }
416
417                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
418                         return DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet);
419                 }
420
421 #if NET_1_2
422                 public
423 #else
424                 internal
425 #endif
426                 MethodBuilder DefinePInvokeMethod (
427                                                 string name, 
428                                                 string dllName, 
429                                                 string entryName, MethodAttributes attributes, 
430                                                 CallingConventions callingConvention, 
431                                                 Type returnType, 
432                                                 Type[] returnTypeRequiredCustomModifiers, 
433                                                 Type[] returnTypeOptionalCustomModifiers, 
434                                                 Type[] parameterTypes, 
435                                                 Type[][] parameterTypeRequiredCustomModifiers, 
436                                                 Type[][] parameterTypeOptionalCustomModifiers, 
437                                                 CallingConvention nativeCallConv, 
438                                                 CharSet nativeCharSet) {
439                         check_name ("name", name);
440                         check_name ("dllName", dllName);
441                         check_name ("entryName", entryName);
442                         if ((attributes & MethodAttributes.Abstract) != 0)
443                                 throw new ArgumentException ("attributes", "PInvoke methods must be static and native and cannot be abstract.");
444                         if (IsInterface)
445                                 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");            
446                         if (is_created)
447                                 throw not_after_created ();
448
449                         MethodBuilder res 
450                                 = new MethodBuilder (
451                                                 this, 
452                                                 name, 
453                                                 attributes, 
454                                                 callingConvention,
455                                                 returnType, 
456                                                 returnTypeRequiredCustomModifiers, 
457                                                 returnTypeOptionalCustomModifiers, 
458                                                 parameterTypes, 
459                                                 parameterTypeRequiredCustomModifiers, 
460                                                 parameterTypeOptionalCustomModifiers,
461                                                 dllName, 
462                                                 entryName, 
463                                                 nativeCallConv, 
464                                                 nativeCharSet);
465                         append_method (res);
466                         return res;
467                 }
468
469                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
470                         return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
471                                 nativeCallConv, nativeCharSet);
472                 }
473
474                 public void DefineMethodOverride( MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) {
475                         if (methodInfoBody == null)
476                                 throw new ArgumentNullException ("methodInfoBody");
477                         if (methodInfoDeclaration == null)
478                                 throw new ArgumentNullException ("methodInfoDeclaration");
479                         if (is_created)
480                                 throw not_after_created ();
481
482                         if (methodInfoBody is MethodBuilder) {
483                                 MethodBuilder mb = (MethodBuilder)methodInfoBody;
484                                 mb.set_override (methodInfoDeclaration);
485                         }
486                 }
487
488                 public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) {
489                         return DefineField (fieldName, type, null, null, attributes);
490                 }
491
492 #if NET_1_2
493                 public
494 #else
495                 internal
496 #endif
497             FieldBuilder DefineField( string fieldName, Type type, Type[] requiredCustomAttributes, Type[] optionalCustomAttributes, FieldAttributes attributes) {
498                         check_name ("fieldName", fieldName);
499                         if (type == typeof (void))
500                                 throw new ArgumentException ("type",  "Bad field type in defining field.");
501                         if (is_created)
502                                 throw not_after_created ();
503
504                         FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomAttributes, optionalCustomAttributes);
505                         if (fields != null) {
506                                 if (fields.Length == num_fields) {
507                                         FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
508                                         System.Array.Copy (fields, new_fields, num_fields);
509                                         fields = new_fields;
510                                 }
511                                 fields [num_fields] = res;
512                                 num_fields ++;
513                         } else {
514                                 fields = new FieldBuilder [1];
515                                 fields [0] = res;
516                                 num_fields ++;
517                                 create_internal_class (this);
518                         }
519                         return res;
520                 }
521
522                 public PropertyBuilder DefineProperty( string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
523                         check_name ("name", name);
524                         if (parameterTypes != null)
525                                 foreach (Type param in parameterTypes)
526                                         if (param == null)
527                                                 throw new ArgumentNullException ("parameterTypes");
528                         if (is_created)
529                                 throw not_after_created ();
530
531                         PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, parameterTypes);
532
533                         if (properties != null) {
534                                 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
535                                 System.Array.Copy (properties, new_properties, properties.Length);
536                                 new_properties [properties.Length] = res;
537                                 properties = new_properties;
538                         } else {
539                                 properties = new PropertyBuilder [1];
540                                 properties [0] = res;
541                         }
542                         return res;
543                 }
544
545                 public ConstructorBuilder DefineTypeInitializer() {
546                         return DefineConstructor (MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, null);
547                 }
548
549                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
550                 private extern Type create_runtime_class (TypeBuilder tb);
551
552                 private bool is_nested_in (Type t) {
553                         while (t != null) {
554                                 if (t == this)
555                                         return true;
556                                 else
557                                         t = t.DeclaringType;
558                         }
559                         return false;
560                 }
561                 
562                 public Type CreateType() {
563                         /* handle nesting_type */
564                         if (is_created)
565                                 throw not_after_created ();
566
567                         // Fire TypeResolve events for fields whose type is an unfinished
568                         // value type.
569                         if (fields != null) {
570                                 foreach (FieldBuilder fb in fields) {
571                                         if (fb == null)
572                                                 continue;
573                                         Type ft = fb.FieldType;
574                                         if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
575                                                 TypeBuilder tb = (TypeBuilder)ft;
576                                                 if (!tb.is_created) {
577                                                         AppDomain.CurrentDomain.DoTypeResolve (tb);
578                                                         if (!tb.is_created) {
579                                                                 // FIXME: We should throw an exception here,
580                                                                 // but mcs expects that the type is created
581                                                                 // even if the exception is thrown
582                                                                 //throw new TypeLoadException ("Could not load type " + tb);
583                                                         }
584                                                 }
585                                         }
586                                 }
587                         }
588
589                         if (methods != null) {
590                                 for (int i = 0; i < num_methods; ++i)
591                                         ((MethodBuilder)(methods[i])).fixup ();
592                         }
593
594                         //
595                         // On classes, define a default constructor if not provided
596                         //
597                         if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>"))
598                                 DefineDefaultConstructor (MethodAttributes.Public);
599
600                         if (ctors != null){
601                                 foreach (ConstructorBuilder ctor in ctors) 
602                                         ctor.fixup ();
603                         }
604
605                         created = create_runtime_class (this);
606                         if (created != null)
607                                 return created;
608                         return this;
609                 }
610
611                 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
612                 {
613                         if (ctors == null)
614                                 return new ConstructorInfo [0];
615                         ArrayList l = new ArrayList ();
616                         bool match;
617                         MethodAttributes mattrs;
618                         
619                         foreach (ConstructorBuilder c in ctors) {
620                                 match = false;
621                                 mattrs = c.Attributes;
622                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
623                                         if ((bindingAttr & BindingFlags.Public) != 0)
624                                                 match = true;
625                                 } else {
626                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
627                                                 match = true;
628                                 }
629                                 if (!match)
630                                         continue;
631                                 match = false;
632                                 if ((mattrs & MethodAttributes.Static) != 0) {
633                                         if ((bindingAttr & BindingFlags.Static) != 0)
634                                                 match = true;
635                                 } else {
636                                         if ((bindingAttr & BindingFlags.Instance) != 0)
637                                                 match = true;
638                                 }
639                                 if (!match)
640                                         continue;
641                                 l.Add (c);
642                         }
643                         ConstructorInfo[] result = new ConstructorInfo [l.Count];
644                         l.CopyTo (result);
645                         return result;
646                 }
647
648                 public override Type GetElementType () { 
649                         throw not_supported ();
650                 }
651
652                 public override EventInfo GetEvent (string name, BindingFlags bindingAttr) {
653                         throw not_supported ();
654                 }
655
656                 /* Needed to keep signature compatibility with MS.NET */
657                 public override EventInfo[] GetEvents ()
658                 {
659                         return GetEvents (DefaultBindingFlags);
660                 }
661
662                 public override EventInfo[] GetEvents (BindingFlags bindingAttr) {
663                         // FIXME: Under MS.NET, this throws a NotImplementedException
664                         // But mcs calls this method. How can that be?
665                         return new EventInfo [0];
666                 }
667
668                 public override FieldInfo GetField( string name, BindingFlags bindingAttr) {
669                         if (fields == null)
670                                 return null;
671
672                         bool match;
673                         FieldAttributes mattrs;
674                         
675                         foreach (FieldInfo c in fields) {
676                                 if (c == null)
677                                         continue;
678                                 if (c.Name != name)
679                                         continue;
680                                 match = false;
681                                 mattrs = c.Attributes;
682                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
683                                         if ((bindingAttr & BindingFlags.Public) != 0)
684                                                 match = true;
685                                 } else {
686                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
687                                                 match = true;
688                                 }
689                                 if (!match)
690                                         continue;
691                                 match = false;
692                                 if ((mattrs & FieldAttributes.Static) != 0) {
693                                         if ((bindingAttr & BindingFlags.Static) != 0)
694                                                 match = true;
695                                 } else {
696                                         if ((bindingAttr & BindingFlags.Instance) != 0)
697                                                 match = true;
698                                 }
699                                 if (!match)
700                                         continue;
701                                 return c;
702                         }
703                         return null;
704                 }
705
706                 public override FieldInfo[] GetFields (BindingFlags bindingAttr) {
707                         if (fields == null)
708                                 return new FieldInfo [0];
709                         ArrayList l = new ArrayList ();
710                         bool match;
711                         FieldAttributes mattrs;
712                         
713                         foreach (FieldInfo c in fields) {
714                                 if (c == null)
715                                         continue;
716                                 match = false;
717                                 mattrs = c.Attributes;
718                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
719                                         if ((bindingAttr & BindingFlags.Public) != 0)
720                                                 match = true;
721                                 } else {
722                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
723                                                 match = true;
724                                 }
725                                 if (!match)
726                                         continue;
727                                 match = false;
728                                 if ((mattrs & FieldAttributes.Static) != 0) {
729                                         if ((bindingAttr & BindingFlags.Static) != 0)
730                                                 match = true;
731                                 } else {
732                                         if ((bindingAttr & BindingFlags.Instance) != 0)
733                                                 match = true;
734                                 }
735                                 if (!match)
736                                         continue;
737                                 l.Add (c);
738                         }
739                         FieldInfo[] result = new FieldInfo [l.Count];
740                         l.CopyTo (result);
741                         return result;
742                 }
743
744                 public override Type GetInterface (string name, bool ignoreCase) {
745                         throw not_supported ();
746                 }
747                 
748                 public override Type[] GetInterfaces () {
749                         if (interfaces != null) {
750                                 Type[] ret = new Type [interfaces.Length];
751                                 interfaces.CopyTo (ret, 0);
752                                 return ret;
753                         } else {
754                                 return Type.EmptyTypes;
755                         }
756                 }
757
758                 public override MemberInfo[] GetMember (string name, MemberTypes type,
759                                                                                                 BindingFlags bindingAttr) {
760                         throw not_supported ();
761                 }
762
763                 public override MemberInfo[] GetMembers (BindingFlags bindingAttr) {
764                         throw not_supported ();
765                 }
766
767                 public override MethodInfo[] GetMethods (BindingFlags bindingAttr) {
768                         if (methods == null)
769                                 return new MethodInfo [0];
770                         ArrayList l = new ArrayList ();
771                         bool match;
772                         MethodAttributes mattrs;
773
774                         foreach (MethodInfo c in methods) {
775                                 if (c == null)
776                                         continue;
777                                 match = false;
778                                 mattrs = c.Attributes;
779                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
780                                         if ((bindingAttr & BindingFlags.Public) != 0)
781                                                 match = true;
782                                 } else {
783                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
784                                                 match = true;
785                                 }
786                                 if (!match)
787                                         continue;
788                                 match = false;
789                                 if ((mattrs & MethodAttributes.Static) != 0) {
790                                         if ((bindingAttr & BindingFlags.Static) != 0)
791                                                 match = true;
792                                 } else {
793                                         if ((bindingAttr & BindingFlags.Instance) != 0)
794                                                 match = true;
795                                 }
796                                 if (!match)
797                                         continue;
798                                 l.Add (c);
799                         }
800                         MethodInfo[] result = new MethodInfo [l.Count];
801                         l.CopyTo (result);
802                         return result;
803                 }
804
805                 protected override MethodInfo GetMethodImpl( string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) {
806                         throw not_supported ();
807                 }
808                 
809                 public override Type GetNestedType( string name, BindingFlags bindingAttr) {
810                         throw not_supported ();
811                 }
812
813                 public override Type[] GetNestedTypes (BindingFlags bindingAttr) {
814                         bool match;
815                         ArrayList result = new ArrayList ();
816                 
817                         if (subtypes == null)
818                                 return Type.EmptyTypes;
819                         foreach (TypeBuilder t in subtypes) {
820                                 match = false;
821                                 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
822                                         if ((bindingAttr & BindingFlags.Public) != 0)
823                                                 match = true;
824                                 } else {
825                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
826                                                 match = true;
827                                 }
828                                 if (!match)
829                                         continue;
830                                 result.Add (t);
831                         }
832                         Type[] r = new Type [result.Count];
833                         result.CopyTo (r);
834                         return r;
835                 }
836
837                 public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) {
838                         if (properties == null)
839                                 return new PropertyInfo [0];
840                         ArrayList l = new ArrayList ();
841                         bool match;
842                         MethodAttributes mattrs;
843                         MethodInfo accessor;
844                         
845                         foreach (PropertyInfo c in properties) {
846                                 match = false;
847                                 accessor = c.GetGetMethod (true);
848                                 if (accessor == null)
849                                         accessor = c.GetSetMethod (true);
850                                 if (accessor == null)
851                                         continue;
852                                 mattrs = accessor.Attributes;
853                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
854                                         if ((bindingAttr & BindingFlags.Public) != 0)
855                                                 match = true;
856                                 } else {
857                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
858                                                 match = true;
859                                 }
860                                 if (!match)
861                                         continue;
862                                 match = false;
863                                 if ((mattrs & MethodAttributes.Static) != 0) {
864                                         if ((bindingAttr & BindingFlags.Static) != 0)
865                                                 match = true;
866                                 } else {
867                                         if ((bindingAttr & BindingFlags.Instance) != 0)
868                                                 match = true;
869                                 }
870                                 if (!match)
871                                         continue;
872                                 l.Add (c);
873                         }
874                         PropertyInfo[] result = new PropertyInfo [l.Count];
875                         l.CopyTo (result);
876                         return result;
877                 }
878                 
879                 protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
880                         throw not_supported ();
881                 }
882
883                 protected override bool HasElementTypeImpl () {
884                         // According to the MSDN docs, this is supported for TypeBuilders,
885                         // but in reality, it is not
886                         throw not_supported ();
887                         //                      return IsArrayImpl() || IsByRefImpl() || IsPointerImpl ();
888                 }
889
890                 public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
891                         throw not_supported ();
892                 }
893
894                 protected override bool IsArrayImpl ()
895                 {
896                         return Type.IsArrayImpl (this);
897                 }
898
899                 protected override bool IsByRefImpl () {
900                         // FIXME
901                         return false;
902                 }
903                 protected override bool IsCOMObjectImpl () {
904                         return false;
905                 }
906                 protected override bool IsPointerImpl () {
907                         // FIXME
908                         return false;
909                 }
910                 protected override bool IsPrimitiveImpl () {
911                         // FIXME
912                         return false;
913                 }
914                 protected override bool IsValueTypeImpl () {
915                         return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
916                                 this != pmodule.assemblyb.corlib_value_type &&
917                                 this != pmodule.assemblyb.corlib_enum_type);
918                 }
919                 
920                 public override RuntimeTypeHandle TypeHandle { 
921                         get { 
922                                 throw not_supported (); 
923                         } 
924                 }
925
926                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
927                         if (customBuilder == null)
928                                 throw new ArgumentNullException ("customBuilder");
929
930                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
931                         if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
932                                 byte[] data = customBuilder.Data;
933                                 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
934                                 layout_kind = (int)data [2];
935                                 layout_kind |= ((int)data [3]) << 8;
936                                 attrs &= ~TypeAttributes.LayoutMask;
937                                 switch ((LayoutKind)layout_kind) {
938                                 case LayoutKind.Auto:
939                                         attrs |= TypeAttributes.AutoLayout;
940                                         break;
941                                 case LayoutKind.Explicit:
942                                         attrs |= TypeAttributes.ExplicitLayout;
943                                         break;
944                                 case LayoutKind.Sequential:
945                                         attrs |= TypeAttributes.SequentialLayout;
946                                         break;
947                                 default:
948                                         // we should ignore it since it can be any value anyway...
949                                         throw new Exception ("Error in customattr");
950                                 }
951                                 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
952                                 int pos = 6;
953                                 if (first_type_name == "System.Int16")
954                                         pos = 4;
955                                 int nnamed = (int)data [pos++];
956                                 nnamed |= ((int)data [pos++]) << 8;
957                                 for (int i = 0; i < nnamed; ++i) {
958                                         byte named_type = data [pos++];
959                                         byte type = data [pos++];
960                                         int len = CustomAttributeBuilder.decode_len (data, pos, out pos);
961                                         string named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
962                                         pos += len;
963                                         /* all the fields are integers in StructLayout */
964                                         int value = (int)data [pos++];
965                                         value |= ((int)data [pos++]) << 8;
966                                         value |= ((int)data [pos++]) << 16;
967                                         value |= ((int)data [pos++]) << 24;
968                                         switch (named_name) {
969                                         case "CharSet":
970                                                 switch ((CharSet)value) {
971                                                 case CharSet.None:
972                                                 case CharSet.Ansi:
973                                                         break;
974                                                 case CharSet.Unicode:
975                                                         attrs |= TypeAttributes.UnicodeClass;
976                                                         break;
977                                                 case CharSet.Auto:
978                                                         attrs |= TypeAttributes.AutoClass;
979                                                         break;
980                                                 default:
981                                                         break; // error out...
982                                                 }
983                                                 break;
984                                         case "Pack":
985                                                 packing_size = (PackingSize)value;
986                                                 break;
987                                         case "Size":
988                                                 class_size = value;
989                                                 break;
990                                         default:
991                                                 break; // error out...
992                                         }
993                                 }
994                                 return;
995                         } else if (attrname == "System.SerializableAttribute") {
996                                 attrs |= TypeAttributes.Serializable;
997                                 return;
998                         }
999                         if (cattrs != null) {
1000                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1001                                 cattrs.CopyTo (new_array, 0);
1002                                 new_array [cattrs.Length] = customBuilder;
1003                                 cattrs = new_array;
1004                         } else {
1005                                 cattrs = new CustomAttributeBuilder [1];
1006                                 cattrs [0] = customBuilder;
1007                         }
1008                 }
1009                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
1010                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1011                 }
1012
1013                 public EventBuilder DefineEvent( string name, EventAttributes attributes, Type eventtype) {
1014                         check_name ("name", name);
1015                         if (eventtype == null)
1016                                 throw new ArgumentNullException ("eventtype");
1017                         if (is_created)
1018                                 throw not_after_created ();
1019
1020                         EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1021                         if (events != null) {
1022                                 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1023                                 System.Array.Copy (events, new_events, events.Length);
1024                                 new_events [events.Length] = res;
1025                                 events = new_events;
1026                         } else {
1027                                 events = new EventBuilder [1];
1028                                 events [0] = res;
1029                         }
1030                         return res;
1031                 }
1032
1033                 static int InitializedDataCount = 0;
1034                 
1035                 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
1036                         check_name ("name", name);
1037                         if (data == null)
1038                                 throw new ArgumentNullException ("data");
1039                         if ((data.Length == 0) || (data.Length > 0x3f0000))
1040                                 throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
1041                         if (is_created)
1042                                 throw not_after_created ();
1043
1044                         string s = "$ArrayType$"+InitializedDataCount.ToString();
1045                         TypeBuilder datablobtype = DefineNestedType (s,
1046                                 TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1047                                 pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, data.Length);
1048                         datablobtype.CreateType ();
1049                         FieldBuilder res = DefineField (name, datablobtype, attributes|FieldAttributes.Assembly|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1050                         res.SetRVAData (data);
1051                         InitializedDataCount++;
1052                         return res;
1053                 }
1054
1055                 [MonoTODO]
1056                 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
1057                         check_name ("name", name);
1058                         if ((size <= 0) || (size > 0x3f0000))
1059                                 throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
1060                         if (is_created)
1061                                 throw not_after_created ();
1062
1063                         throw new NotImplementedException ();
1064                 }
1065
1066                 public TypeToken TypeToken {
1067                         get {
1068                                 return new TypeToken (0x02000000 | table_idx);
1069                         }
1070                 }
1071                 public void SetParent (Type parentType) {
1072                         if (parentType == null)
1073                                 throw new ArgumentNullException ("parentType");
1074                         if (is_created)
1075                                 throw not_after_created ();
1076
1077                         parent = parentType;
1078                 }
1079                 internal int get_next_table_index (object obj, int table, bool inc) {
1080                         return pmodule.get_next_table_index (obj, table, inc);
1081                 }
1082
1083                 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1084                 {
1085                         if (created == null)
1086                                 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1087
1088                         return created.GetInterfaceMap (interfaceType);
1089                 }
1090
1091                 internal bool is_created {
1092                         get {
1093                                 return created != null;
1094                         }
1095                 }
1096
1097                 private Exception not_supported ()
1098                 {
1099                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1100                 }
1101
1102                 private Exception not_after_created ()
1103                 {
1104                         return new InvalidOperationException ("Unable to change after type has been created.");
1105                 }
1106
1107                 private void check_name (string argName, string name)
1108                 {
1109                         if (name == null)
1110                                 throw new ArgumentNullException (argName);
1111                         if (name == "")
1112                                 throw new ArgumentException (argName, "Empty name is not legal.");
1113                         if (name.IndexOf ((char)0) != -1)
1114                                 throw new ArgumentException (argName, "Illegal name.");
1115                 }
1116
1117 #if NET_1_2
1118                 public override Type GetGenericTypeDefinition ()
1119                 {
1120                         setup_generic_class (this);
1121
1122                         return base.GetGenericTypeDefinition ();
1123                 }
1124
1125                 public override bool HasGenericArguments {
1126                         get {
1127                                 throw new NotImplementedException ();
1128                         }
1129                 }
1130
1131                 public override bool ContainsGenericParameters {
1132                         get {
1133                                 throw new NotImplementedException ();
1134                         }
1135                 }
1136
1137                 public extern override bool IsGenericParameter {
1138                         [MethodImplAttribute(MethodImplOptions.InternalCall)]
1139                         get;
1140                 }
1141
1142                 public override int GenericParameterPosition {
1143                         get {
1144                                 throw new NotImplementedException ();
1145                         }
1146                 }
1147
1148                 public override MethodInfo DeclaringMethod {
1149                         get {
1150                                 throw new NotImplementedException ();
1151                         }
1152                 }
1153
1154                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1155                 private extern MonoGenericParam define_generic_parameter (string name, int index);
1156                 
1157                 public Type DefineGenericParameter (string name)
1158                 {
1159                         int index;
1160                         if (generic_params != null) {
1161                                 MonoGenericParam[] new_generic_params = new MonoGenericParam [generic_params.Length+1];
1162                                 System.Array.Copy (generic_params, new_generic_params, generic_params.Length);
1163                                 index = generic_params.Length;
1164                                 generic_params = new_generic_params;
1165                         } else {
1166                                 generic_params = new MonoGenericParam [1];
1167                                 index = 0;
1168                         }
1169
1170                         generic_params [index] = define_generic_parameter (name, index);
1171                         return generic_params [index];
1172                 }
1173
1174                 public void SetGenericParameterConstraints (int index, Type[] constraints)
1175                 {
1176                         generic_params [index].SetConstraints (constraints);
1177                 }
1178
1179                 public MethodBuilder DefineGenericMethod (string name, MethodAttributes attributes)
1180                 {
1181                         return DefineMethod (name, attributes, CallingConventions.Standard, null, null);
1182                 }
1183 #endif
1184         }
1185 }