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