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