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