merge -r 58060:58217
[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 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System;
34 using System.Text;
35 using System.Reflection;
36 using System.Reflection.Emit;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39 using System.Globalization;
40 using System.Collections;
41 using System.Security;
42 using System.Security.Permissions;
43 using System.Diagnostics.SymbolStore;
44
45 namespace System.Reflection.Emit {
46 #if NET_2_0
47         [ComVisible (true)]
48         [ComDefaultInterface (typeof (_TypeBuilder))]
49 #endif
50         [ClassInterface (ClassInterfaceType.None)]
51         public sealed class TypeBuilder : Type, _TypeBuilder {
52         #region Sync with reflection.h
53         private string tname;
54         private string nspace;
55         private Type parent;
56         private Type nesting_type;
57         private Type[] interfaces;
58         private int num_methods;
59         private MethodBuilder[] methods;
60         private ConstructorBuilder[] ctors;
61         private PropertyBuilder[] properties;
62         private int num_fields;
63         private FieldBuilder[] fields;
64         private EventBuilder[] events;
65         private CustomAttributeBuilder[] cattrs;
66         internal TypeBuilder[] subtypes;
67         internal TypeAttributes attrs;
68         private int table_idx;
69         private ModuleBuilder pmodule;
70         private int class_size;
71         private PackingSize packing_size;
72         private IntPtr generic_container;
73 #if NET_2_0 || BOOTSTRAP_NET_2_0
74         private GenericTypeParameterBuilder[] generic_params;
75 #else
76         private Object generic_params; /* so offsets don't change */
77 #endif
78         private RefEmitPermissionSet[] permissions;     
79         private Type created;
80         #endregion
81         string fullname;
82
83         public const int UnspecifiedTypeSize = 0;
84
85                 protected override TypeAttributes GetAttributeFlagsImpl () {
86                         return attrs;
87                 }
88                 
89                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
90                 private extern void setup_internal_class (TypeBuilder tb);
91                 
92                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
93                 private extern void create_internal_class (TypeBuilder tb);
94                 
95                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
96                 private extern void setup_generic_class ();
97
98                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
99                 private extern void create_generic_class ();
100
101                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
102                 private extern EventInfo get_event_info (EventBuilder eb);
103
104                 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr) {
105                         this.parent = null;
106                         this.attrs = attr;
107                         this.class_size = UnspecifiedTypeSize;
108                         this.table_idx = 1;
109                         fullname = this.tname = "<Module>";
110                         this.nspace = "";
111                         pmodule = mb;
112                         setup_internal_class (this);
113                 }
114
115                 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type) {
116                         int sep_index;
117                         this.parent = parent;
118                         this.attrs = attr;
119                         this.class_size = type_size;
120                         this.packing_size = packing_size;
121                         this.nesting_type = nesting_type;
122                         sep_index = name.LastIndexOf('.');
123                         if (sep_index != -1) {
124                                 this.tname = name.Substring (sep_index + 1);
125                                 this.nspace = name.Substring (0, sep_index);
126                         } else {
127                                 this.tname = name;
128                                 this.nspace = "";
129                         }
130                         if (interfaces != null) {
131                                 this.interfaces = new Type[interfaces.Length];
132                                 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
133                         }
134                         pmodule = mb;
135                         // skip .<Module> ?
136                         table_idx = mb.get_next_table_index (this, 0x02, true);
137                         setup_internal_class (this);
138                         fullname = GetFullName ();
139                 }
140
141                 public override Assembly Assembly {
142                         get {return pmodule.Assembly;}
143                 }
144
145                 public override string AssemblyQualifiedName {
146                         get {
147                                 return fullname + ", " + Assembly.GetName().FullName;
148                         }
149                 }
150                 public override Type BaseType {
151                         get {
152                                 return parent;
153                         }
154                 }
155                 public override Type DeclaringType {get {return nesting_type;}}
156
157 /*              public override bool IsSubclassOf (Type c)
158                 {
159                         Type t;
160                         if (c == null)
161                                 return false;
162                         if (c == this)
163                                 return false;
164                         t = parent;
165                         while (t != null) {
166                                 if (c == t)
167                                         return true;
168                                 t = t.BaseType;
169                         }
170                         return false;
171                 }*/
172
173                 [MonoTODO]
174                 public override Type UnderlyingSystemType {
175                         get {
176
177                                 // Return this as requested by Zoltan.
178                                 
179                                 return this;
180
181 #if false
182                                 // Dont know what to do with the rest, should be killed:
183                                 // See bug: 75008.
184                                 //
185                                 ////// This should return the type itself for non-enum types but 
186                                 ////// that breaks mcs.
187                                 if (fields != null) {
188                                         foreach (FieldBuilder f in fields) {
189                                                 if ((f != null) && (f.Attributes & FieldAttributes.Static) == 0)
190                                                         return f.FieldType;
191                                         }
192                                 }
193                                 throw new InvalidOperationException ("Underlying type information on enumeration is not specified.");
194 #endif
195                         }
196                 }
197
198                 string GetFullName () {
199                         if (nesting_type != null)
200                                 return String.Concat (nesting_type.FullName, "+", tname);
201                         if ((nspace != null) && (nspace.Length > 0))
202                                 return String.Concat (nspace, ".", tname);
203                         return tname;
204                 }
205         
206                 public override string FullName {
207                         get {
208                                 return fullname;
209                         }
210                 }
211         
212                 public override Guid GUID {
213                         get {
214                                 check_created ();
215                                 return created.GUID;
216                         }
217                 }
218
219                 public override Module Module {
220                         get {return pmodule;}
221                 }
222                 public override string Name {
223                         get {return tname;}
224                 }
225                 public override string Namespace {
226                         get {return nspace;}
227                 }
228                 public PackingSize PackingSize {
229                         get {return packing_size;}
230                 }
231                 public int Size {
232                         get { return class_size; }
233                 }
234                 public override Type ReflectedType {get {return nesting_type;}}
235
236                 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
237                         if (pset == null)
238                                 throw new ArgumentNullException ("pset");
239                         if ((action == SecurityAction.RequestMinimum) ||
240                                 (action == SecurityAction.RequestOptional) ||
241                                 (action == SecurityAction.RequestRefuse))
242                                 throw new ArgumentException ("Request* values are not permitted", "action");
243
244                         check_not_created ();
245
246                         if (permissions != null) {
247                                 /* Check duplicate actions */
248                                 foreach (RefEmitPermissionSet set in permissions)
249                                         if (set.action == action)
250                                                 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
251
252                                 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
253                                 permissions.CopyTo (new_array, 0);
254                                 permissions = new_array;
255                         }
256                         else
257                                 permissions = new RefEmitPermissionSet [1];
258
259                         permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
260                         attrs |= TypeAttributes.HasSecurity;
261                 }
262
263 #if NET_2_0
264                 [ComVisible (true)]
265 #endif
266                 public void AddInterfaceImplementation( Type interfaceType) {
267                         if (interfaceType == null)
268                                 throw new ArgumentNullException ("interfaceType");
269                         check_not_created ();
270
271                         if (interfaces != null) {
272                                 // Check for duplicates
273                                 foreach (Type t in interfaces)
274                                         if (t == interfaceType)
275                                                 return;
276
277                                 Type[] ifnew = new Type [interfaces.Length + 1];
278                                 interfaces.CopyTo (ifnew, 0);
279                                 ifnew [interfaces.Length] = interfaceType;
280                                 interfaces = ifnew;
281                         } else {
282                                 interfaces = new Type [1];
283                                 interfaces [0] = interfaceType;
284                         }
285                 }
286
287                 [MonoTODO]
288                 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
289                                                                        CallingConventions callConvention, Type[] types,
290                                                                        ParameterModifier[] modifiers)
291                 {
292                         check_created ();
293                         
294                         if (ctors == null)
295                                 return null;
296
297                         ConstructorBuilder found = null;
298                         int count = 0;
299                         
300                         foreach (ConstructorBuilder cb in ctors){
301                                 if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
302                                         continue;
303                                 found = cb;
304                                 count++;
305                         }
306
307                         if (count == 0)
308                                 return null;
309                         if (types == null){
310                                 if (count > 1)
311                                         throw new AmbiguousMatchException ();
312                                 return found;
313                         }
314                         MethodBase[] match = new MethodBase [count];
315                         if (count == 1)
316                                 match [0] = found;
317                         else {
318                                 count = 0;
319                                 foreach (ConstructorInfo m in ctors) {
320                                         if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
321                                                 continue;
322                                         match [count++] = m;
323                                 }
324                         }
325                         if (binder == null)
326                                 binder = Binder.DefaultBinder;
327                         return (ConstructorInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
328                 }
329
330                 public override bool IsDefined( Type attributeType, bool inherit)
331                 {
332                         /*
333                          * MS throws NotSupported here, but we can't because some corlib
334                          * classes make calls to IsDefined.
335                          */
336                         return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
337                 }
338                 
339                 public override object[] GetCustomAttributes(bool inherit)
340                 {
341                         check_created ();
342
343                         return created.GetCustomAttributes (inherit);
344                 }
345                 
346                 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
347                 {
348                         check_created ();
349
350                         return created.GetCustomAttributes (attributeType, inherit);
351                 }
352
353                 public TypeBuilder DefineNestedType (string name) {
354                         return DefineNestedType (name, TypeAttributes.NestedPrivate, pmodule.assemblyb.corlib_object_type, null);
355                 }
356
357                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr) {
358                         return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
359                 }
360
361                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) {
362                         return DefineNestedType (name, attr, parent, null);
363                 }
364
365                 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
366                                                       PackingSize packsize, int typesize)
367                 {
368                         check_name ("name", name);
369                         // Visibility must be NestedXXX
370                         /* This breaks mcs
371                         if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
372                                 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
373                                 throw new ArgumentException ("attr", "Bad type flags for nested type.");
374                         */
375                         if (interfaces != null)
376                                 foreach (Type iface in interfaces)
377                                         if (iface == null)
378                                                 throw new ArgumentNullException ("interfaces");
379
380                         TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packsize, typesize, this);
381                         res.fullname = res.GetFullName ();
382                         pmodule.RegisterTypeName (res, res.fullname);
383                         if (subtypes != null) {
384                                 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
385                                 System.Array.Copy (subtypes, new_types, subtypes.Length);
386                                 new_types [subtypes.Length] = res;
387                                 subtypes = new_types;
388                         } else {
389                                 subtypes = new TypeBuilder [1];
390                                 subtypes [0] = res;
391                         }
392                         return res;
393                 }
394
395 #if NET_2_0
396                 [ComVisible (true)]
397 #endif
398                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
399                         return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
400                 }
401
402                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
403                         return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typesize);
404                 }
405
406                 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
407                         return DefineNestedType (name, attr, parent, null, packsize, UnspecifiedTypeSize);
408                 }
409
410 #if NET_2_0
411                 [ComVisible (true)]
412 #endif
413                 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) {
414                         return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
415                 }
416
417 #if NET_2_0
418                 [ComVisible (true)]
419 #endif
420 #if NET_2_0 || BOOTSTRAP_NET_2_0
421                 public
422 #else
423                 internal
424 #endif
425                 ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
426                 {
427                         check_not_created ();
428                         ConstructorBuilder cb = new ConstructorBuilder (this, attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
429                         if (ctors != null) {
430                                 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
431                                 System.Array.Copy (ctors, new_ctors, ctors.Length);
432                                 new_ctors [ctors.Length] = cb;
433                                 ctors = new_ctors;
434                         } else {
435                                 ctors = new ConstructorBuilder [1];
436                                 ctors [0] = cb;
437                         }
438                         return cb;
439                 }
440
441 #if NET_2_0
442                 [ComVisible (true)]
443 #endif
444                 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
445                 {
446                         Type parent_type;
447
448                         if (parent != null)
449                                 parent_type = parent;
450                         else
451                                 parent_type = pmodule.assemblyb.corlib_object_type;
452
453                         ConstructorInfo parent_constructor =
454                                 parent_type.GetConstructor (
455                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
456                                         null, Type.EmptyTypes, null);
457                         if (parent_constructor == null) {
458                                 throw new NotSupportedException ("Parent does"
459                                         + " not have a default constructor."
460                                         + " The default constructor must be"
461                                         + " explicitly defined.");
462                         }
463
464                         ConstructorBuilder cb = DefineConstructor (attributes, 
465                                 CallingConventions.Standard, new Type[0]);
466                         ILGenerator ig = cb.GetILGenerator ();
467                         ig.Emit (OpCodes.Ldarg_0);
468                         ig.Emit (OpCodes.Call, parent_constructor);
469                         ig.Emit (OpCodes.Ret);
470                         return cb;
471                 }
472
473                 private void append_method (MethodBuilder mb) {
474                         if (methods != null) {
475                                 if (methods.Length == num_methods) {
476                                         MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
477                                         System.Array.Copy (methods, new_methods, num_methods);
478                                         methods = new_methods;
479                                 }
480                         } else {
481                                 methods = new MethodBuilder [1];
482                         }
483                         methods [num_methods] = mb;
484                         num_methods ++;
485                 }
486
487                 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
488                         return DefineMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
489                 }
490
491                 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
492                         return DefineMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
493                 }
494
495 #if NET_2_0 || BOOTSTRAP_NET_2_0
496                 public
497 #else
498                 internal
499 #endif
500                 MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
501                         check_name ("name", name);
502                         check_not_created ();
503                         if (IsInterface && (
504                                 !((attributes & MethodAttributes.Abstract) != 0) || 
505                                 !((attributes & MethodAttributes.Virtual) != 0)))
506                                 throw new ArgumentException ("attributes", "Interface method must be abstract and virtual.");
507
508                         if (returnType == null)
509                                 returnType = pmodule.assemblyb.corlib_void_type;
510                         MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
511                         append_method (res);
512                         return res;
513                 }
514
515                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
516                         return DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet);
517                 }
518
519 #if NET_2_0 || BOOTSTRAP_NET_2_0
520                 public
521 #else
522                 internal
523 #endif
524                 MethodBuilder DefinePInvokeMethod (
525                                                 string name, 
526                                                 string dllName, 
527                                                 string entryName, MethodAttributes attributes, 
528                                                 CallingConventions callingConvention, 
529                                                 Type returnType, 
530                                                 Type[] returnTypeRequiredCustomModifiers, 
531                                                 Type[] returnTypeOptionalCustomModifiers, 
532                                                 Type[] parameterTypes, 
533                                                 Type[][] parameterTypeRequiredCustomModifiers, 
534                                                 Type[][] parameterTypeOptionalCustomModifiers, 
535                                                 CallingConvention nativeCallConv, 
536                                                 CharSet nativeCharSet) {
537                         check_name ("name", name);
538                         check_name ("dllName", dllName);
539                         check_name ("entryName", entryName);
540                         if ((attributes & MethodAttributes.Abstract) != 0)
541                                 throw new ArgumentException ("attributes", "PInvoke methods must be static and native and cannot be abstract.");
542                         if (IsInterface)
543                                 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");            
544                         check_not_created ();
545
546                         MethodBuilder res 
547                                 = new MethodBuilder (
548                                                 this, 
549                                                 name, 
550                                                 attributes, 
551                                                 callingConvention,
552                                                 returnType, 
553                                                 returnTypeRequiredCustomModifiers, 
554                                                 returnTypeOptionalCustomModifiers, 
555                                                 parameterTypes, 
556                                                 parameterTypeRequiredCustomModifiers, 
557                                                 parameterTypeOptionalCustomModifiers,
558                                                 dllName, 
559                                                 entryName, 
560                                                 nativeCallConv, 
561                                                 nativeCharSet);
562                         append_method (res);
563                         return res;
564                 }
565
566                 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
567                         return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
568                                 nativeCallConv, nativeCharSet);
569                 }
570
571 #if NET_2_0
572                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes) {
573                         return DefineMethod (name, attributes, CallingConventions.Standard);
574                 }
575
576                 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callConv) {
577                         return DefineMethod (name, attributes, callConv, null, null);
578                 }
579 #endif
580
581                 public void DefineMethodOverride( MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) {
582                         if (methodInfoBody == null)
583                                 throw new ArgumentNullException ("methodInfoBody");
584                         if (methodInfoDeclaration == null)
585                                 throw new ArgumentNullException ("methodInfoDeclaration");
586                         check_not_created ();
587
588                         if (methodInfoBody is MethodBuilder) {
589                                 MethodBuilder mb = (MethodBuilder)methodInfoBody;
590                                 mb.set_override (methodInfoDeclaration);
591                         }
592                 }
593
594                 public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) {
595                         return DefineField (fieldName, type, null, null, attributes);
596                 }
597
598 #if NET_2_0 || BOOTSTRAP_NET_2_0
599                 public
600 #else
601                 internal
602 #endif
603             FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomAttributes, Type[] optionalCustomAttributes, FieldAttributes attributes) {
604                         check_name ("fieldName", fieldName);
605                         if (type == typeof (void))
606                                 throw new ArgumentException ("type",  "Bad field type in defining field.");
607                         check_not_created ();
608
609                         FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomAttributes, optionalCustomAttributes);
610                         if (fields != null) {
611                                 if (fields.Length == num_fields) {
612                                         FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
613                                         System.Array.Copy (fields, new_fields, num_fields);
614                                         fields = new_fields;
615                                 }
616                                 fields [num_fields] = res;
617                                 num_fields ++;
618                         } else {
619                                 fields = new FieldBuilder [1];
620                                 fields [0] = res;
621                                 num_fields ++;
622                                 create_internal_class (this);
623                         }
624                         return res;
625                 }
626
627                 public PropertyBuilder DefineProperty( string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
628                         return DefineProperty (name, attributes, returnType, null, null, parameterTypes, null, null);
629                 }
630
631 #if NET_2_0
632                 public 
633 #else
634                 internal
635 #endif
636                 PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
637                         check_name ("name", name);
638                         if (parameterTypes != null)
639                                 foreach (Type param in parameterTypes)
640                                         if (param == null)
641                                                 throw new ArgumentNullException ("parameterTypes");
642                         check_not_created ();
643
644                         PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
645
646                         if (properties != null) {
647                                 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
648                                 System.Array.Copy (properties, new_properties, properties.Length);
649                                 new_properties [properties.Length] = res;
650                                 properties = new_properties;
651                         } else {
652                                 properties = new PropertyBuilder [1];
653                                 properties [0] = res;
654                         }
655                         return res;
656                 }
657
658 #if NET_2_0
659                 [ComVisible (true)]
660 #endif
661                 public ConstructorBuilder DefineTypeInitializer() {
662                         return DefineConstructor (MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, null);
663                 }
664
665                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
666                 private extern Type create_runtime_class (TypeBuilder tb);
667
668                 private bool is_nested_in (Type t) {
669                         while (t != null) {
670                                 if (t == this)
671                                         return true;
672                                 else
673                                         t = t.DeclaringType;
674                         }
675                         return false;
676                 }
677                 
678                 public Type CreateType() {
679                         /* handle nesting_type */
680                         if (created != null)
681                                 return created;
682
683                         create_generic_class ();
684
685                         // Fire TypeResolve events for fields whose type is an unfinished
686                         // value type.
687                         if (fields != null) {
688                                 foreach (FieldBuilder fb in fields) {
689                                         if (fb == null)
690                                                 continue;
691                                         Type ft = fb.FieldType;
692                                         if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
693                                                 TypeBuilder tb = (TypeBuilder)ft;
694                                                 if (!tb.is_created) {
695                                                         AppDomain.CurrentDomain.DoTypeResolve (tb);
696                                                         if (!tb.is_created) {
697                                                                 // FIXME: We should throw an exception here,
698                                                                 // but mcs expects that the type is created
699                                                                 // even if the exception is thrown
700                                                                 //throw new TypeLoadException ("Could not load type " + tb);
701                                                         }
702                                                 }
703                                         }
704                                 }
705                         }
706
707                         if (methods != null) {
708                                 for (int i = 0; i < num_methods; ++i)
709                                         ((MethodBuilder)(methods[i])).fixup ();
710                         }
711
712                         //
713                         // On classes, define a default constructor if not provided
714                         //
715                         if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") && 
716                                 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed))
717                                 DefineDefaultConstructor (MethodAttributes.Public);
718
719                         if (ctors != null){
720                                 foreach (ConstructorBuilder ctor in ctors) 
721                                         ctor.fixup ();
722                         }
723                         
724                         created = create_runtime_class (this);
725                         if (created != null)
726                                 return created;
727                         return this;
728                 }
729
730                 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
731                 {
732                         symbolWriter.OpenNamespace (this.Namespace);
733
734                         if (methods != null) {
735                                 for (int i = 0; i < num_methods; ++i) {
736                                         MethodBuilder metb = (MethodBuilder) methods[i]; 
737                                         metb.GenerateDebugInfo (symbolWriter);
738                                 }
739                         }
740
741                         if (ctors != null) {
742                                 foreach (ConstructorBuilder ctor in ctors)
743                                         ctor.GenerateDebugInfo (symbolWriter);
744                         }
745                         
746                         symbolWriter.CloseNamespace ();
747                 }
748
749 #if NET_2_0
750                 [ComVisible (true)]
751 #endif
752                 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
753                 {
754                         if (ctors == null)
755                                 return new ConstructorInfo [0];
756                         ArrayList l = new ArrayList ();
757                         bool match;
758                         MethodAttributes mattrs;
759                         
760                         foreach (ConstructorBuilder c in ctors) {
761                                 match = false;
762                                 mattrs = c.Attributes;
763                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
764                                         if ((bindingAttr & BindingFlags.Public) != 0)
765                                                 match = true;
766                                 } else {
767                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
768                                                 match = true;
769                                 }
770                                 if (!match)
771                                         continue;
772                                 match = false;
773                                 if ((mattrs & MethodAttributes.Static) != 0) {
774                                         if ((bindingAttr & BindingFlags.Static) != 0)
775                                                 match = true;
776                                 } else {
777                                         if ((bindingAttr & BindingFlags.Instance) != 0)
778                                                 match = true;
779                                 }
780                                 if (!match)
781                                         continue;
782                                 l.Add (c);
783                         }
784                         ConstructorInfo[] result = new ConstructorInfo [l.Count];
785                         l.CopyTo (result);
786                         return result;
787                 }
788
789                 public override Type GetElementType () { 
790                         check_created ();
791                         return created.GetElementType ();
792                 }
793
794                 public override EventInfo GetEvent (string name, BindingFlags bindingAttr) {
795                         check_created ();
796                         return created.GetEvent (name, bindingAttr);
797                 }
798
799                 /* Needed to keep signature compatibility with MS.NET */
800                 public override EventInfo[] GetEvents ()
801                 {
802                         return GetEvents (DefaultBindingFlags);
803                 }
804
805                 public override EventInfo[] GetEvents (BindingFlags bindingAttr) {
806                         /* FIXME: mcs calls this
807                            check_created ();
808                         */
809                         if (!is_created)
810                                 return new EventInfo [0];
811                         else
812                                 return created.GetEvents (bindingAttr);
813                 }
814
815                 // This is only used from MonoGenericInst.initialize().
816                 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
817                 {
818                         if (events == null)
819                                 return new EventInfo [0];
820                         ArrayList l = new ArrayList ();
821                         bool match;
822                         MethodAttributes mattrs;
823                         MethodInfo accessor;
824
825                         foreach (EventBuilder eb in events) {
826                                 if (eb == null)
827                                         continue;
828                                 EventInfo c = get_event_info (eb);
829                                 match = false;
830                                 accessor = c.GetAddMethod (true);
831                                 if (accessor == null)
832                                         accessor = c.GetRemoveMethod (true);
833                                 if (accessor == null)
834                                         continue;
835                                 mattrs = accessor.Attributes;
836                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
837                                         if ((bindingAttr & BindingFlags.Public) != 0)
838                                                 match = true;
839                                 } else {
840                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
841                                                 match = true;
842                                 }
843                                 if (!match)
844                                         continue;
845                                 match = false;
846                                 if ((mattrs & MethodAttributes.Static) != 0) {
847                                         if ((bindingAttr & BindingFlags.Static) != 0)
848                                                 match = true;
849                                 } else {
850                                         if ((bindingAttr & BindingFlags.Instance) != 0)
851                                                 match = true;
852                                 }
853                                 if (!match)
854                                         continue;
855                                 l.Add (c);
856                         }
857                         EventInfo[] result = new EventInfo [l.Count];
858                         l.CopyTo (result);
859                         return result;
860                 }
861
862                 public override FieldInfo GetField( string name, BindingFlags bindingAttr) {
863                         if (fields == null)
864                                 return null;
865
866                         bool match;
867                         FieldAttributes mattrs;
868                         
869                         foreach (FieldInfo c in fields) {
870                                 if (c == null)
871                                         continue;
872                                 if (c.Name != name)
873                                         continue;
874                                 match = false;
875                                 mattrs = c.Attributes;
876                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
877                                         if ((bindingAttr & BindingFlags.Public) != 0)
878                                                 match = true;
879                                 } else {
880                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
881                                                 match = true;
882                                 }
883                                 if (!match)
884                                         continue;
885                                 match = false;
886                                 if ((mattrs & FieldAttributes.Static) != 0) {
887                                         if ((bindingAttr & BindingFlags.Static) != 0)
888                                                 match = true;
889                                 } else {
890                                         if ((bindingAttr & BindingFlags.Instance) != 0)
891                                                 match = true;
892                                 }
893                                 if (!match)
894                                         continue;
895                                 return c;
896                         }
897                         return null;
898                 }
899
900                 public override FieldInfo[] GetFields (BindingFlags bindingAttr) {
901                         if (fields == null)
902                                 return new FieldInfo [0];
903                         ArrayList l = new ArrayList ();
904                         bool match;
905                         FieldAttributes mattrs;
906                         
907                         foreach (FieldInfo c in fields) {
908                                 if (c == null)
909                                         continue;
910                                 match = false;
911                                 mattrs = c.Attributes;
912                                 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
913                                         if ((bindingAttr & BindingFlags.Public) != 0)
914                                                 match = true;
915                                 } else {
916                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
917                                                 match = true;
918                                 }
919                                 if (!match)
920                                         continue;
921                                 match = false;
922                                 if ((mattrs & FieldAttributes.Static) != 0) {
923                                         if ((bindingAttr & BindingFlags.Static) != 0)
924                                                 match = true;
925                                 } else {
926                                         if ((bindingAttr & BindingFlags.Instance) != 0)
927                                                 match = true;
928                                 }
929                                 if (!match)
930                                         continue;
931                                 l.Add (c);
932                         }
933                         FieldInfo[] result = new FieldInfo [l.Count];
934                         l.CopyTo (result);
935                         return result;
936                 }
937
938                 public override Type GetInterface (string name, bool ignoreCase) {
939                         check_created ();
940                         return created.GetInterface (name, ignoreCase);
941                 }
942                 
943                 public override Type[] GetInterfaces () {
944                         if (interfaces != null) {
945                                 Type[] ret = new Type [interfaces.Length];
946                                 interfaces.CopyTo (ret, 0);
947                                 return ret;
948                         } else {
949                                 return Type.EmptyTypes;
950                         }
951                 }
952
953                 public override MemberInfo[] GetMember (string name, MemberTypes type,
954                                                                                                 BindingFlags bindingAttr) {
955                         check_created ();
956                         return created.GetMember (name, type, bindingAttr);
957                 }
958
959                 public override MemberInfo[] GetMembers (BindingFlags bindingAttr) {
960                         check_created ();
961                         return created.GetMembers (bindingAttr);
962                 }
963
964                 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type) {
965                         MethodInfo[] candidates;
966                         if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
967                                 MethodInfo[] parent_methods = parent.GetMethods (bindingAttr);
968                                 if (methods == null)
969                                         candidates = parent_methods;
970                                 else {
971                                         candidates = new MethodInfo [methods.Length + parent_methods.Length];
972                                         parent_methods.CopyTo (candidates, 0);
973                                         methods.CopyTo (candidates, parent_methods.Length);
974                                 }
975                         }
976                         else
977                                 candidates = methods;
978
979                         if (candidates == null)
980                                 return new MethodInfo [0];
981
982                         ArrayList l = new ArrayList ();
983                         bool match;
984                         MethodAttributes mattrs;
985
986                         foreach (MethodInfo c in candidates) {
987                                 if (c == null)
988                                         continue;
989                                 if (name != null) {
990                                         if (String.Compare (c.Name, name, ignoreCase) != 0)
991                                                 continue;
992                                 }
993                                 match = false;
994                                 mattrs = c.Attributes;
995                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
996                                         if ((bindingAttr & BindingFlags.Public) != 0)
997                                                 match = true;
998                                 } else {
999                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1000                                                 match = true;
1001                                 }
1002                                 if (!match)
1003                                         continue;
1004                                 match = false;
1005                                 if ((mattrs & MethodAttributes.Static) != 0) {
1006                                         if ((bindingAttr & BindingFlags.Static) != 0)
1007                                                 match = true;
1008                                 } else {
1009                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1010                                                 match = true;
1011                                 }
1012                                 if (!match)
1013                                         continue;
1014                                 l.Add (c);
1015                         }
1016
1017                         MethodInfo[] result = new MethodInfo [l.Count];
1018                         l.CopyTo (result);
1019                         return result;
1020                 }
1021
1022                 public override MethodInfo[] GetMethods (BindingFlags bindingAttr) {
1023                         return GetMethodsByName (null, bindingAttr, false, this);
1024                 }
1025
1026                 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
1027                                                              Binder binder,
1028                                                              CallingConventions callConvention,
1029                                                              Type[] types, ParameterModifier[] modifiers)
1030                 {
1031                         check_created ();
1032
1033                         bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
1034                         MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
1035                         MethodInfo found = null;
1036                         MethodBase[] match;
1037                         int typesLen = (types != null) ? types.Length : 0;
1038                         int count = 0;
1039                         
1040                         foreach (MethodInfo m in methods) {
1041                                 // Under MS.NET, Standard|HasThis matches Standard...
1042                                 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1043                                         continue;
1044                                 found = m;
1045                                 count++;
1046                         }
1047
1048                         if (count == 0)
1049                                 return null;
1050                         
1051                         if (count == 1 && typesLen == 0) 
1052                                 return found;
1053
1054                         match = new MethodBase [count];
1055                         if (count == 1)
1056                                 match [0] = found;
1057                         else {
1058                                 count = 0;
1059                                 foreach (MethodInfo m in methods) {
1060                                         if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1061                                                 continue;
1062                                         match [count++] = m;
1063                                 }
1064                         }
1065                         
1066                         if (types == null) 
1067                                 return (MethodInfo) Binder.FindMostDerivedMatch (match);
1068
1069                         if (binder == null)
1070                                 binder = Binder.DefaultBinder;
1071                         
1072                         return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
1073                 }
1074
1075                 public override Type GetNestedType( string name, BindingFlags bindingAttr) {
1076                         check_created ();
1077                         return created.GetNestedType (name, bindingAttr);
1078                 }
1079
1080                 public override Type[] GetNestedTypes (BindingFlags bindingAttr) {
1081                         bool match;
1082                         ArrayList result = new ArrayList ();
1083
1084                         if (subtypes == null)
1085                                 return Type.EmptyTypes;
1086                         foreach (TypeBuilder t in subtypes) {
1087                                 match = false;
1088                                 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1089                                         if ((bindingAttr & BindingFlags.Public) != 0)
1090                                                 match = true;
1091                                 } else {
1092                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1093                                                 match = true;
1094                                 }
1095                                 if (!match)
1096                                         continue;
1097                                 result.Add (t);
1098                         }
1099                         Type[] r = new Type [result.Count];
1100                         result.CopyTo (r);
1101                         return r;
1102                 }
1103
1104                 public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) {
1105                         if (properties == null)
1106                                 return new PropertyInfo [0];
1107                         ArrayList l = new ArrayList ();
1108                         bool match;
1109                         MethodAttributes mattrs;
1110                         MethodInfo accessor;
1111                         
1112                         foreach (PropertyInfo c in properties) {
1113                                 match = false;
1114                                 accessor = c.GetGetMethod (true);
1115                                 if (accessor == null)
1116                                         accessor = c.GetSetMethod (true);
1117                                 if (accessor == null)
1118                                         continue;
1119                                 mattrs = accessor.Attributes;
1120                                 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1121                                         if ((bindingAttr & BindingFlags.Public) != 0)
1122                                                 match = true;
1123                                 } else {
1124                                         if ((bindingAttr & BindingFlags.NonPublic) != 0)
1125                                                 match = true;
1126                                 }
1127                                 if (!match)
1128                                         continue;
1129                                 match = false;
1130                                 if ((mattrs & MethodAttributes.Static) != 0) {
1131                                         if ((bindingAttr & BindingFlags.Static) != 0)
1132                                                 match = true;
1133                                 } else {
1134                                         if ((bindingAttr & BindingFlags.Instance) != 0)
1135                                                 match = true;
1136                                 }
1137                                 if (!match)
1138                                         continue;
1139                                 l.Add (c);
1140                         }
1141                         PropertyInfo[] result = new PropertyInfo [l.Count];
1142                         l.CopyTo (result);
1143                         return result;
1144                 }
1145                 
1146                 protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
1147                         throw not_supported ();
1148                 }
1149
1150                 protected override bool HasElementTypeImpl () {
1151                         check_created ();
1152                         return created.HasElementType;
1153                 }
1154
1155                 public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
1156                         check_created ();
1157                         return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1158                 }
1159
1160                 protected override bool IsArrayImpl ()
1161                 {
1162                         return Type.IsArrayImpl (this);
1163                 }
1164
1165                 protected override bool IsByRefImpl () {
1166                         // FIXME
1167                         return false;
1168                 }
1169                 protected override bool IsCOMObjectImpl () {
1170                         return false;
1171                 }
1172                 protected override bool IsPointerImpl () {
1173                         // FIXME
1174                         return false;
1175                 }
1176                 protected override bool IsPrimitiveImpl () {
1177                         // FIXME
1178                         return false;
1179                 }
1180                 protected override bool IsValueTypeImpl () {
1181                         return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
1182                                 this != pmodule.assemblyb.corlib_value_type &&
1183                                 this != pmodule.assemblyb.corlib_enum_type);
1184                 }
1185                 
1186                 public override RuntimeTypeHandle TypeHandle { 
1187                         get { 
1188                                 check_created ();
1189                                 return created.TypeHandle;
1190                         } 
1191                 }
1192
1193                 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
1194                         if (customBuilder == null)
1195                                 throw new ArgumentNullException ("customBuilder");
1196
1197                         string attrname = customBuilder.Ctor.ReflectedType.FullName;
1198                         if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1199                                 byte[] data = customBuilder.Data;
1200                                 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1201                                 layout_kind = (int)data [2];
1202                                 layout_kind |= ((int)data [3]) << 8;
1203                                 attrs &= ~TypeAttributes.LayoutMask;
1204                                 switch ((LayoutKind)layout_kind) {
1205                                 case LayoutKind.Auto:
1206                                         attrs |= TypeAttributes.AutoLayout;
1207                                         break;
1208                                 case LayoutKind.Explicit:
1209                                         attrs |= TypeAttributes.ExplicitLayout;
1210                                         break;
1211                                 case LayoutKind.Sequential:
1212                                         attrs |= TypeAttributes.SequentialLayout;
1213                                         break;
1214                                 default:
1215                                         // we should ignore it since it can be any value anyway...
1216                                         throw new Exception ("Error in customattr");
1217                                 }
1218                                 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
1219                                 int pos = 6;
1220                                 if (first_type_name == "System.Int16")
1221                                         pos = 4;
1222                                 int nnamed = (int)data [pos++];
1223                                 nnamed |= ((int)data [pos++]) << 8;
1224                                 for (int i = 0; i < nnamed; ++i) {
1225                                         //byte named_type = data [pos++];
1226                                         pos ++;
1227                                         byte type = data [pos++];
1228                                         int len;
1229                                         string named_name;
1230
1231                                         if (type == 0x55) {
1232                                                 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1233                                                 //string named_typename = 
1234                                                 CustomAttributeBuilder.string_from_bytes (data, pos, len);
1235                                                 pos += len;
1236                                                 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1237                                                 //        See related code/FIXME in mono/mono/metadata/reflection.c
1238                                         }
1239
1240                                         len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1241                                         named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1242                                         pos += len;
1243                                         /* all the fields are integers in StructLayout */
1244                                         int value = (int)data [pos++];
1245                                         value |= ((int)data [pos++]) << 8;
1246                                         value |= ((int)data [pos++]) << 16;
1247                                         value |= ((int)data [pos++]) << 24;
1248                                         switch (named_name) {
1249                                         case "CharSet":
1250                                                 switch ((CharSet)value) {
1251                                                 case CharSet.None:
1252                                                 case CharSet.Ansi:
1253                                                         attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
1254                                                         break;
1255                                                 case CharSet.Unicode:
1256                                                         attrs &= ~TypeAttributes.AutoClass;
1257                                                         attrs |= TypeAttributes.UnicodeClass;
1258                                                         break;
1259                                                 case CharSet.Auto:
1260                                                         attrs &= ~TypeAttributes.UnicodeClass;
1261                                                         attrs |= TypeAttributes.AutoClass;
1262                                                         break;
1263                                                 default:
1264                                                         break; // error out...
1265                                                 }
1266                                                 break;
1267                                         case "Pack":
1268                                                 packing_size = (PackingSize)value;
1269                                                 break;
1270                                         case "Size":
1271                                                 class_size = value;
1272                                                 break;
1273                                         default:
1274                                                 break; // error out...
1275                                         }
1276                                 }
1277                                 return;
1278 #if NET_2_0
1279                         } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
1280                                 attrs |= TypeAttributes.SpecialName;
1281                                 return;
1282 #endif
1283                         } else if (attrname == "System.SerializableAttribute") {
1284                                 attrs |= TypeAttributes.Serializable;
1285                                 return;
1286                         } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
1287                                 attrs |= TypeAttributes.Import;
1288                                 return;
1289                         }
1290
1291                         if (cattrs != null) {
1292                                 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1293                                 cattrs.CopyTo (new_array, 0);
1294                                 new_array [cattrs.Length] = customBuilder;
1295                                 cattrs = new_array;
1296                         } else {
1297                                 cattrs = new CustomAttributeBuilder [1];
1298                                 cattrs [0] = customBuilder;
1299                         }
1300                 }
1301
1302 #if NET_2_0
1303                 [ComVisible (true)]
1304 #endif
1305                 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
1306                         SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1307                 }
1308
1309                 public EventBuilder DefineEvent( string name, EventAttributes attributes, Type eventtype) {
1310                         check_name ("name", name);
1311                         if (eventtype == null)
1312                                 throw new ArgumentNullException ("eventtype");
1313                         check_not_created ();
1314
1315                         EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1316                         if (events != null) {
1317                                 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1318                                 System.Array.Copy (events, new_events, events.Length);
1319                                 new_events [events.Length] = res;
1320                                 events = new_events;
1321                         } else {
1322                                 events = new EventBuilder [1];
1323                                 events [0] = res;
1324                         }
1325                         return res;
1326                 }
1327
1328                 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
1329                         if (data == null)
1330                                 throw new ArgumentNullException ("data");
1331                         if ((data.Length == 0) || (data.Length > 0x3f0000))
1332                                 throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
1333
1334                         FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1335                         res.SetRVAData (data);
1336
1337                         return res;
1338                 }
1339
1340                 static int UnmanagedDataCount = 0;
1341                 
1342                 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
1343                         check_name ("name", name);
1344                         if ((size <= 0) || (size > 0x3f0000))
1345                                 throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
1346                         check_not_created ();
1347
1348                         string s = "$ArrayType$"+UnmanagedDataCount.ToString();
1349                         UnmanagedDataCount++;
1350                         TypeBuilder datablobtype = DefineNestedType (s,
1351                                 TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1352                                 pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1353                         datablobtype.CreateType ();
1354                         return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1355                 }
1356
1357                 public TypeToken TypeToken {
1358                         get {
1359                                 return new TypeToken (0x02000000 | table_idx);
1360                         }
1361                 }
1362                 public void SetParent (Type parentType) {
1363                         if (parentType == null)
1364                                 throw new ArgumentNullException ("parentType");
1365                         check_not_created ();
1366
1367                         parent = parentType;
1368                         // will just set the parent-related bits if called a second time
1369                         setup_internal_class (this);
1370                 }
1371                 internal int get_next_table_index (object obj, int table, bool inc) {
1372                         return pmodule.get_next_table_index (obj, table, inc);
1373                 }
1374
1375 #if NET_2_0
1376                 [ComVisible (true)]
1377 #endif
1378                 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1379                 {
1380                         if (created == null)
1381                                 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1382
1383                         return created.GetInterfaceMap (interfaceType);
1384                 }
1385
1386                 internal bool is_created {
1387                         get {
1388                                 return created != null;
1389                         }
1390                 }
1391
1392                 private Exception not_supported ()
1393                 {
1394                         return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1395                 }
1396
1397                 private void check_not_created ()
1398                 {
1399                         if (is_created)
1400                                 throw new InvalidOperationException ("Unable to change after type has been created.");
1401                 }
1402
1403                 private void check_created ()
1404                 {
1405                         if (!is_created)
1406                                 throw not_supported ();
1407                 }
1408
1409                 private void check_name (string argName, string name)
1410                 {
1411                         if (name == null)
1412                                 throw new ArgumentNullException (argName);
1413                         if (name.Length == 0)
1414                                 throw new ArgumentException ("Empty name is not legal", argName);
1415                         if (name.IndexOf ((char)0) != -1)
1416                                 throw new ArgumentException ("Illegal name", argName);
1417                 }
1418
1419                 public override String ToString ()
1420                 {
1421                         return FullName;
1422                 }
1423
1424                 [MonoTODO]
1425                 public override bool IsAssignableFrom (Type c)
1426                 {
1427                         return base.IsAssignableFrom (c);
1428                 }
1429
1430 #if NET_2_0
1431                 [ComVisible (true)]
1432 #endif
1433                 [MonoTODO]
1434                 public override bool IsSubclassOf (Type c)
1435                 {
1436                         return base.IsSubclassOf (c);
1437                 }
1438
1439                 [MonoTODO ("arrays")]
1440                 internal bool IsAssignableTo (Type c)
1441                 {
1442                         if (c == this)
1443                                 return true;
1444
1445                         if (c.IsInterface) {
1446                                 if (interfaces == null)
1447                                         return false;
1448                                 foreach (Type t in interfaces)
1449                                         if (c.IsAssignableFrom (t))
1450                                                 return true;
1451                                 return false;
1452                         }
1453
1454                         if (parent == null)
1455                                 return c == typeof (object);
1456                         else
1457                                 return c.IsAssignableFrom (parent);
1458                 }
1459
1460 #if NET_2_0 || BOOTSTRAP_NET_2_0
1461                 public bool IsCreated () {
1462                         return is_created;
1463                 }
1464
1465                 public override Type[] GetGenericArguments ()
1466                 {
1467                         if (generic_params != null)
1468                                 return generic_params;
1469
1470                         throw new InvalidOperationException ();
1471                 }
1472
1473                 public override Type GetGenericTypeDefinition ()
1474                 {
1475                         create_generic_class ();
1476
1477                         return base.GetGenericTypeDefinition ();
1478                 }
1479
1480                 public override bool ContainsGenericParameters {
1481                         get {
1482                                 return generic_params != null;
1483                         }
1484                 }
1485
1486                 public extern override bool IsGenericParameter {
1487                         [MethodImplAttribute(MethodImplOptions.InternalCall)]
1488                         get;
1489                 }
1490
1491                 public override bool IsGenericTypeDefinition {
1492                         get {
1493                                 return generic_params != null;
1494                         }
1495                 }
1496
1497                 public override int GenericParameterPosition {
1498                         get {
1499                                 throw new NotImplementedException ();
1500                         }
1501                 }
1502
1503                 public override MethodInfo DeclaringMethod {
1504                         get {
1505                                 throw new NotImplementedException ();
1506                         }
1507                 }
1508
1509                 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1510                 {
1511                         setup_generic_class ();
1512
1513                         generic_params = new GenericTypeParameterBuilder [names.Length];
1514                         for (int i = 0; i < names.Length; i++)
1515                                 generic_params [i] = new GenericTypeParameterBuilder (
1516                                         this, null, names [i], i);
1517
1518                         return generic_params;
1519                 }
1520
1521                 public MethodBuilder DefineGenericMethod (string name, MethodAttributes attributes)
1522                 {
1523                         return DefineMethod (name, attributes, CallingConventions.Standard, null, null);
1524                 }
1525
1526                 public static ConstructorInfo GetConstructor (Type instanciated, ConstructorInfo ctor)
1527                 {
1528                         ConstructorInfo res = instanciated.GetConstructor (ctor);
1529                         if (res == null)
1530                                 throw new System.Exception ("constructor not found");
1531                         else
1532                                 return res;
1533                 }
1534
1535                 public static MethodInfo GetMethod (Type instanciated, MethodInfo meth)
1536                 {
1537                         MethodInfo res = instanciated.GetMethod (meth);
1538                         if (res == null)
1539                                 throw new System.Exception ("method not found");
1540                         else
1541                                 return res;
1542                 }
1543
1544                 public static FieldInfo GetField (Type instanciated, FieldInfo fld)
1545                 {
1546                         FieldInfo res = instanciated.GetField (fld);
1547                         if (res == null)
1548                                 throw new System.Exception ("field not found");
1549                         else
1550                                 return res;
1551                 }
1552 #endif
1553
1554                 void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1555                 {
1556                         throw new NotImplementedException ();
1557                 }
1558
1559                 void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1560                 {
1561                         throw new NotImplementedException ();
1562                 }
1563
1564                 void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
1565                 {
1566                         throw new NotImplementedException ();
1567                 }
1568
1569                 void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1570                 {
1571                         throw new NotImplementedException ();
1572                 }
1573         }
1574 }