2 // System.Reflection.Emit.TypeBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // (C) 2001 Ximian, Inc. http://www.ximian.com
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
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.
36 using System.Reflection;
37 using System.Reflection.Emit;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Globalization;
41 using System.Collections;
42 using System.Security;
43 using System.Security.Permissions;
44 using System.Diagnostics.SymbolStore;
46 namespace System.Reflection.Emit
50 [ComDefaultInterface (typeof (_TypeBuilder))]
52 [ClassInterface (ClassInterfaceType.None)]
53 public sealed class TypeBuilder : Type, _TypeBuilder
55 #region Sync with reflection.h
57 private string nspace;
59 private Type nesting_type;
60 private Type[] interfaces;
61 private int num_methods;
62 private MethodBuilder[] methods;
63 private ConstructorBuilder[] ctors;
64 private PropertyBuilder[] properties;
65 private int num_fields;
66 private FieldBuilder[] fields;
67 private EventBuilder[] events;
68 private CustomAttributeBuilder[] cattrs;
69 internal TypeBuilder[] subtypes;
70 internal TypeAttributes attrs;
71 private int table_idx;
72 private ModuleBuilder pmodule;
73 private int class_size;
74 private PackingSize packing_size;
75 private IntPtr generic_container;
76 #if NET_2_0 || BOOTSTRAP_NET_2_0
77 private GenericTypeParameterBuilder[] generic_params;
79 private Object generic_params; /* so offsets don't change */
81 private RefEmitPermissionSet[] permissions;
85 bool createTypeCalled;
86 private Type underlying_type;
88 public const int UnspecifiedTypeSize = 0;
90 protected override TypeAttributes GetAttributeFlagsImpl ()
95 [MethodImplAttribute(MethodImplOptions.InternalCall)]
96 private extern void setup_internal_class (TypeBuilder tb);
98 [MethodImplAttribute(MethodImplOptions.InternalCall)]
99 private extern void create_internal_class (TypeBuilder tb);
101 [MethodImplAttribute(MethodImplOptions.InternalCall)]
102 private extern void setup_generic_class ();
104 [MethodImplAttribute(MethodImplOptions.InternalCall)]
105 private extern void create_generic_class ();
107 [MethodImplAttribute(MethodImplOptions.InternalCall)]
108 private extern EventInfo get_event_info (EventBuilder eb);
110 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr)
114 this.class_size = UnspecifiedTypeSize;
116 fullname = this.tname = "<Module>";
117 this.nspace = String.Empty;
119 setup_internal_class (this);
122 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type)
125 this.parent = parent;
127 this.class_size = type_size;
128 this.packing_size = packing_size;
129 this.nesting_type = nesting_type;
131 check_name ("fullname", name);
133 if (parent == null && (attr & TypeAttributes.Interface) != 0 && (attr & TypeAttributes.Abstract) == 0)
134 throw new InvalidOperationException ("Interface must be declared abstract.");
136 sep_index = name.LastIndexOf('.');
137 if (sep_index != -1) {
138 this.tname = name.Substring (sep_index + 1);
139 this.nspace = name.Substring (0, sep_index);
142 this.nspace = String.Empty;
144 if (interfaces != null) {
145 this.interfaces = new Type[interfaces.Length];
146 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
150 if (((attr & TypeAttributes.Interface) == 0) && (parent == null) && !IsCompilerContext)
151 this.parent = typeof (object);
154 table_idx = mb.get_next_table_index (this, 0x02, true);
155 setup_internal_class (this);
156 fullname = GetFullName ();
159 public override Assembly Assembly {
160 get {return pmodule.Assembly;}
163 public override string AssemblyQualifiedName {
165 return fullname + ", " + Assembly.FullName;
169 public override Type BaseType {
175 public override Type DeclaringType {
176 get { return nesting_type; }
179 /* public override bool IsSubclassOf (Type c)
195 public override Type UnderlyingSystemType {
198 return created.UnderlyingSystemType;
200 if (IsEnum && !IsCompilerContext) {
201 if (underlying_type != null)
202 return underlying_type;
203 throw new InvalidOperationException (
204 "Enumeration type is not defined.");
211 string GetFullName ()
213 if (nesting_type != null)
214 return String.Concat (nesting_type.FullName, "+", tname);
215 if ((nspace != null) && (nspace.Length > 0))
216 return String.Concat (nspace, ".", tname);
220 public override string FullName {
226 public override Guid GUID {
233 public override Module Module {
234 get {return pmodule;}
237 public override string Name {
241 public override string Namespace {
245 public PackingSize PackingSize {
246 get {return packing_size;}
250 get { return class_size; }
253 public override Type ReflectedType {
254 get { return nesting_type; }
257 public void AddDeclarativeSecurity (SecurityAction action, PermissionSet pset)
260 throw new ArgumentNullException ("pset");
261 if ((action == SecurityAction.RequestMinimum) ||
262 (action == SecurityAction.RequestOptional) ||
263 (action == SecurityAction.RequestRefuse))
264 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
266 check_not_created ();
268 if (permissions != null) {
269 /* Check duplicate actions */
270 foreach (RefEmitPermissionSet set in permissions)
271 if (set.action == action)
272 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
274 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
275 permissions.CopyTo (new_array, 0);
276 permissions = new_array;
279 permissions = new RefEmitPermissionSet [1];
281 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
282 attrs |= TypeAttributes.HasSecurity;
288 public void AddInterfaceImplementation (Type interfaceType)
290 if (interfaceType == null)
291 throw new ArgumentNullException ("interfaceType");
292 check_not_created ();
294 if (interfaces != null) {
295 // Check for duplicates
296 foreach (Type t in interfaces)
297 if (t == interfaceType)
300 Type[] ifnew = new Type [interfaces.Length + 1];
301 interfaces.CopyTo (ifnew, 0);
302 ifnew [interfaces.Length] = interfaceType;
305 interfaces = new Type [1];
306 interfaces [0] = interfaceType;
310 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
311 CallingConventions callConvention, Type[] types,
312 ParameterModifier[] modifiers)
316 if (created == typeof (object)) {
318 * This happens when building corlib. Calling created.GetConstructor
319 * would return constructors from the real mscorlib, instead of the
326 ConstructorBuilder found = null;
329 foreach (ConstructorBuilder cb in ctors) {
330 if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
340 throw new AmbiguousMatchException ();
343 MethodBase[] match = new MethodBase [count];
348 foreach (ConstructorInfo m in ctors) {
349 if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
355 binder = Binder.DefaultBinder;
356 return (ConstructorInfo) binder.SelectMethod (bindingAttr, match,
360 return created.GetConstructor (bindingAttr, binder,
361 callConvention, types, modifiers);
364 public override bool IsDefined (Type attributeType, bool inherit)
367 * MS throws NotSupported here, but we can't because some corlib
368 * classes make calls to IsDefined.
370 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
373 public override object[] GetCustomAttributes(bool inherit)
377 return created.GetCustomAttributes (inherit);
380 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
384 return created.GetCustomAttributes (attributeType, inherit);
387 public TypeBuilder DefineNestedType (string name)
389 return DefineNestedType (name, TypeAttributes.NestedPrivate,
390 pmodule.assemblyb.corlib_object_type, null);
393 public TypeBuilder DefineNestedType (string name, TypeAttributes attr)
395 return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
398 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent)
400 return DefineNestedType (name, attr, parent, null);
403 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
404 PackingSize packSize, int typeSize)
406 // Visibility must be NestedXXX
408 if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
409 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
410 throw new ArgumentException ("attr", "Bad type flags for nested type.");
412 if (interfaces != null)
413 foreach (Type iface in interfaces)
415 throw new ArgumentNullException ("interfaces");
417 TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packSize, typeSize, this);
418 res.fullname = res.GetFullName ();
419 pmodule.RegisterTypeName (res, res.fullname);
420 if (subtypes != null) {
421 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
422 System.Array.Copy (subtypes, new_types, subtypes.Length);
423 new_types [subtypes.Length] = res;
424 subtypes = new_types;
426 subtypes = new TypeBuilder [1];
435 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces)
437 return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
440 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typeSize)
442 return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typeSize);
445 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packSize)
447 return DefineNestedType (name, attr, parent, null, packSize, UnspecifiedTypeSize);
453 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
455 return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
461 #if NET_2_0 || BOOTSTRAP_NET_2_0
466 ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
468 check_not_created ();
469 ConstructorBuilder cb = new ConstructorBuilder (this, attributes,
470 callingConvention, parameterTypes, requiredCustomModifiers,
471 optionalCustomModifiers);
473 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
474 System.Array.Copy (ctors, new_ctors, ctors.Length);
475 new_ctors [ctors.Length] = cb;
478 ctors = new ConstructorBuilder [1];
487 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
492 parent_type = parent;
494 parent_type = pmodule.assemblyb.corlib_object_type;
496 ConstructorInfo parent_constructor =
497 parent_type.GetConstructor (
498 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
499 null, Type.EmptyTypes, null);
500 if (parent_constructor == null) {
501 throw new NotSupportedException ("Parent does"
502 + " not have a default constructor."
503 + " The default constructor must be"
504 + " explicitly defined.");
507 ConstructorBuilder cb = DefineConstructor (attributes,
508 CallingConventions.Standard, Type.EmptyTypes);
509 ILGenerator ig = cb.GetILGenerator ();
510 ig.Emit (OpCodes.Ldarg_0);
511 ig.Emit (OpCodes.Call, parent_constructor);
512 ig.Emit (OpCodes.Ret);
516 private void append_method (MethodBuilder mb)
518 if (methods != null) {
519 if (methods.Length == num_methods) {
520 MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
521 System.Array.Copy (methods, new_methods, num_methods);
522 methods = new_methods;
525 methods = new MethodBuilder [1];
527 methods [num_methods] = mb;
531 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
533 return DefineMethod (name, attributes, CallingConventions.Standard,
534 returnType, parameterTypes);
537 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
539 return DefineMethod (name, attributes, callingConvention, returnType,
540 null, null, parameterTypes, null, null);
543 #if NET_2_0 || BOOTSTRAP_NET_2_0
548 MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
550 check_name ("name", name);
551 check_not_created ();
553 !((attributes & MethodAttributes.Abstract) != 0) ||
554 !((attributes & MethodAttributes.Virtual) != 0)) &&
555 !(((attributes & MethodAttributes.Static) != 0)))
556 throw new ArgumentException ("Interface method must be abstract and virtual.");
558 if (returnType == null)
559 returnType = pmodule.assemblyb.corlib_void_type;
560 MethodBuilder res = new MethodBuilder (this, name, attributes,
561 callingConvention, returnType,
562 returnTypeRequiredCustomModifiers,
563 returnTypeOptionalCustomModifiers, parameterTypes,
564 parameterTypeRequiredCustomModifiers,
565 parameterTypeOptionalCustomModifiers);
570 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet)
572 return DefinePInvokeMethod (name, dllName, entryName, attributes,
573 callingConvention, returnType, null, null, parameterTypes,
574 null, null, nativeCallConv, nativeCharSet);
577 #if NET_2_0 || BOOTSTRAP_NET_2_0
582 MethodBuilder DefinePInvokeMethod (
585 string entryName, MethodAttributes attributes,
586 CallingConventions callingConvention,
588 Type[] returnTypeRequiredCustomModifiers,
589 Type[] returnTypeOptionalCustomModifiers,
590 Type[] parameterTypes,
591 Type[][] parameterTypeRequiredCustomModifiers,
592 Type[][] parameterTypeOptionalCustomModifiers,
593 CallingConvention nativeCallConv,
594 CharSet nativeCharSet)
596 check_name ("name", name);
597 check_name ("dllName", dllName);
598 check_name ("entryName", entryName);
599 if ((attributes & MethodAttributes.Abstract) != 0)
600 throw new ArgumentException ("PInvoke methods must be static and native and cannot be abstract.");
602 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
603 check_not_created ();
606 = new MethodBuilder (
612 returnTypeRequiredCustomModifiers,
613 returnTypeOptionalCustomModifiers,
615 parameterTypeRequiredCustomModifiers,
616 parameterTypeOptionalCustomModifiers,
625 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
626 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
627 nativeCallConv, nativeCharSet);
630 #if NET_2_0 || BOOTSTRAP_NET_2_0
631 public MethodBuilder DefineMethod (string name, MethodAttributes attributes)
633 return DefineMethod (name, attributes, CallingConventions.Standard);
636 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callingConvention)
638 return DefineMethod (name, attributes, callingConvention, null, null);
642 public void DefineMethodOverride (MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
644 if (methodInfoBody == null)
645 throw new ArgumentNullException ("methodInfoBody");
646 if (methodInfoDeclaration == null)
647 throw new ArgumentNullException ("methodInfoDeclaration");
648 check_not_created ();
650 if (methodInfoBody is MethodBuilder) {
651 MethodBuilder mb = (MethodBuilder)methodInfoBody;
652 mb.set_override (methodInfoDeclaration);
656 public FieldBuilder DefineField (string fieldName, Type type, FieldAttributes attributes)
658 return DefineField (fieldName, type, null, null, attributes);
661 #if NET_2_0 || BOOTSTRAP_NET_2_0
666 FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
668 check_name ("fieldName", fieldName);
669 if (type == typeof (void))
670 throw new ArgumentException ("Bad field type in defining field.");
671 check_not_created ();
673 FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomModifiers, optionalCustomModifiers);
674 if (fields != null) {
675 if (fields.Length == num_fields) {
676 FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
677 System.Array.Copy (fields, new_fields, num_fields);
680 fields [num_fields] = res;
683 fields = new FieldBuilder [1];
686 create_internal_class (this);
689 if (IsEnum && !IsCompilerContext) {
690 if (underlying_type == null && (attributes & FieldAttributes.Static) == 0)
691 underlying_type = type;
697 public PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
699 return DefineProperty (name, attributes, returnType, null, null, parameterTypes, null, null);
707 PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
709 check_name ("name", name);
710 if (parameterTypes != null)
711 foreach (Type param in parameterTypes)
713 throw new ArgumentNullException ("parameterTypes");
714 check_not_created ();
716 PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
718 if (properties != null) {
719 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
720 System.Array.Copy (properties, new_properties, properties.Length);
721 new_properties [properties.Length] = res;
722 properties = new_properties;
724 properties = new PropertyBuilder [1];
725 properties [0] = res;
733 public ConstructorBuilder DefineTypeInitializer()
735 return DefineConstructor (MethodAttributes.Public |
736 MethodAttributes.Static | MethodAttributes.SpecialName |
737 MethodAttributes.RTSpecialName, CallingConventions.Standard,
741 [MethodImplAttribute(MethodImplOptions.InternalCall)]
742 private extern Type create_runtime_class (TypeBuilder tb);
744 private bool is_nested_in (Type t)
755 // Return whenever this type has a ctor defined using DefineMethod ()
756 private bool has_ctor_method () {
757 MethodAttributes ctor_attrs = MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
759 for (int i = 0; i < num_methods; ++i) {
760 MethodBuilder mb = (MethodBuilder)(methods[i]);
762 if (mb.Name == ConstructorInfo.ConstructorName && (mb.Attributes & ctor_attrs) == ctor_attrs)
769 public Type CreateType()
771 /* handle nesting_type */
772 if (createTypeCalled)
775 if (!IsInterface && (parent == null) && (this != pmodule.assemblyb.corlib_object_type) && (FullName != "<Module>")) {
776 SetParent (pmodule.assemblyb.corlib_object_type);
779 create_generic_class ();
781 // Fire TypeResolve events for fields whose type is an unfinished
783 if (fields != null) {
784 foreach (FieldBuilder fb in fields) {
787 Type ft = fb.FieldType;
788 if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
789 TypeBuilder tb = (TypeBuilder)ft;
790 if (!tb.is_created) {
791 AppDomain.CurrentDomain.DoTypeResolve (tb);
792 if (!tb.is_created) {
793 // FIXME: We should throw an exception here,
794 // but mcs expects that the type is created
795 // even if the exception is thrown
796 //throw new TypeLoadException ("Could not load type " + tb);
803 if ((parent != null) && parent.IsSealed)
804 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
806 if (parent == pmodule.assemblyb.corlib_enum_type && methods != null)
807 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because it is an enum with methods.");
809 if (methods != null) {
810 for (int i = 0; i < num_methods; ++i) {
811 MethodBuilder mb = (MethodBuilder)(methods[i]);
812 mb.check_override ();
818 // On classes, define a default constructor if not provided
820 if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") &&
821 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ())
822 DefineDefaultConstructor (MethodAttributes.Public);
825 foreach (ConstructorBuilder ctor in ctors)
829 createTypeCalled = true;
830 created = create_runtime_class (this);
836 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
838 symbolWriter.OpenNamespace (this.Namespace);
840 if (methods != null) {
841 for (int i = 0; i < num_methods; ++i) {
842 MethodBuilder metb = (MethodBuilder) methods[i];
843 metb.GenerateDebugInfo (symbolWriter);
848 foreach (ConstructorBuilder ctor in ctors)
849 ctor.GenerateDebugInfo (symbolWriter);
852 symbolWriter.CloseNamespace ();
854 if (subtypes != null) {
855 for (int i = 0; i < subtypes.Length; ++i)
856 subtypes [i].GenerateDebugInfo (symbolWriter);
863 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
866 return created.GetConstructors (bindingAttr);
869 return new ConstructorInfo [0];
870 ArrayList l = new ArrayList ();
872 MethodAttributes mattrs;
874 foreach (ConstructorBuilder c in ctors) {
876 mattrs = c.Attributes;
877 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
878 if ((bindingAttr & BindingFlags.Public) != 0)
881 if ((bindingAttr & BindingFlags.NonPublic) != 0)
887 if ((mattrs & MethodAttributes.Static) != 0) {
888 if ((bindingAttr & BindingFlags.Static) != 0)
891 if ((bindingAttr & BindingFlags.Instance) != 0)
898 ConstructorInfo[] result = new ConstructorInfo [l.Count];
903 public override Type GetElementType ()
906 return created.GetElementType ();
909 public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
912 return created.GetEvent (name, bindingAttr);
915 /* Needed to keep signature compatibility with MS.NET */
916 public override EventInfo[] GetEvents ()
918 return GetEvents (DefaultBindingFlags);
921 public override EventInfo[] GetEvents (BindingFlags bindingAttr)
923 /* FIXME: mcs calls this
927 return new EventInfo [0];
929 return created.GetEvents (bindingAttr);
932 // This is only used from MonoGenericInst.initialize().
933 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
936 return new EventInfo [0];
937 ArrayList l = new ArrayList ();
939 MethodAttributes mattrs;
942 foreach (EventBuilder eb in events) {
945 EventInfo c = get_event_info (eb);
947 accessor = c.GetAddMethod (true);
948 if (accessor == null)
949 accessor = c.GetRemoveMethod (true);
950 if (accessor == null)
952 mattrs = accessor.Attributes;
953 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
954 if ((bindingAttr & BindingFlags.Public) != 0)
957 if ((bindingAttr & BindingFlags.NonPublic) != 0)
963 if ((mattrs & MethodAttributes.Static) != 0) {
964 if ((bindingAttr & BindingFlags.Static) != 0)
967 if ((bindingAttr & BindingFlags.Instance) != 0)
974 EventInfo[] result = new EventInfo [l.Count];
979 public override FieldInfo GetField (string name, BindingFlags bindingAttr)
982 return created.GetField (name, bindingAttr);
988 FieldAttributes mattrs;
990 foreach (FieldInfo c in fields) {
996 mattrs = c.Attributes;
997 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
998 if ((bindingAttr & BindingFlags.Public) != 0)
1001 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1007 if ((mattrs & FieldAttributes.Static) != 0) {
1008 if ((bindingAttr & BindingFlags.Static) != 0)
1011 if ((bindingAttr & BindingFlags.Instance) != 0)
1021 public override FieldInfo[] GetFields (BindingFlags bindingAttr)
1023 if (created != null)
1024 return created.GetFields (bindingAttr);
1027 return new FieldInfo [0];
1028 ArrayList l = new ArrayList ();
1030 FieldAttributes mattrs;
1032 foreach (FieldInfo c in fields) {
1036 mattrs = c.Attributes;
1037 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
1038 if ((bindingAttr & BindingFlags.Public) != 0)
1041 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1047 if ((mattrs & FieldAttributes.Static) != 0) {
1048 if ((bindingAttr & BindingFlags.Static) != 0)
1051 if ((bindingAttr & BindingFlags.Instance) != 0)
1058 FieldInfo[] result = new FieldInfo [l.Count];
1063 public override Type GetInterface (string name, bool ignoreCase)
1066 return created.GetInterface (name, ignoreCase);
1069 public override Type[] GetInterfaces ()
1071 if (interfaces != null) {
1072 Type[] ret = new Type [interfaces.Length];
1073 interfaces.CopyTo (ret, 0);
1076 return Type.EmptyTypes;
1080 public override MemberInfo[] GetMember (string name, MemberTypes type,
1081 BindingFlags bindingAttr)
1084 return created.GetMember (name, type, bindingAttr);
1087 public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
1090 return created.GetMembers (bindingAttr);
1093 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type)
1095 MethodInfo[] candidates;
1097 MethodAttributes mattrs;
1099 if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
1100 MethodInfo [] parent_methods = parent.GetMethods (bindingAttr);
1101 ArrayList parent_candidates = new ArrayList (parent_methods.Length);
1103 bool flatten = (bindingAttr & BindingFlags.FlattenHierarchy) != 0;
1105 for (int i = 0; i < parent_methods.Length; i++) {
1106 MethodInfo m = parent_methods [i];
1108 mattrs = m.Attributes;
1110 if (m.IsStatic && !flatten)
1113 switch (mattrs & MethodAttributes.MemberAccessMask) {
1114 case MethodAttributes.Public:
1115 match = (bindingAttr & BindingFlags.Public) != 0;
1117 case MethodAttributes.Assembly:
1119 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1124 case MethodAttributes.Private:
1128 match = (bindingAttr & BindingFlags.NonPublic) != 0;
1133 parent_candidates.Add (m);
1136 if (methods == null) {
1137 candidates = new MethodInfo [parent_candidates.Count];
1138 parent_candidates.CopyTo (candidates);
1140 candidates = new MethodInfo [methods.Length + parent_candidates.Count];
1141 parent_candidates.CopyTo (candidates, 0);
1142 methods.CopyTo (candidates, parent_candidates.Count);
1146 candidates = methods;
1148 if (candidates == null)
1149 return new MethodInfo [0];
1151 ArrayList l = new ArrayList ();
1153 foreach (MethodInfo c in candidates) {
1157 if (String.Compare (c.Name, name, ignoreCase) != 0)
1161 mattrs = c.Attributes;
1162 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1163 if ((bindingAttr & BindingFlags.Public) != 0)
1166 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1172 if ((mattrs & MethodAttributes.Static) != 0) {
1173 if ((bindingAttr & BindingFlags.Static) != 0)
1176 if ((bindingAttr & BindingFlags.Instance) != 0)
1184 MethodInfo[] result = new MethodInfo [l.Count];
1189 public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
1191 return GetMethodsByName (null, bindingAttr, false, this);
1194 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
1196 CallingConventions callConvention,
1197 Type[] types, ParameterModifier[] modifiers)
1201 bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
1202 MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
1203 MethodInfo found = null;
1205 int typesLen = (types != null) ? types.Length : 0;
1208 foreach (MethodInfo m in methods) {
1209 // Under MS.NET, Standard|HasThis matches Standard...
1210 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1219 if (count == 1 && typesLen == 0)
1222 match = new MethodBase [count];
1227 foreach (MethodInfo m in methods) {
1228 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1230 match [count++] = m;
1235 return (MethodInfo) Binder.FindMostDerivedMatch (match);
1238 binder = Binder.DefaultBinder;
1240 return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
1243 public override Type GetNestedType (string name, BindingFlags bindingAttr)
1246 return created.GetNestedType (name, bindingAttr);
1249 public override Type[] GetNestedTypes (BindingFlags bindingAttr)
1252 ArrayList result = new ArrayList ();
1254 if (subtypes == null)
1255 return Type.EmptyTypes;
1256 foreach (TypeBuilder t in subtypes) {
1258 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1259 if ((bindingAttr & BindingFlags.Public) != 0)
1262 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1269 Type[] r = new Type [result.Count];
1274 public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
1277 return created.GetProperties (bindingAttr);
1279 if (properties == null)
1280 return new PropertyInfo [0];
1281 ArrayList l = new ArrayList ();
1283 MethodAttributes mattrs;
1284 MethodInfo accessor;
1286 foreach (PropertyInfo c in properties) {
1288 accessor = c.GetGetMethod (true);
1289 if (accessor == null)
1290 accessor = c.GetSetMethod (true);
1291 if (accessor == null)
1293 mattrs = accessor.Attributes;
1294 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1295 if ((bindingAttr & BindingFlags.Public) != 0)
1298 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1304 if ((mattrs & MethodAttributes.Static) != 0) {
1305 if ((bindingAttr & BindingFlags.Static) != 0)
1308 if ((bindingAttr & BindingFlags.Instance) != 0)
1315 PropertyInfo[] result = new PropertyInfo [l.Count];
1320 protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
1322 throw not_supported ();
1325 protected override bool HasElementTypeImpl ()
1328 // a TypeBuilder can never represent an array, pointer
1334 return created.HasElementType;
1337 public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
1340 return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1343 protected override bool IsArrayImpl ()
1345 return Type.IsArrayImpl (this);
1348 protected override bool IsByRefImpl ()
1354 protected override bool IsCOMObjectImpl ()
1356 return ((GetAttributeFlagsImpl () & TypeAttributes.Import) != 0);
1359 protected override bool IsPointerImpl ()
1365 protected override bool IsPrimitiveImpl ()
1371 // FIXME: I doubt just removing this still works.
1372 protected override bool IsValueTypeImpl ()
1374 return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
1375 this != pmodule.assemblyb.corlib_value_type &&
1376 this != pmodule.assemblyb.corlib_enum_type);
1381 public override Type MakeArrayType ()
1383 return base.MakeArrayType ();
1387 public override Type MakeArrayType (int rank)
1389 return base.MakeArrayType (rank);
1393 public override Type MakeByRefType ()
1395 return base.MakeByRefType ();
1399 public override Type MakeGenericType (params Type [] typeArguments)
1401 return base.MakeGenericType (typeArguments);
1405 public override Type MakePointerType ()
1407 return base.MakePointerType ();
1411 public override RuntimeTypeHandle TypeHandle {
1414 return created.TypeHandle;
1418 public void SetCustomAttribute (CustomAttributeBuilder customBuilder)
1420 if (customBuilder == null)
1421 throw new ArgumentNullException ("customBuilder");
1423 string attrname = customBuilder.Ctor.ReflectedType.FullName;
1424 if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1425 byte[] data = customBuilder.Data;
1426 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1427 layout_kind = (int)data [2];
1428 layout_kind |= ((int)data [3]) << 8;
1429 attrs &= ~TypeAttributes.LayoutMask;
1430 switch ((LayoutKind)layout_kind) {
1431 case LayoutKind.Auto:
1432 attrs |= TypeAttributes.AutoLayout;
1434 case LayoutKind.Explicit:
1435 attrs |= TypeAttributes.ExplicitLayout;
1437 case LayoutKind.Sequential:
1438 attrs |= TypeAttributes.SequentialLayout;
1441 // we should ignore it since it can be any value anyway...
1442 throw new Exception ("Error in customattr");
1444 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
1446 if (first_type_name == "System.Int16")
1448 int nnamed = (int)data [pos++];
1449 nnamed |= ((int)data [pos++]) << 8;
1450 for (int i = 0; i < nnamed; ++i) {
1451 //byte named_type = data [pos++];
1453 byte type = data [pos++];
1458 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1459 //string named_typename =
1460 CustomAttributeBuilder.string_from_bytes (data, pos, len);
1462 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1463 // See related code/FIXME in mono/mono/metadata/reflection.c
1466 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1467 named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1469 /* all the fields are integers in StructLayout */
1470 int value = (int)data [pos++];
1471 value |= ((int)data [pos++]) << 8;
1472 value |= ((int)data [pos++]) << 16;
1473 value |= ((int)data [pos++]) << 24;
1474 switch (named_name) {
1476 switch ((CharSet)value) {
1479 attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
1481 case CharSet.Unicode:
1482 attrs &= ~TypeAttributes.AutoClass;
1483 attrs |= TypeAttributes.UnicodeClass;
1486 attrs &= ~TypeAttributes.UnicodeClass;
1487 attrs |= TypeAttributes.AutoClass;
1490 break; // error out...
1494 packing_size = (PackingSize)value;
1500 break; // error out...
1505 } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
1506 attrs |= TypeAttributes.SpecialName;
1509 } else if (attrname == "System.SerializableAttribute") {
1510 attrs |= TypeAttributes.Serializable;
1512 } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
1513 attrs |= TypeAttributes.Import;
1515 } else if (attrname == "System.Security.SuppressUnmanagedCodeSecurityAttribute") {
1516 attrs |= TypeAttributes.HasSecurity;
1519 if (cattrs != null) {
1520 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1521 cattrs.CopyTo (new_array, 0);
1522 new_array [cattrs.Length] = customBuilder;
1525 cattrs = new CustomAttributeBuilder [1];
1526 cattrs [0] = customBuilder;
1533 public void SetCustomAttribute (ConstructorInfo con, byte[] binaryAttribute)
1535 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1538 public EventBuilder DefineEvent (string name, EventAttributes attributes, Type eventtype)
1540 check_name ("name", name);
1541 if (eventtype == null)
1542 throw new ArgumentNullException ("type");
1543 check_not_created ();
1545 EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1546 if (events != null) {
1547 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1548 System.Array.Copy (events, new_events, events.Length);
1549 new_events [events.Length] = res;
1550 events = new_events;
1552 events = new EventBuilder [1];
1558 public FieldBuilder DefineInitializedData (string name, byte[] data, FieldAttributes attributes) {
1560 throw new ArgumentNullException ("data");
1562 FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1563 res.SetRVAData (data);
1567 static int UnmanagedDataCount = 0;
1569 public FieldBuilder DefineUninitializedData (string name, int size, FieldAttributes attributes)
1572 throw new ArgumentNullException ("name");
1573 if (name.Length == 0)
1574 throw new ArgumentException ("Empty name is not legal", "name");
1575 if ((size <= 0) || (size > 0x3f0000))
1576 throw new ArgumentException ("Data size must be > 0 and < 0x3f0000");
1577 check_not_created ();
1579 string typeName = "$ArrayType$" + size;
1580 Type datablobtype = pmodule.GetRegisteredType (fullname + "+" + typeName);
1581 if (datablobtype == null) {
1582 TypeBuilder tb = DefineNestedType (typeName,
1583 TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1584 pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1588 return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1591 public TypeToken TypeToken {
1593 return new TypeToken (0x02000000 | table_idx);
1597 public void SetParent (Type parent)
1599 check_not_created ();
1602 if (parent == null) {
1603 if ((attrs & TypeAttributes.Interface) != 0) {
1604 if ((attrs & TypeAttributes.Abstract) == 0)
1605 throw new InvalidOperationException ("Interface must be declared abstract.");
1608 this.parent = typeof (object);
1611 this.parent = parent;
1615 throw new ArgumentNullException ("parent");
1616 this.parent = parent;
1619 // will just set the parent-related bits if called a second time
1620 setup_internal_class (this);
1623 internal int get_next_table_index (object obj, int table, bool inc) {
1624 return pmodule.get_next_table_index (obj, table, inc);
1630 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1632 if (created == null)
1633 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1635 return created.GetInterfaceMap (interfaceType);
1638 internal bool IsCompilerContext {
1640 return pmodule.assemblyb.IsCompilerContext;
1644 internal bool is_created {
1646 return created != null;
1650 private Exception not_supported ()
1652 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1655 private void check_not_created ()
1658 throw new InvalidOperationException ("Unable to change after type has been created.");
1661 private void check_created ()
1664 throw not_supported ();
1667 private void check_name (string argName, string name)
1670 throw new ArgumentNullException (argName);
1671 if (name.Length == 0)
1672 throw new ArgumentException ("Empty name is not legal", argName);
1673 if (name [0] == ((char)0))
1674 throw new ArgumentException ("Illegal name", argName);
1677 public override String ToString ()
1683 public override bool IsAssignableFrom (Type c)
1685 return base.IsAssignableFrom (c);
1692 public override bool IsSubclassOf (Type c)
1694 return base.IsSubclassOf (c);
1697 [MonoTODO ("arrays")]
1698 internal bool IsAssignableTo (Type c)
1703 if (c.IsInterface) {
1704 if (parent != null && is_created) {
1705 if (c.IsAssignableFrom (parent))
1709 if (interfaces == null)
1711 foreach (Type t in interfaces)
1712 if (c.IsAssignableFrom (t))
1719 return c == typeof (object);
1721 return c.IsAssignableFrom (parent);
1724 #if NET_2_0 || BOOTSTRAP_NET_2_0
1725 public bool IsCreated ()
1730 public override Type[] GetGenericArguments ()
1732 if (generic_params != null)
1733 return generic_params;
1735 throw new InvalidOperationException ();
1738 public override Type GetGenericTypeDefinition ()
1740 create_generic_class ();
1742 return base.GetGenericTypeDefinition ();
1745 public override bool ContainsGenericParameters {
1747 return generic_params != null;
1751 public extern override bool IsGenericParameter {
1752 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1756 public override bool IsGenericTypeDefinition {
1758 return generic_params != null;
1762 public override bool IsGenericType {
1763 get { return IsGenericTypeDefinition; }
1766 public override int GenericParameterPosition {
1768 throw new NotImplementedException ();
1772 public override MethodBase DeclaringMethod {
1774 throw new NotImplementedException ();
1778 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1780 setup_generic_class ();
1782 generic_params = new GenericTypeParameterBuilder [names.Length];
1783 for (int i = 0; i < names.Length; i++)
1784 generic_params [i] = new GenericTypeParameterBuilder (
1785 this, null, names [i], i);
1787 return generic_params;
1790 public static ConstructorInfo GetConstructor (Type type, ConstructorInfo constructor)
1792 ConstructorInfo res = type.GetConstructor (constructor);
1794 throw new System.Exception ("constructor not found");
1799 static bool IsValidGetMethodType (Type type)
1801 if (type is TypeBuilder || type is MonoGenericClass)
1803 /*GetMethod() must work with TypeBuilders after CreateType() was called.*/
1804 if (type.Module is ModuleBuilder)
1806 if (type.IsGenericParameter)
1809 Type[] inst = type.GetGenericArguments ();
1812 for (int i = 0; i < inst.Length; ++i) {
1813 if (IsValidGetMethodType (inst [i]))
1819 public static MethodInfo GetMethod (Type type, MethodInfo method)
1821 if (!IsValidGetMethodType (type))
1822 throw new ArgumentException ("type is not TypeBuilder but " + type.GetType (), "type");
1824 if (!type.IsGenericType)
1825 throw new ArgumentException ("type is not a generic type", "type");
1827 if (!method.DeclaringType.IsGenericTypeDefinition)
1828 throw new ArgumentException ("method declaring type is not a generic type definition", "method");
1829 if (method.DeclaringType != type.GetGenericTypeDefinition ())
1830 throw new ArgumentException ("method declaring type is not the generic type definition of type", "method");
1832 MethodInfo res = type.GetMethod (method);
1834 throw new ArgumentException (String.Format ("method {0} not found in type {1}", method.Name, type));
1839 public static FieldInfo GetField (Type type, FieldInfo field)
1841 FieldInfo res = type.GetField (field);
1843 throw new System.Exception ("field not found");
1849 void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1851 throw new NotImplementedException ();
1854 void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1856 throw new NotImplementedException ();
1859 void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
1861 throw new NotImplementedException ();
1864 void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1866 throw new NotImplementedException ();