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