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 {
49 [ComDefaultInterface (typeof (_TypeBuilder))]
51 [ClassInterface (ClassInterfaceType.None)]
52 public sealed class TypeBuilder : Type, _TypeBuilder {
53 #region Sync with reflection.h
55 private string nspace;
57 private Type nesting_type;
58 private Type[] interfaces;
59 private int num_methods;
60 private MethodBuilder[] methods;
61 private ConstructorBuilder[] ctors;
62 private PropertyBuilder[] properties;
63 private int num_fields;
64 private FieldBuilder[] fields;
65 private EventBuilder[] events;
66 private CustomAttributeBuilder[] cattrs;
67 internal TypeBuilder[] subtypes;
68 internal TypeAttributes attrs;
69 private int table_idx;
70 private ModuleBuilder pmodule;
71 private int class_size;
72 private PackingSize packing_size;
73 private IntPtr generic_container;
74 #if NET_2_0 || BOOTSTRAP_NET_2_0
75 private GenericTypeParameterBuilder[] generic_params;
77 private Object generic_params; /* so offsets don't change */
79 private RefEmitPermissionSet[] permissions;
84 public const int UnspecifiedTypeSize = 0;
86 protected override TypeAttributes GetAttributeFlagsImpl () {
90 [MethodImplAttribute(MethodImplOptions.InternalCall)]
91 private extern void setup_internal_class (TypeBuilder tb);
93 [MethodImplAttribute(MethodImplOptions.InternalCall)]
94 private extern void create_internal_class (TypeBuilder tb);
96 [MethodImplAttribute(MethodImplOptions.InternalCall)]
97 private extern void setup_generic_class ();
99 [MethodImplAttribute(MethodImplOptions.InternalCall)]
100 private extern void create_generic_class ();
102 [MethodImplAttribute(MethodImplOptions.InternalCall)]
103 private extern EventInfo get_event_info (EventBuilder eb);
105 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr) {
108 this.class_size = UnspecifiedTypeSize;
110 fullname = this.tname = "<Module>";
111 this.nspace = String.Empty;
113 setup_internal_class (this);
116 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type) {
118 this.parent = parent;
120 this.class_size = type_size;
121 this.packing_size = packing_size;
122 this.nesting_type = nesting_type;
123 sep_index = name.LastIndexOf('.');
124 if (sep_index != -1) {
125 this.tname = name.Substring (sep_index + 1);
126 this.nspace = name.Substring (0, sep_index);
129 this.nspace = String.Empty;
131 if (interfaces != null) {
132 this.interfaces = new Type[interfaces.Length];
133 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
137 table_idx = mb.get_next_table_index (this, 0x02, true);
138 setup_internal_class (this);
139 fullname = GetFullName ();
142 public override Assembly Assembly {
143 get {return pmodule.Assembly;}
146 public override string AssemblyQualifiedName {
148 return fullname + ", " + Assembly.GetName().FullName;
151 public override Type BaseType {
156 public override Type DeclaringType {get {return nesting_type;}}
158 /* public override bool IsSubclassOf (Type c)
174 public override Type UnderlyingSystemType {
177 // Return this as requested by Zoltan.
182 // Dont know what to do with the rest, should be killed:
185 ////// This should return the type itself for non-enum types but
186 ////// that breaks mcs.
187 if (fields != null) {
188 foreach (FieldBuilder f in fields) {
189 if ((f != null) && (f.Attributes & FieldAttributes.Static) == 0)
193 throw new InvalidOperationException ("Underlying type information on enumeration is not specified.");
198 string GetFullName () {
199 if (nesting_type != null)
200 return String.Concat (nesting_type.FullName, "+", tname);
201 if ((nspace != null) && (nspace.Length > 0))
202 return String.Concat (nspace, ".", tname);
206 public override string FullName {
212 public override Guid GUID {
219 public override Module Module {
220 get {return pmodule;}
222 public override string Name {
225 public override string Namespace {
228 public PackingSize PackingSize {
229 get {return packing_size;}
232 get { return class_size; }
234 public override Type ReflectedType {get {return nesting_type;}}
236 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
238 throw new ArgumentNullException ("pset");
239 if ((action == SecurityAction.RequestMinimum) ||
240 (action == SecurityAction.RequestOptional) ||
241 (action == SecurityAction.RequestRefuse))
242 throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");
244 check_not_created ();
246 if (permissions != null) {
247 /* Check duplicate actions */
248 foreach (RefEmitPermissionSet set in permissions)
249 if (set.action == action)
250 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
252 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
253 permissions.CopyTo (new_array, 0);
254 permissions = new_array;
257 permissions = new RefEmitPermissionSet [1];
259 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
260 attrs |= TypeAttributes.HasSecurity;
266 public void AddInterfaceImplementation( Type interfaceType) {
267 if (interfaceType == null)
268 throw new ArgumentNullException ("interfaceType");
269 check_not_created ();
271 if (interfaces != null) {
272 // Check for duplicates
273 foreach (Type t in interfaces)
274 if (t == interfaceType)
277 Type[] ifnew = new Type [interfaces.Length + 1];
278 interfaces.CopyTo (ifnew, 0);
279 ifnew [interfaces.Length] = interfaceType;
282 interfaces = new Type [1];
283 interfaces [0] = interfaceType;
288 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
289 CallingConventions callConvention, Type[] types,
290 ParameterModifier[] modifiers)
297 ConstructorBuilder found = null;
300 foreach (ConstructorBuilder cb in ctors){
301 if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
311 throw new AmbiguousMatchException ();
314 MethodBase[] match = new MethodBase [count];
319 foreach (ConstructorInfo m in ctors) {
320 if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
326 binder = Binder.DefaultBinder;
327 return (ConstructorInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
330 public override bool IsDefined( Type attributeType, bool inherit)
333 * MS throws NotSupported here, but we can't because some corlib
334 * classes make calls to IsDefined.
336 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
339 public override object[] GetCustomAttributes(bool inherit)
343 return created.GetCustomAttributes (inherit);
346 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
350 return created.GetCustomAttributes (attributeType, inherit);
353 public TypeBuilder DefineNestedType (string name) {
354 return DefineNestedType (name, TypeAttributes.NestedPrivate, pmodule.assemblyb.corlib_object_type, null);
357 public TypeBuilder DefineNestedType (string name, TypeAttributes attr) {
358 return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
361 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) {
362 return DefineNestedType (name, attr, parent, null);
365 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
366 PackingSize packsize, int typesize)
368 check_name ("name", name);
369 // Visibility must be NestedXXX
371 if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
372 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
373 throw new ArgumentException ("attr", "Bad type flags for nested type.");
375 if (interfaces != null)
376 foreach (Type iface in interfaces)
378 throw new ArgumentNullException ("interfaces");
380 TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packsize, typesize, this);
381 res.fullname = res.GetFullName ();
382 pmodule.RegisterTypeName (res, res.fullname);
383 if (subtypes != null) {
384 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
385 System.Array.Copy (subtypes, new_types, subtypes.Length);
386 new_types [subtypes.Length] = res;
387 subtypes = new_types;
389 subtypes = new TypeBuilder [1];
398 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
399 return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
402 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
403 return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typesize);
406 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
407 return DefineNestedType (name, attr, parent, null, packsize, UnspecifiedTypeSize);
413 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) {
414 return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
420 #if NET_2_0 || BOOTSTRAP_NET_2_0
425 ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
427 check_not_created ();
428 ConstructorBuilder cb = new ConstructorBuilder (this, attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
430 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
431 System.Array.Copy (ctors, new_ctors, ctors.Length);
432 new_ctors [ctors.Length] = cb;
435 ctors = new ConstructorBuilder [1];
444 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
449 parent_type = parent;
451 parent_type = pmodule.assemblyb.corlib_object_type;
453 ConstructorInfo parent_constructor =
454 parent_type.GetConstructor (
455 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
456 null, Type.EmptyTypes, null);
457 if (parent_constructor == null) {
458 throw new NotSupportedException ("Parent does"
459 + " not have a default constructor."
460 + " The default constructor must be"
461 + " explicitly defined.");
464 ConstructorBuilder cb = DefineConstructor (attributes,
465 CallingConventions.Standard, new Type[0]);
466 ILGenerator ig = cb.GetILGenerator ();
467 ig.Emit (OpCodes.Ldarg_0);
468 ig.Emit (OpCodes.Call, parent_constructor);
469 ig.Emit (OpCodes.Ret);
473 private void append_method (MethodBuilder mb) {
474 if (methods != null) {
475 if (methods.Length == num_methods) {
476 MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
477 System.Array.Copy (methods, new_methods, num_methods);
478 methods = new_methods;
481 methods = new MethodBuilder [1];
483 methods [num_methods] = mb;
487 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
488 return DefineMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
491 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
492 return DefineMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
495 #if NET_2_0 || BOOTSTRAP_NET_2_0
500 MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
501 check_name ("name", name);
502 check_not_created ();
504 !((attributes & MethodAttributes.Abstract) != 0) ||
505 !((attributes & MethodAttributes.Virtual) != 0)) &&
506 !(((attributes & MethodAttributes.Static) != 0)))
507 throw new ArgumentException ("attributes", "Interface method must be abstract and virtual.");
509 if (returnType == null)
510 returnType = pmodule.assemblyb.corlib_void_type;
511 MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
516 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
517 return DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet);
520 #if NET_2_0 || BOOTSTRAP_NET_2_0
525 MethodBuilder DefinePInvokeMethod (
528 string entryName, MethodAttributes attributes,
529 CallingConventions callingConvention,
531 Type[] returnTypeRequiredCustomModifiers,
532 Type[] returnTypeOptionalCustomModifiers,
533 Type[] parameterTypes,
534 Type[][] parameterTypeRequiredCustomModifiers,
535 Type[][] parameterTypeOptionalCustomModifiers,
536 CallingConvention nativeCallConv,
537 CharSet nativeCharSet) {
538 check_name ("name", name);
539 check_name ("dllName", dllName);
540 check_name ("entryName", entryName);
541 if ((attributes & MethodAttributes.Abstract) != 0)
542 throw new ArgumentException ("attributes", "PInvoke methods must be static and native and cannot be abstract.");
544 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
545 check_not_created ();
548 = new MethodBuilder (
554 returnTypeRequiredCustomModifiers,
555 returnTypeOptionalCustomModifiers,
557 parameterTypeRequiredCustomModifiers,
558 parameterTypeOptionalCustomModifiers,
567 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
568 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
569 nativeCallConv, nativeCharSet);
572 #if NET_2_0 || BOOTSTRAP_NET_2_0
573 public MethodBuilder DefineMethod (string name, MethodAttributes attributes) {
574 return DefineMethod (name, attributes, CallingConventions.Standard);
577 public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callConv) {
578 return DefineMethod (name, attributes, callConv, null, null);
582 public void DefineMethodOverride( MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) {
583 if (methodInfoBody == null)
584 throw new ArgumentNullException ("methodInfoBody");
585 if (methodInfoDeclaration == null)
586 throw new ArgumentNullException ("methodInfoDeclaration");
587 check_not_created ();
589 if (methodInfoBody is MethodBuilder) {
590 MethodBuilder mb = (MethodBuilder)methodInfoBody;
591 mb.set_override (methodInfoDeclaration);
595 public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) {
596 return DefineField (fieldName, type, null, null, attributes);
599 #if NET_2_0 || BOOTSTRAP_NET_2_0
604 FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomAttributes, Type[] optionalCustomAttributes, FieldAttributes attributes) {
605 check_name ("fieldName", fieldName);
606 if (type == typeof (void))
607 throw new ArgumentException ("type", "Bad field type in defining field.");
608 check_not_created ();
610 FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomAttributes, optionalCustomAttributes);
611 if (fields != null) {
612 if (fields.Length == num_fields) {
613 FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
614 System.Array.Copy (fields, new_fields, num_fields);
617 fields [num_fields] = res;
620 fields = new FieldBuilder [1];
623 create_internal_class (this);
628 public PropertyBuilder DefineProperty( string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
629 return DefineProperty (name, attributes, returnType, null, null, parameterTypes, null, null);
637 PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
638 check_name ("name", name);
639 if (parameterTypes != null)
640 foreach (Type param in parameterTypes)
642 throw new ArgumentNullException ("parameterTypes");
643 check_not_created ();
645 PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
647 if (properties != null) {
648 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
649 System.Array.Copy (properties, new_properties, properties.Length);
650 new_properties [properties.Length] = res;
651 properties = new_properties;
653 properties = new PropertyBuilder [1];
654 properties [0] = res;
662 public ConstructorBuilder DefineTypeInitializer() {
663 return DefineConstructor (MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, null);
666 [MethodImplAttribute(MethodImplOptions.InternalCall)]
667 private extern Type create_runtime_class (TypeBuilder tb);
669 private bool is_nested_in (Type t) {
679 public Type CreateType() {
680 /* handle nesting_type */
684 create_generic_class ();
686 // Fire TypeResolve events for fields whose type is an unfinished
688 if (fields != null) {
689 foreach (FieldBuilder fb in fields) {
692 Type ft = fb.FieldType;
693 if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
694 TypeBuilder tb = (TypeBuilder)ft;
695 if (!tb.is_created) {
696 AppDomain.CurrentDomain.DoTypeResolve (tb);
697 if (!tb.is_created) {
698 // FIXME: We should throw an exception here,
699 // but mcs expects that the type is created
700 // even if the exception is thrown
701 //throw new TypeLoadException ("Could not load type " + tb);
708 if ((parent != null) && parent.IsSealed)
709 throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
711 if (methods != null) {
712 for (int i = 0; i < num_methods; ++i)
713 ((MethodBuilder)(methods[i])).fixup ();
717 // On classes, define a default constructor if not provided
719 if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") &&
720 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed))
721 DefineDefaultConstructor (MethodAttributes.Public);
724 foreach (ConstructorBuilder ctor in ctors)
728 created = create_runtime_class (this);
734 internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
736 symbolWriter.OpenNamespace (this.Namespace);
738 if (methods != null) {
739 for (int i = 0; i < num_methods; ++i) {
740 MethodBuilder metb = (MethodBuilder) methods[i];
741 metb.GenerateDebugInfo (symbolWriter);
746 foreach (ConstructorBuilder ctor in ctors)
747 ctor.GenerateDebugInfo (symbolWriter);
750 symbolWriter.CloseNamespace ();
756 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
759 return new ConstructorInfo [0];
760 ArrayList l = new ArrayList ();
762 MethodAttributes mattrs;
764 foreach (ConstructorBuilder c in ctors) {
766 mattrs = c.Attributes;
767 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
768 if ((bindingAttr & BindingFlags.Public) != 0)
771 if ((bindingAttr & BindingFlags.NonPublic) != 0)
777 if ((mattrs & MethodAttributes.Static) != 0) {
778 if ((bindingAttr & BindingFlags.Static) != 0)
781 if ((bindingAttr & BindingFlags.Instance) != 0)
788 ConstructorInfo[] result = new ConstructorInfo [l.Count];
793 public override Type GetElementType () {
795 return created.GetElementType ();
798 public override EventInfo GetEvent (string name, BindingFlags bindingAttr) {
800 return created.GetEvent (name, bindingAttr);
803 /* Needed to keep signature compatibility with MS.NET */
804 public override EventInfo[] GetEvents ()
806 return GetEvents (DefaultBindingFlags);
809 public override EventInfo[] GetEvents (BindingFlags bindingAttr) {
810 /* FIXME: mcs calls this
814 return new EventInfo [0];
816 return created.GetEvents (bindingAttr);
819 // This is only used from MonoGenericInst.initialize().
820 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
823 return new EventInfo [0];
824 ArrayList l = new ArrayList ();
826 MethodAttributes mattrs;
829 foreach (EventBuilder eb in events) {
832 EventInfo c = get_event_info (eb);
834 accessor = c.GetAddMethod (true);
835 if (accessor == null)
836 accessor = c.GetRemoveMethod (true);
837 if (accessor == null)
839 mattrs = accessor.Attributes;
840 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
841 if ((bindingAttr & BindingFlags.Public) != 0)
844 if ((bindingAttr & BindingFlags.NonPublic) != 0)
850 if ((mattrs & MethodAttributes.Static) != 0) {
851 if ((bindingAttr & BindingFlags.Static) != 0)
854 if ((bindingAttr & BindingFlags.Instance) != 0)
861 EventInfo[] result = new EventInfo [l.Count];
866 public override FieldInfo GetField( string name, BindingFlags bindingAttr) {
871 FieldAttributes mattrs;
873 foreach (FieldInfo c in fields) {
879 mattrs = c.Attributes;
880 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
881 if ((bindingAttr & BindingFlags.Public) != 0)
884 if ((bindingAttr & BindingFlags.NonPublic) != 0)
890 if ((mattrs & FieldAttributes.Static) != 0) {
891 if ((bindingAttr & BindingFlags.Static) != 0)
894 if ((bindingAttr & BindingFlags.Instance) != 0)
904 public override FieldInfo[] GetFields (BindingFlags bindingAttr) {
906 return new FieldInfo [0];
907 ArrayList l = new ArrayList ();
909 FieldAttributes mattrs;
911 foreach (FieldInfo c in fields) {
915 mattrs = c.Attributes;
916 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
917 if ((bindingAttr & BindingFlags.Public) != 0)
920 if ((bindingAttr & BindingFlags.NonPublic) != 0)
926 if ((mattrs & FieldAttributes.Static) != 0) {
927 if ((bindingAttr & BindingFlags.Static) != 0)
930 if ((bindingAttr & BindingFlags.Instance) != 0)
937 FieldInfo[] result = new FieldInfo [l.Count];
942 public override Type GetInterface (string name, bool ignoreCase) {
944 return created.GetInterface (name, ignoreCase);
947 public override Type[] GetInterfaces () {
948 if (interfaces != null) {
949 Type[] ret = new Type [interfaces.Length];
950 interfaces.CopyTo (ret, 0);
953 return Type.EmptyTypes;
957 public override MemberInfo[] GetMember (string name, MemberTypes type,
958 BindingFlags bindingAttr) {
960 return created.GetMember (name, type, bindingAttr);
963 public override MemberInfo[] GetMembers (BindingFlags bindingAttr) {
965 return created.GetMembers (bindingAttr);
968 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type) {
969 MethodInfo[] candidates;
970 if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
971 MethodInfo[] parent_methods = parent.GetMethods (bindingAttr);
973 candidates = parent_methods;
975 candidates = new MethodInfo [methods.Length + parent_methods.Length];
976 parent_methods.CopyTo (candidates, 0);
977 methods.CopyTo (candidates, parent_methods.Length);
981 candidates = methods;
983 if (candidates == null)
984 return new MethodInfo [0];
986 ArrayList l = new ArrayList ();
988 MethodAttributes mattrs;
990 foreach (MethodInfo c in candidates) {
994 if (String.Compare (c.Name, name, ignoreCase) != 0)
998 mattrs = c.Attributes;
999 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1000 if ((bindingAttr & BindingFlags.Public) != 0)
1003 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1009 if ((mattrs & MethodAttributes.Static) != 0) {
1010 if ((bindingAttr & BindingFlags.Static) != 0)
1013 if ((bindingAttr & BindingFlags.Instance) != 0)
1021 MethodInfo[] result = new MethodInfo [l.Count];
1026 public override MethodInfo[] GetMethods (BindingFlags bindingAttr) {
1027 return GetMethodsByName (null, bindingAttr, false, this);
1030 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
1032 CallingConventions callConvention,
1033 Type[] types, ParameterModifier[] modifiers)
1037 bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
1038 MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
1039 MethodInfo found = null;
1041 int typesLen = (types != null) ? types.Length : 0;
1044 foreach (MethodInfo m in methods) {
1045 // Under MS.NET, Standard|HasThis matches Standard...
1046 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1055 if (count == 1 && typesLen == 0)
1058 match = new MethodBase [count];
1063 foreach (MethodInfo m in methods) {
1064 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
1066 match [count++] = m;
1071 return (MethodInfo) Binder.FindMostDerivedMatch (match);
1074 binder = Binder.DefaultBinder;
1076 return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
1079 public override Type GetNestedType( string name, BindingFlags bindingAttr) {
1081 return created.GetNestedType (name, bindingAttr);
1084 public override Type[] GetNestedTypes (BindingFlags bindingAttr) {
1086 ArrayList result = new ArrayList ();
1088 if (subtypes == null)
1089 return Type.EmptyTypes;
1090 foreach (TypeBuilder t in subtypes) {
1092 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1093 if ((bindingAttr & BindingFlags.Public) != 0)
1096 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1103 Type[] r = new Type [result.Count];
1108 public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) {
1109 if (properties == null)
1110 return new PropertyInfo [0];
1111 ArrayList l = new ArrayList ();
1113 MethodAttributes mattrs;
1114 MethodInfo accessor;
1116 foreach (PropertyInfo c in properties) {
1118 accessor = c.GetGetMethod (true);
1119 if (accessor == null)
1120 accessor = c.GetSetMethod (true);
1121 if (accessor == null)
1123 mattrs = accessor.Attributes;
1124 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1125 if ((bindingAttr & BindingFlags.Public) != 0)
1128 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1134 if ((mattrs & MethodAttributes.Static) != 0) {
1135 if ((bindingAttr & BindingFlags.Static) != 0)
1138 if ((bindingAttr & BindingFlags.Instance) != 0)
1145 PropertyInfo[] result = new PropertyInfo [l.Count];
1150 protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
1151 throw not_supported ();
1154 protected override bool HasElementTypeImpl () {
1156 return created.HasElementType;
1159 public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
1161 return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1164 protected override bool IsArrayImpl ()
1166 return Type.IsArrayImpl (this);
1169 protected override bool IsByRefImpl () {
1173 protected override bool IsCOMObjectImpl () {
1176 protected override bool IsPointerImpl () {
1180 protected override bool IsPrimitiveImpl () {
1184 protected override bool IsValueTypeImpl () {
1185 return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
1186 this != pmodule.assemblyb.corlib_value_type &&
1187 this != pmodule.assemblyb.corlib_enum_type);
1190 public override RuntimeTypeHandle TypeHandle {
1193 return created.TypeHandle;
1197 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
1198 if (customBuilder == null)
1199 throw new ArgumentNullException ("customBuilder");
1201 string attrname = customBuilder.Ctor.ReflectedType.FullName;
1202 if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1203 byte[] data = customBuilder.Data;
1204 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1205 layout_kind = (int)data [2];
1206 layout_kind |= ((int)data [3]) << 8;
1207 attrs &= ~TypeAttributes.LayoutMask;
1208 switch ((LayoutKind)layout_kind) {
1209 case LayoutKind.Auto:
1210 attrs |= TypeAttributes.AutoLayout;
1212 case LayoutKind.Explicit:
1213 attrs |= TypeAttributes.ExplicitLayout;
1215 case LayoutKind.Sequential:
1216 attrs |= TypeAttributes.SequentialLayout;
1219 // we should ignore it since it can be any value anyway...
1220 throw new Exception ("Error in customattr");
1222 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
1224 if (first_type_name == "System.Int16")
1226 int nnamed = (int)data [pos++];
1227 nnamed |= ((int)data [pos++]) << 8;
1228 for (int i = 0; i < nnamed; ++i) {
1229 //byte named_type = data [pos++];
1231 byte type = data [pos++];
1236 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1237 //string named_typename =
1238 CustomAttributeBuilder.string_from_bytes (data, pos, len);
1240 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1241 // See related code/FIXME in mono/mono/metadata/reflection.c
1244 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1245 named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1247 /* all the fields are integers in StructLayout */
1248 int value = (int)data [pos++];
1249 value |= ((int)data [pos++]) << 8;
1250 value |= ((int)data [pos++]) << 16;
1251 value |= ((int)data [pos++]) << 24;
1252 switch (named_name) {
1254 switch ((CharSet)value) {
1257 attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
1259 case CharSet.Unicode:
1260 attrs &= ~TypeAttributes.AutoClass;
1261 attrs |= TypeAttributes.UnicodeClass;
1264 attrs &= ~TypeAttributes.UnicodeClass;
1265 attrs |= TypeAttributes.AutoClass;
1268 break; // error out...
1272 packing_size = (PackingSize)value;
1278 break; // error out...
1283 } else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
1284 attrs |= TypeAttributes.SpecialName;
1287 } else if (attrname == "System.SerializableAttribute") {
1288 attrs |= TypeAttributes.Serializable;
1290 } else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
1291 attrs |= TypeAttributes.Import;
1295 if (cattrs != null) {
1296 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1297 cattrs.CopyTo (new_array, 0);
1298 new_array [cattrs.Length] = customBuilder;
1301 cattrs = new CustomAttributeBuilder [1];
1302 cattrs [0] = customBuilder;
1309 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
1310 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1313 public EventBuilder DefineEvent( string name, EventAttributes attributes, Type eventtype) {
1314 check_name ("name", name);
1315 if (eventtype == null)
1316 throw new ArgumentNullException ("eventtype");
1317 check_not_created ();
1319 EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1320 if (events != null) {
1321 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1322 System.Array.Copy (events, new_events, events.Length);
1323 new_events [events.Length] = res;
1324 events = new_events;
1326 events = new EventBuilder [1];
1332 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
1334 throw new ArgumentNullException ("data");
1335 if ((data.Length == 0) || (data.Length > 0x3f0000))
1336 throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
1338 FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1339 res.SetRVAData (data);
1344 static int UnmanagedDataCount = 0;
1346 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes)
1348 check_name ("name", name);
1349 if ((size <= 0) || (size > 0x3f0000))
1350 throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
1351 check_not_created ();
1353 string typeName = "$ArrayType$" + size;
1354 Type datablobtype = pmodule.GetRegisteredType (fullname + "+" + typeName);
1355 if (datablobtype == null) {
1356 TypeBuilder tb = DefineNestedType (typeName,
1357 TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1358 pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1362 return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1365 public TypeToken TypeToken {
1367 return new TypeToken (0x02000000 | table_idx);
1370 public void SetParent (Type parentType) {
1371 check_not_created ();
1373 if (parentType == null && (attrs & TypeAttributes.Interface) == 0)
1374 throw new ArgumentNullException ("parentType");
1376 parent = parentType;
1377 // will just set the parent-related bits if called a second time
1378 setup_internal_class (this);
1380 internal int get_next_table_index (object obj, int table, bool inc) {
1381 return pmodule.get_next_table_index (obj, table, inc);
1387 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1389 if (created == null)
1390 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1392 return created.GetInterfaceMap (interfaceType);
1395 internal bool is_created {
1397 return created != null;
1401 private Exception not_supported ()
1403 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1406 private void check_not_created ()
1409 throw new InvalidOperationException ("Unable to change after type has been created.");
1412 private void check_created ()
1415 throw not_supported ();
1418 private void check_name (string argName, string name)
1421 throw new ArgumentNullException (argName);
1422 if (name.Length == 0)
1423 throw new ArgumentException ("Empty name is not legal", argName);
1424 if (name.IndexOf ((char)0) != -1)
1425 throw new ArgumentException ("Illegal name", argName);
1428 public override String ToString ()
1434 public override bool IsAssignableFrom (Type c)
1436 return base.IsAssignableFrom (c);
1443 public override bool IsSubclassOf (Type c)
1445 return base.IsSubclassOf (c);
1448 [MonoTODO ("arrays")]
1449 internal bool IsAssignableTo (Type c)
1454 if (c.IsInterface) {
1455 if (interfaces == null)
1457 foreach (Type t in interfaces)
1458 if (c.IsAssignableFrom (t))
1464 return c == typeof (object);
1466 return c.IsAssignableFrom (parent);
1469 #if NET_2_0 || BOOTSTRAP_NET_2_0
1470 public bool IsCreated () {
1474 public override Type[] GetGenericArguments ()
1476 if (generic_params != null)
1477 return generic_params;
1479 throw new InvalidOperationException ();
1482 public override Type GetGenericTypeDefinition ()
1484 create_generic_class ();
1486 return base.GetGenericTypeDefinition ();
1489 public override bool ContainsGenericParameters {
1491 return generic_params != null;
1495 public extern override bool IsGenericParameter {
1496 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1500 public override bool IsGenericTypeDefinition {
1502 return generic_params != null;
1506 public override bool IsGenericType {
1507 get { return IsGenericTypeDefinition; }
1510 public override int GenericParameterPosition {
1512 throw new NotImplementedException ();
1516 public override MethodBase DeclaringMethod {
1518 throw new NotImplementedException ();
1522 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1524 setup_generic_class ();
1526 generic_params = new GenericTypeParameterBuilder [names.Length];
1527 for (int i = 0; i < names.Length; i++)
1528 generic_params [i] = new GenericTypeParameterBuilder (
1529 this, null, names [i], i);
1531 return generic_params;
1534 public static ConstructorInfo GetConstructor (Type instanciated, ConstructorInfo ctor)
1536 ConstructorInfo res = instanciated.GetConstructor (ctor);
1538 throw new System.Exception ("constructor not found");
1543 public static MethodInfo GetMethod (Type instanciated, MethodInfo meth)
1545 MethodInfo res = instanciated.GetMethod (meth);
1547 throw new System.Exception ("method not found");
1552 public static FieldInfo GetField (Type instanciated, FieldInfo fld)
1554 FieldInfo res = instanciated.GetField (fld);
1556 throw new System.Exception ("field not found");
1562 void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1564 throw new NotImplementedException ();
1567 void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1569 throw new NotImplementedException ();
1572 void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
1574 throw new NotImplementedException ();
1577 void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1579 throw new NotImplementedException ();