2 // System.Reflection.Emit/TypeBuilder.cs
5 // Paolo Molaro (lupus@ximian.com)
7 // (C) 2001 Ximian, Inc. http://www.ximian.com
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Reflection;
36 using System.Reflection.Emit;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
39 using System.Globalization;
40 using System.Collections;
41 using System.Security;
42 using System.Security.Permissions;
44 namespace System.Reflection.Emit {
46 public sealed class TypeBuilder : Type {
47 #region Sync with reflection.h
49 private string nspace;
51 private Type nesting_type;
52 private Type[] interfaces;
53 private int num_methods;
54 private MethodBuilder[] methods;
55 private ConstructorBuilder[] ctors;
56 private PropertyBuilder[] properties;
57 private int num_fields;
58 private FieldBuilder[] fields;
59 private EventBuilder[] events;
60 private CustomAttributeBuilder[] cattrs;
61 internal TypeBuilder[] subtypes;
62 internal TypeAttributes attrs;
63 private int table_idx;
64 private ModuleBuilder pmodule;
65 private int class_size;
66 private PackingSize packing_size;
67 private IntPtr generic_container;
68 #if NET_2_0 || BOOTSTRAP_NET_2_0
69 private GenericTypeParameterBuilder[] generic_params;
71 private Object generic_params; /* so offsets don't change */
73 private RefEmitPermissionSet[] permissions;
78 public const int UnspecifiedTypeSize = 0;
80 protected override TypeAttributes GetAttributeFlagsImpl () {
84 [MethodImplAttribute(MethodImplOptions.InternalCall)]
85 private extern void setup_internal_class (TypeBuilder tb);
87 [MethodImplAttribute(MethodImplOptions.InternalCall)]
88 private extern void create_internal_class (TypeBuilder tb);
90 [MethodImplAttribute(MethodImplOptions.InternalCall)]
91 private extern void setup_generic_class ();
93 [MethodImplAttribute(MethodImplOptions.InternalCall)]
94 private extern void create_generic_class ();
96 [MethodImplAttribute(MethodImplOptions.InternalCall)]
97 private extern EventInfo get_event_info (EventBuilder eb);
99 internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr) {
102 this.class_size = UnspecifiedTypeSize;
104 fullname = this.tname = "<Module>";
107 setup_internal_class (this);
110 internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type) {
112 this.parent = parent;
114 this.class_size = type_size;
115 this.packing_size = packing_size;
116 this.nesting_type = nesting_type;
117 sep_index = name.LastIndexOf('.');
118 if (sep_index != -1) {
119 this.tname = name.Substring (sep_index + 1);
120 this.nspace = name.Substring (0, sep_index);
125 if (interfaces != null) {
126 this.interfaces = new Type[interfaces.Length];
127 System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
131 table_idx = mb.get_next_table_index (this, 0x02, true);
132 setup_internal_class (this);
133 fullname = GetFullName ();
136 public override Assembly Assembly {
137 get {return pmodule.Assembly;}
140 public override string AssemblyQualifiedName {
142 return fullname + ", " + Assembly.GetName().FullName;
145 public override Type BaseType {
150 public override Type DeclaringType {get {return nesting_type;}}
152 /* public override bool IsSubclassOf (Type c)
169 public override Type UnderlyingSystemType {
171 // This should return the type itself for non-enum types but
173 if (fields != null) {
174 foreach (FieldBuilder f in fields) {
175 if ((f != null) && (f.Attributes & FieldAttributes.Static) == 0)
179 throw new InvalidOperationException ("Underlying type information on enumeration is not specified.");
183 string GetFullName () {
184 if (nesting_type != null)
185 return String.Concat (nesting_type.FullName, "+", tname);
186 if ((nspace != null) && (nspace.Length > 0))
187 return String.Concat (nspace, ".", tname);
191 public override string FullName {
197 public override Guid GUID {
204 public override Module Module {
205 get {return pmodule;}
207 public override string Name {
210 public override string Namespace {
213 public PackingSize PackingSize {
214 get {return packing_size;}
217 get { return class_size; }
219 public override Type ReflectedType {get {return nesting_type;}}
221 public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
223 throw new ArgumentNullException ("pset");
224 if ((action == SecurityAction.RequestMinimum) ||
225 (action == SecurityAction.RequestOptional) ||
226 (action == SecurityAction.RequestRefuse))
227 throw new ArgumentException ("Request* values are not permitted", "action");
229 check_not_created ();
231 if (permissions != null) {
232 /* Check duplicate actions */
233 foreach (RefEmitPermissionSet set in permissions)
234 if (set.action == action)
235 throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");
237 RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
238 permissions.CopyTo (new_array, 0);
239 permissions = new_array;
242 permissions = new RefEmitPermissionSet [1];
244 permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
245 attrs |= TypeAttributes.HasSecurity;
248 public void AddInterfaceImplementation( Type interfaceType) {
249 if (interfaceType == null)
250 throw new ArgumentNullException ("interfaceType");
251 check_not_created ();
253 if (interfaces != null) {
254 // Check for duplicates
255 foreach (Type t in interfaces)
256 if (t == interfaceType)
259 Type[] ifnew = new Type [interfaces.Length + 1];
260 interfaces.CopyTo (ifnew, 0);
261 ifnew [interfaces.Length] = interfaceType;
264 interfaces = new Type [1];
265 interfaces [0] = interfaceType;
270 protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
271 CallingConventions callConvention, Type[] types,
272 ParameterModifier[] modifiers)
279 ConstructorBuilder found = null;
282 foreach (ConstructorBuilder cb in ctors){
283 if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
293 throw new AmbiguousMatchException ();
296 MethodBase[] match = new MethodBase [count];
301 foreach (ConstructorInfo m in ctors) {
302 if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
308 binder = Binder.DefaultBinder;
309 return (ConstructorInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
312 public override bool IsDefined( Type attributeType, bool inherit)
315 * MS throws NotSupported here, but we can't because some corlib
316 * classes make calls to IsDefined.
318 return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
321 public override object[] GetCustomAttributes(bool inherit)
325 return created.GetCustomAttributes (inherit);
328 public override object[] GetCustomAttributes(Type attributeType, bool inherit)
332 return created.GetCustomAttributes (attributeType, inherit);
335 public TypeBuilder DefineNestedType (string name) {
336 return DefineNestedType (name, TypeAttributes.NestedPrivate, pmodule.assemblyb.corlib_object_type, null);
339 public TypeBuilder DefineNestedType (string name, TypeAttributes attr) {
340 return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
343 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) {
344 return DefineNestedType (name, attr, parent, null);
347 private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
348 PackingSize packsize, int typesize)
350 check_name ("name", name);
351 // Visibility must be NestedXXX
353 if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
354 ((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
355 throw new ArgumentException ("attr", "Bad type flags for nested type.");
357 if (interfaces != null)
358 foreach (Type iface in interfaces)
360 throw new ArgumentNullException ("interfaces");
362 TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packsize, typesize, this);
363 res.fullname = res.GetFullName ();
364 pmodule.RegisterTypeName (res, res.fullname);
365 if (subtypes != null) {
366 TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
367 System.Array.Copy (subtypes, new_types, subtypes.Length);
368 new_types [subtypes.Length] = res;
369 subtypes = new_types;
371 subtypes = new TypeBuilder [1];
377 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
378 return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
381 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
382 return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typesize);
385 public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
386 return DefineNestedType (name, attr, parent, null, packsize, UnspecifiedTypeSize);
389 public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) {
390 return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
393 #if NET_2_0 || BOOTSTRAP_NET_2_0
398 ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
400 check_not_created ();
401 ConstructorBuilder cb = new ConstructorBuilder (this, attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
403 ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
404 System.Array.Copy (ctors, new_ctors, ctors.Length);
405 new_ctors [ctors.Length] = cb;
408 ctors = new ConstructorBuilder [1];
414 public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
419 parent_type = parent;
421 parent_type = pmodule.assemblyb.corlib_object_type;
423 ConstructorInfo parent_constructor =
424 parent_type.GetConstructor (
425 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
426 null, Type.EmptyTypes, null);
427 if (parent_constructor == null) {
428 throw new NotSupportedException ("Parent does"
429 + " not have a default constructor."
430 + " The default constructor must be"
431 + " explicitly defined.");
434 ConstructorBuilder cb = DefineConstructor (attributes,
435 CallingConventions.Standard, new Type[0]);
436 ILGenerator ig = cb.GetILGenerator ();
437 ig.Emit (OpCodes.Ldarg_0);
438 ig.Emit (OpCodes.Call, parent_constructor);
439 ig.Emit (OpCodes.Ret);
443 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
444 return DefineMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
447 private void append_method (MethodBuilder mb) {
448 if (methods != null) {
449 if (methods.Length == num_methods) {
450 MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
451 System.Array.Copy (methods, new_methods, num_methods);
452 methods = new_methods;
455 methods = new MethodBuilder [1];
457 methods [num_methods] = mb;
461 public MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
462 return DefineMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
465 #if NET_2_0 || BOOTSTRAP_NET_2_0
470 MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
471 check_name ("name", name);
472 check_not_created ();
474 !((attributes & MethodAttributes.Abstract) != 0) ||
475 !((attributes & MethodAttributes.Virtual) != 0)))
476 throw new ArgumentException ("attributes", "Interface method must be abstract and virtual.");
478 if (returnType == null)
479 returnType = pmodule.assemblyb.corlib_void_type;
480 MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
485 public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
486 return DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet);
489 #if NET_2_0 || BOOTSTRAP_NET_2_0
494 MethodBuilder DefinePInvokeMethod (
497 string entryName, MethodAttributes attributes,
498 CallingConventions callingConvention,
500 Type[] returnTypeRequiredCustomModifiers,
501 Type[] returnTypeOptionalCustomModifiers,
502 Type[] parameterTypes,
503 Type[][] parameterTypeRequiredCustomModifiers,
504 Type[][] parameterTypeOptionalCustomModifiers,
505 CallingConvention nativeCallConv,
506 CharSet nativeCharSet) {
507 check_name ("name", name);
508 check_name ("dllName", dllName);
509 check_name ("entryName", entryName);
510 if ((attributes & MethodAttributes.Abstract) != 0)
511 throw new ArgumentException ("attributes", "PInvoke methods must be static and native and cannot be abstract.");
513 throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");
514 check_not_created ();
517 = new MethodBuilder (
523 returnTypeRequiredCustomModifiers,
524 returnTypeOptionalCustomModifiers,
526 parameterTypeRequiredCustomModifiers,
527 parameterTypeOptionalCustomModifiers,
536 public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
537 return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
538 nativeCallConv, nativeCharSet);
541 public void DefineMethodOverride( MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) {
542 if (methodInfoBody == null)
543 throw new ArgumentNullException ("methodInfoBody");
544 if (methodInfoDeclaration == null)
545 throw new ArgumentNullException ("methodInfoDeclaration");
546 check_not_created ();
548 if (methodInfoBody is MethodBuilder) {
549 MethodBuilder mb = (MethodBuilder)methodInfoBody;
550 mb.set_override (methodInfoDeclaration);
554 public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) {
555 return DefineField (fieldName, type, null, null, attributes);
558 #if NET_2_0 || BOOTSTRAP_NET_2_0
563 FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomAttributes, Type[] optionalCustomAttributes, FieldAttributes attributes) {
564 check_name ("fieldName", fieldName);
565 if (type == typeof (void))
566 throw new ArgumentException ("type", "Bad field type in defining field.");
567 check_not_created ();
569 FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomAttributes, optionalCustomAttributes);
570 if (fields != null) {
571 if (fields.Length == num_fields) {
572 FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
573 System.Array.Copy (fields, new_fields, num_fields);
576 fields [num_fields] = res;
579 fields = new FieldBuilder [1];
582 create_internal_class (this);
587 public PropertyBuilder DefineProperty( string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
588 check_name ("name", name);
589 if (parameterTypes != null)
590 foreach (Type param in parameterTypes)
592 throw new ArgumentNullException ("parameterTypes");
593 check_not_created ();
595 PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, parameterTypes);
597 if (properties != null) {
598 PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
599 System.Array.Copy (properties, new_properties, properties.Length);
600 new_properties [properties.Length] = res;
601 properties = new_properties;
603 properties = new PropertyBuilder [1];
604 properties [0] = res;
609 public ConstructorBuilder DefineTypeInitializer() {
610 return DefineConstructor (MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, null);
613 [MethodImplAttribute(MethodImplOptions.InternalCall)]
614 private extern Type create_runtime_class (TypeBuilder tb);
616 private bool is_nested_in (Type t) {
626 public Type CreateType() {
627 /* handle nesting_type */
631 // Fire TypeResolve events for fields whose type is an unfinished
633 if (fields != null) {
634 foreach (FieldBuilder fb in fields) {
637 Type ft = fb.FieldType;
638 if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
639 TypeBuilder tb = (TypeBuilder)ft;
640 if (!tb.is_created) {
641 AppDomain.CurrentDomain.DoTypeResolve (tb);
642 if (!tb.is_created) {
643 // FIXME: We should throw an exception here,
644 // but mcs expects that the type is created
645 // even if the exception is thrown
646 //throw new TypeLoadException ("Could not load type " + tb);
653 if (methods != null) {
654 for (int i = 0; i < num_methods; ++i)
655 ((MethodBuilder)(methods[i])).fixup ();
659 // On classes, define a default constructor if not provided
661 if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") &&
662 (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed))
663 DefineDefaultConstructor (MethodAttributes.Public);
666 foreach (ConstructorBuilder ctor in ctors)
670 created = create_runtime_class (this);
676 public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
679 return new ConstructorInfo [0];
680 ArrayList l = new ArrayList ();
682 MethodAttributes mattrs;
684 foreach (ConstructorBuilder c in ctors) {
686 mattrs = c.Attributes;
687 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
688 if ((bindingAttr & BindingFlags.Public) != 0)
691 if ((bindingAttr & BindingFlags.NonPublic) != 0)
697 if ((mattrs & MethodAttributes.Static) != 0) {
698 if ((bindingAttr & BindingFlags.Static) != 0)
701 if ((bindingAttr & BindingFlags.Instance) != 0)
708 ConstructorInfo[] result = new ConstructorInfo [l.Count];
713 public override Type GetElementType () {
715 return created.GetElementType ();
718 public override EventInfo GetEvent (string name, BindingFlags bindingAttr) {
720 return created.GetEvent (name, bindingAttr);
723 /* Needed to keep signature compatibility with MS.NET */
724 public override EventInfo[] GetEvents ()
726 return GetEvents (DefaultBindingFlags);
729 public override EventInfo[] GetEvents (BindingFlags bindingAttr) {
730 /* FIXME: mcs calls this
734 return new EventInfo [0];
736 return created.GetEvents (bindingAttr);
739 // This is only used from MonoGenericInst.initialize().
740 internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
743 return new EventInfo [0];
744 ArrayList l = new ArrayList ();
746 MethodAttributes mattrs;
749 foreach (EventBuilder eb in events) {
752 EventInfo c = get_event_info (eb);
754 accessor = c.GetAddMethod (true);
755 if (accessor == null)
756 accessor = c.GetRemoveMethod (true);
757 if (accessor == null)
759 mattrs = accessor.Attributes;
760 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
761 if ((bindingAttr & BindingFlags.Public) != 0)
764 if ((bindingAttr & BindingFlags.NonPublic) != 0)
770 if ((mattrs & MethodAttributes.Static) != 0) {
771 if ((bindingAttr & BindingFlags.Static) != 0)
774 if ((bindingAttr & BindingFlags.Instance) != 0)
781 EventInfo[] result = new EventInfo [l.Count];
786 public override FieldInfo GetField( string name, BindingFlags bindingAttr) {
791 FieldAttributes mattrs;
793 foreach (FieldInfo c in fields) {
799 mattrs = c.Attributes;
800 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
801 if ((bindingAttr & BindingFlags.Public) != 0)
804 if ((bindingAttr & BindingFlags.NonPublic) != 0)
810 if ((mattrs & FieldAttributes.Static) != 0) {
811 if ((bindingAttr & BindingFlags.Static) != 0)
814 if ((bindingAttr & BindingFlags.Instance) != 0)
824 public override FieldInfo[] GetFields (BindingFlags bindingAttr) {
826 return new FieldInfo [0];
827 ArrayList l = new ArrayList ();
829 FieldAttributes mattrs;
831 foreach (FieldInfo c in fields) {
835 mattrs = c.Attributes;
836 if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
837 if ((bindingAttr & BindingFlags.Public) != 0)
840 if ((bindingAttr & BindingFlags.NonPublic) != 0)
846 if ((mattrs & FieldAttributes.Static) != 0) {
847 if ((bindingAttr & BindingFlags.Static) != 0)
850 if ((bindingAttr & BindingFlags.Instance) != 0)
857 FieldInfo[] result = new FieldInfo [l.Count];
862 public override Type GetInterface (string name, bool ignoreCase) {
864 return created.GetInterface (name, ignoreCase);
867 public override Type[] GetInterfaces () {
868 if (interfaces != null) {
869 Type[] ret = new Type [interfaces.Length];
870 interfaces.CopyTo (ret, 0);
873 return Type.EmptyTypes;
877 public override MemberInfo[] GetMember (string name, MemberTypes type,
878 BindingFlags bindingAttr) {
880 return created.GetMember (name, type, bindingAttr);
883 public override MemberInfo[] GetMembers (BindingFlags bindingAttr) {
885 return created.GetMembers (bindingAttr);
888 private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type) {
889 MethodInfo[] candidates;
890 if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
891 MethodInfo[] parent_methods = parent.GetMethods (bindingAttr);
893 candidates = parent_methods;
895 candidates = new MethodInfo [methods.Length + parent_methods.Length];
896 parent_methods.CopyTo (candidates, 0);
897 methods.CopyTo (candidates, parent_methods.Length);
901 candidates = methods;
903 if (candidates == null)
904 return new MethodInfo [0];
906 ArrayList l = new ArrayList ();
908 MethodAttributes mattrs;
910 foreach (MethodInfo c in candidates) {
914 if (String.Compare (c.Name, name, ignoreCase) != 0)
918 mattrs = c.Attributes;
919 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
920 if ((bindingAttr & BindingFlags.Public) != 0)
923 if ((bindingAttr & BindingFlags.NonPublic) != 0)
929 if ((mattrs & MethodAttributes.Static) != 0) {
930 if ((bindingAttr & BindingFlags.Static) != 0)
933 if ((bindingAttr & BindingFlags.Instance) != 0)
941 MethodInfo[] result = new MethodInfo [l.Count];
946 public override MethodInfo[] GetMethods (BindingFlags bindingAttr) {
947 return GetMethodsByName (null, bindingAttr, false, this);
950 protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
952 CallingConventions callConvention,
953 Type[] types, ParameterModifier[] modifiers)
957 bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
958 MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
959 MethodInfo found = null;
961 int typesLen = (types != null) ? types.Length : 0;
964 foreach (MethodInfo m in methods) {
965 // Under MS.NET, Standard|HasThis matches Standard...
966 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
975 if (count == 1 && typesLen == 0)
978 match = new MethodBase [count];
983 foreach (MethodInfo m in methods) {
984 if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
991 return (MethodInfo) Binder.FindMostDerivedMatch (match);
994 binder = Binder.DefaultBinder;
996 return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
999 public override Type GetNestedType( string name, BindingFlags bindingAttr) {
1001 return created.GetNestedType (name, bindingAttr);
1004 public override Type[] GetNestedTypes (BindingFlags bindingAttr) {
1006 ArrayList result = new ArrayList ();
1008 if (subtypes == null)
1009 return Type.EmptyTypes;
1010 foreach (TypeBuilder t in subtypes) {
1012 if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
1013 if ((bindingAttr & BindingFlags.Public) != 0)
1016 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1023 Type[] r = new Type [result.Count];
1028 public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) {
1029 if (properties == null)
1030 return new PropertyInfo [0];
1031 ArrayList l = new ArrayList ();
1033 MethodAttributes mattrs;
1034 MethodInfo accessor;
1036 foreach (PropertyInfo c in properties) {
1038 accessor = c.GetGetMethod (true);
1039 if (accessor == null)
1040 accessor = c.GetSetMethod (true);
1041 if (accessor == null)
1043 mattrs = accessor.Attributes;
1044 if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
1045 if ((bindingAttr & BindingFlags.Public) != 0)
1048 if ((bindingAttr & BindingFlags.NonPublic) != 0)
1054 if ((mattrs & MethodAttributes.Static) != 0) {
1055 if ((bindingAttr & BindingFlags.Static) != 0)
1058 if ((bindingAttr & BindingFlags.Instance) != 0)
1065 PropertyInfo[] result = new PropertyInfo [l.Count];
1070 protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
1071 throw not_supported ();
1074 protected override bool HasElementTypeImpl () {
1076 return created.HasElementType;
1079 public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
1081 return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
1084 protected override bool IsArrayImpl ()
1086 return Type.IsArrayImpl (this);
1089 protected override bool IsByRefImpl () {
1093 protected override bool IsCOMObjectImpl () {
1096 protected override bool IsPointerImpl () {
1100 protected override bool IsPrimitiveImpl () {
1104 protected override bool IsValueTypeImpl () {
1105 return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
1106 this != pmodule.assemblyb.corlib_value_type &&
1107 this != pmodule.assemblyb.corlib_enum_type);
1110 public override RuntimeTypeHandle TypeHandle {
1113 return created.TypeHandle;
1117 public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
1118 if (customBuilder == null)
1119 throw new ArgumentNullException ("customBuilder");
1121 string attrname = customBuilder.Ctor.ReflectedType.FullName;
1122 if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
1123 byte[] data = customBuilder.Data;
1124 int layout_kind; /* the (stupid) ctor takes a short or an int ... */
1125 layout_kind = (int)data [2];
1126 layout_kind |= ((int)data [3]) << 8;
1127 attrs &= ~TypeAttributes.LayoutMask;
1128 switch ((LayoutKind)layout_kind) {
1129 case LayoutKind.Auto:
1130 attrs |= TypeAttributes.AutoLayout;
1132 case LayoutKind.Explicit:
1133 attrs |= TypeAttributes.ExplicitLayout;
1135 case LayoutKind.Sequential:
1136 attrs |= TypeAttributes.SequentialLayout;
1139 // we should ignore it since it can be any value anyway...
1140 throw new Exception ("Error in customattr");
1142 string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
1144 if (first_type_name == "System.Int16")
1146 int nnamed = (int)data [pos++];
1147 nnamed |= ((int)data [pos++]) << 8;
1148 for (int i = 0; i < nnamed; ++i) {
1149 byte named_type = data [pos++];
1150 byte type = data [pos++];
1155 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1156 string named_typename = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1158 // FIXME: Check that 'named_type' and 'named_typename' match, etc.
1159 // See related code/FIXME in mono/mono/metadata/reflection.c
1162 len = CustomAttributeBuilder.decode_len (data, pos, out pos);
1163 named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
1165 /* all the fields are integers in StructLayout */
1166 int value = (int)data [pos++];
1167 value |= ((int)data [pos++]) << 8;
1168 value |= ((int)data [pos++]) << 16;
1169 value |= ((int)data [pos++]) << 24;
1170 switch (named_name) {
1172 switch ((CharSet)value) {
1176 case CharSet.Unicode:
1177 attrs |= TypeAttributes.UnicodeClass;
1180 attrs |= TypeAttributes.AutoClass;
1183 break; // error out...
1187 packing_size = (PackingSize)value;
1193 break; // error out...
1197 } else if (attrname == "System.SerializableAttribute") {
1198 attrs |= TypeAttributes.Serializable;
1201 if (cattrs != null) {
1202 CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
1203 cattrs.CopyTo (new_array, 0);
1204 new_array [cattrs.Length] = customBuilder;
1207 cattrs = new CustomAttributeBuilder [1];
1208 cattrs [0] = customBuilder;
1211 public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
1212 SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
1215 public EventBuilder DefineEvent( string name, EventAttributes attributes, Type eventtype) {
1216 check_name ("name", name);
1217 if (eventtype == null)
1218 throw new ArgumentNullException ("eventtype");
1219 check_not_created ();
1221 EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
1222 if (events != null) {
1223 EventBuilder[] new_events = new EventBuilder [events.Length+1];
1224 System.Array.Copy (events, new_events, events.Length);
1225 new_events [events.Length] = res;
1226 events = new_events;
1228 events = new EventBuilder [1];
1234 public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
1236 throw new ArgumentNullException ("data");
1237 if ((data.Length == 0) || (data.Length > 0x3f0000))
1238 throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");
1240 FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
1241 res.SetRVAData (data);
1246 static int UnmanagedDataCount = 0;
1248 public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
1249 check_name ("name", name);
1250 if ((size <= 0) || (size > 0x3f0000))
1251 throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
1252 check_not_created ();
1254 string s = "$ArrayType$"+UnmanagedDataCount.ToString();
1255 UnmanagedDataCount++;
1256 TypeBuilder datablobtype = DefineNestedType (s,
1257 TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
1258 pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
1259 datablobtype.CreateType ();
1260 return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
1263 public TypeToken TypeToken {
1265 return new TypeToken (0x02000000 | table_idx);
1268 public void SetParent (Type parentType) {
1269 if (parentType == null)
1270 throw new ArgumentNullException ("parentType");
1271 check_not_created ();
1273 parent = parentType;
1274 // will just set the parent-related bits if called a second time
1275 setup_internal_class (this);
1277 internal int get_next_table_index (object obj, int table, bool inc) {
1278 return pmodule.get_next_table_index (obj, table, inc);
1281 public override InterfaceMapping GetInterfaceMap (Type interfaceType)
1283 if (created == null)
1284 throw new NotSupportedException ("This method is not implemented for incomplete types.");
1286 return created.GetInterfaceMap (interfaceType);
1289 internal bool is_created {
1291 return created != null;
1295 private Exception not_supported ()
1297 return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
1300 private void check_not_created ()
1303 throw new InvalidOperationException ("Unable to change after type has been created.");
1306 private void check_created ()
1309 throw not_supported ();
1312 private void check_name (string argName, string name)
1315 throw new ArgumentNullException (argName);
1317 throw new ArgumentException (argName, "Empty name is not legal.");
1318 if (name.IndexOf ((char)0) != -1)
1319 throw new ArgumentException (argName, "Illegal name.");
1322 public override String ToString ()
1328 public override bool IsAssignableFrom (Type c)
1330 return base.IsAssignableFrom (c);
1334 public override bool IsSubclassOf (Type c)
1336 return base.IsSubclassOf (c);
1339 #if NET_2_0 || BOOTSTRAP_NET_2_0
1340 public bool IsCreated () {
1344 public override Type[] GetGenericArguments ()
1346 if (generic_params != null)
1347 return generic_params;
1349 throw new InvalidOperationException ();
1352 public override Type GetGenericTypeDefinition ()
1354 create_generic_class ();
1356 return base.GetGenericTypeDefinition ();
1359 public override bool HasGenericArguments {
1361 throw new NotImplementedException ();
1365 public override bool ContainsGenericParameters {
1367 return generic_params != null;
1371 public extern override bool IsGenericParameter {
1372 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1376 public override int GenericParameterPosition {
1378 throw new NotImplementedException ();
1382 public override MethodInfo DeclaringMethod {
1384 throw new NotImplementedException ();
1388 public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
1390 setup_generic_class ();
1392 generic_params = new GenericTypeParameterBuilder [names.Length];
1393 for (int i = 0; i < names.Length; i++)
1394 generic_params [i] = new GenericTypeParameterBuilder (
1395 this, null, names [i], i);
1397 return generic_params;
1400 public MethodBuilder DefineGenericMethod (string name, MethodAttributes attributes)
1402 return DefineMethod (name, attributes, CallingConventions.Standard, null, null);