Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TypeBuilder.cs « System.Reflection.Emit « corlib « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d46282cf1ef54d73d805f0c40db0d450c89e5a7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
//
// System.Reflection.Emit/TypeBuilder.cs
//
// Author:
//   Paolo Molaro (lupus@ximian.com)
//
// (C) 2001 Ximian, Inc.  http://www.ximian.com
//

//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Collections;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.SymbolStore;

namespace System.Reflection.Emit {
#if NET_2_0
	[ComVisible (true)]
	[ComDefaultInterface (typeof (_TypeBuilder))]
#endif
	[ClassInterface (ClassInterfaceType.None)]
	public sealed class TypeBuilder : Type, _TypeBuilder {
	#region Sync with reflection.h
	private string tname;
	private string nspace;
	private Type parent;
	private Type nesting_type;
	private Type[] interfaces;
	private int num_methods;
	private MethodBuilder[] methods;
	private ConstructorBuilder[] ctors;
	private PropertyBuilder[] properties;
	private int num_fields;
	private FieldBuilder[] fields;
	private EventBuilder[] events;
	private CustomAttributeBuilder[] cattrs;
	internal TypeBuilder[] subtypes;
	internal TypeAttributes attrs;
	private int table_idx;
	private ModuleBuilder pmodule;
	private int class_size;
	private PackingSize packing_size;
	private IntPtr generic_container;
#if NET_2_0 || BOOTSTRAP_NET_2_0
	private	GenericTypeParameterBuilder[] generic_params;
#else
        private Object generic_params; /* so offsets don't change */
#endif
	private RefEmitPermissionSet[] permissions;	
	private Type created;
	#endregion
	string fullname;

	public const int UnspecifiedTypeSize = 0;

		protected override TypeAttributes GetAttributeFlagsImpl () {
			return attrs;
		}
		
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		private extern void setup_internal_class (TypeBuilder tb);
		
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		private extern void create_internal_class (TypeBuilder tb);
		
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		private extern void setup_generic_class ();

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		private extern void create_generic_class ();

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		private extern EventInfo get_event_info (EventBuilder eb);

		internal TypeBuilder (ModuleBuilder mb, TypeAttributes attr) {
			this.parent = null;
			this.attrs = attr;
			this.class_size = UnspecifiedTypeSize;
			this.table_idx = 1;
			fullname = this.tname = "<Module>";
			this.nspace = "";
			pmodule = mb;
			setup_internal_class (this);
		}

		internal TypeBuilder (ModuleBuilder mb, string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packing_size, int type_size, Type nesting_type) {
			int sep_index;
			this.parent = parent;
			this.attrs = attr;
			this.class_size = type_size;
			this.packing_size = packing_size;
			this.nesting_type = nesting_type;
			sep_index = name.LastIndexOf('.');
			if (sep_index != -1) {
				this.tname = name.Substring (sep_index + 1);
				this.nspace = name.Substring (0, sep_index);
			} else {
				this.tname = name;
				this.nspace = "";
			}
			if (interfaces != null) {
				this.interfaces = new Type[interfaces.Length];
				System.Array.Copy (interfaces, this.interfaces, interfaces.Length);
			}
			pmodule = mb;
			// skip .<Module> ?
			table_idx = mb.get_next_table_index (this, 0x02, true);
			setup_internal_class (this);
			fullname = GetFullName ();
		}

		public override Assembly Assembly {
			get {return pmodule.Assembly;}
		}

		public override string AssemblyQualifiedName {
			get {
				return fullname + ", " + Assembly.GetName().FullName;
			}
		}
		public override Type BaseType {
			get {
				return parent;
			}
		}
		public override Type DeclaringType {get {return nesting_type;}}

/*		public override bool IsSubclassOf (Type c)
		{
			Type t;
			if (c == null)
				return false;
			if (c == this)
				return false;
			t = parent;
			while (t != null) {
				if (c == t)
					return true;
				t = t.BaseType;
			}
			return false;
		}*/

		[MonoTODO]
		public override Type UnderlyingSystemType {
			get {

				// Return this as requested by Zoltan.
				
				return this;

#if false
				// Dont know what to do with the rest, should be killed:
				// See bug: 75008.
				//
				////// This should return the type itself for non-enum types but 
				////// that breaks mcs.
				if (fields != null) {
					foreach (FieldBuilder f in fields) {
						if ((f != null) && (f.Attributes & FieldAttributes.Static) == 0)
							return f.FieldType;
					}
				}
				throw new InvalidOperationException ("Underlying type information on enumeration is not specified.");
#endif
			}
		}

		string GetFullName () {
			if (nesting_type != null)
				return String.Concat (nesting_type.FullName, "+", tname);
			if ((nspace != null) && (nspace.Length > 0))
				return String.Concat (nspace, ".", tname);
			return tname;
		}
	
		public override string FullName {
			get {
				return fullname;
			}
		}
	
		public override Guid GUID {
			get {
				check_created ();
				return created.GUID;
			}
		}

		public override Module Module {
			get {return pmodule;}
		}
		public override string Name {
			get {return tname;}
		}
		public override string Namespace {
			get {return nspace;}
		}
		public PackingSize PackingSize {
			get {return packing_size;}
		}
		public int Size {
			get { return class_size; }
		}
		public override Type ReflectedType {get {return nesting_type;}}

		public void AddDeclarativeSecurity( SecurityAction action, PermissionSet pset) {
			if (pset == null)
				throw new ArgumentNullException ("pset");
			if ((action == SecurityAction.RequestMinimum) ||
				(action == SecurityAction.RequestOptional) ||
				(action == SecurityAction.RequestRefuse))
				throw new ArgumentOutOfRangeException ("Request* values are not permitted", "action");

			check_not_created ();

			if (permissions != null) {
				/* Check duplicate actions */
				foreach (RefEmitPermissionSet set in permissions)
					if (set.action == action)
						throw new InvalidOperationException ("Multiple permission sets specified with the same SecurityAction.");

				RefEmitPermissionSet[] new_array = new RefEmitPermissionSet [permissions.Length + 1];
				permissions.CopyTo (new_array, 0);
				permissions = new_array;
			}
			else
				permissions = new RefEmitPermissionSet [1];

			permissions [permissions.Length - 1] = new RefEmitPermissionSet (action, pset.ToXml ().ToString ());
			attrs |= TypeAttributes.HasSecurity;
		}

#if NET_2_0
		[ComVisible (true)]
#endif
		public void AddInterfaceImplementation( Type interfaceType) {
			if (interfaceType == null)
				throw new ArgumentNullException ("interfaceType");
			check_not_created ();

			if (interfaces != null) {
				// Check for duplicates
				foreach (Type t in interfaces)
					if (t == interfaceType)
						return;

				Type[] ifnew = new Type [interfaces.Length + 1];
				interfaces.CopyTo (ifnew, 0);
				ifnew [interfaces.Length] = interfaceType;
				interfaces = ifnew;
			} else {
				interfaces = new Type [1];
				interfaces [0] = interfaceType;
			}
		}

		[MonoTODO]
		protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder,
								       CallingConventions callConvention, Type[] types,
								       ParameterModifier[] modifiers)
		{
			check_created ();
			
			if (ctors == null)
				return null;

			ConstructorBuilder found = null;
			int count = 0;
			
			foreach (ConstructorBuilder cb in ctors){
				if (callConvention != CallingConventions.Any && cb.CallingConvention != callConvention)
					continue;
				found = cb;
				count++;
			}

			if (count == 0)
				return null;
			if (types == null){
				if (count > 1)
					throw new AmbiguousMatchException ();
				return found;
			}
			MethodBase[] match = new MethodBase [count];
			if (count == 1)
				match [0] = found;
			else {
				count = 0;
				foreach (ConstructorInfo m in ctors) {
					if (callConvention != CallingConventions.Any && m.CallingConvention != callConvention)
						continue;
					match [count++] = m;
				}
			}
			if (binder == null)
				binder = Binder.DefaultBinder;
			return (ConstructorInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
		}

		public override bool IsDefined( Type attributeType, bool inherit)
		{
			/*
			 * MS throws NotSupported here, but we can't because some corlib
			 * classes make calls to IsDefined.
			 */
			return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
		}
		
		public override object[] GetCustomAttributes(bool inherit)
		{
			check_created ();

			return created.GetCustomAttributes (inherit);
		}
		
		public override object[] GetCustomAttributes(Type attributeType, bool inherit)
		{
			check_created ();

			return created.GetCustomAttributes (attributeType, inherit);
		}

		public TypeBuilder DefineNestedType (string name) {
			return DefineNestedType (name, TypeAttributes.NestedPrivate, pmodule.assemblyb.corlib_object_type, null);
		}

		public TypeBuilder DefineNestedType (string name, TypeAttributes attr) {
			return DefineNestedType (name, attr, pmodule.assemblyb.corlib_object_type, null);
		}

		public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent) {
			return DefineNestedType (name, attr, parent, null);
		}

		private TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces,
						      PackingSize packsize, int typesize)
		{
			check_name ("name", name);
			// Visibility must be NestedXXX
			/* This breaks mcs
			if (((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||
				((attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
				throw new ArgumentException ("attr", "Bad type flags for nested type.");
			*/
			if (interfaces != null)
				foreach (Type iface in interfaces)
					if (iface == null)
						throw new ArgumentNullException ("interfaces");

			TypeBuilder res = new TypeBuilder (pmodule, name, attr, parent, interfaces, packsize, typesize, this);
			res.fullname = res.GetFullName ();
			pmodule.RegisterTypeName (res, res.fullname);
			if (subtypes != null) {
				TypeBuilder[] new_types = new TypeBuilder [subtypes.Length + 1];
				System.Array.Copy (subtypes, new_types, subtypes.Length);
				new_types [subtypes.Length] = res;
				subtypes = new_types;
			} else {
				subtypes = new TypeBuilder [1];
				subtypes [0] = res;
			}
			return res;
		}

#if NET_2_0
		[ComVisible (true)]
#endif
		public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, Type[] interfaces) {
			return DefineNestedType (name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
		}

		public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, int typesize) {
			return DefineNestedType (name, attr, parent, null, PackingSize.Unspecified, typesize);
		}

		public TypeBuilder DefineNestedType (string name, TypeAttributes attr, Type parent, PackingSize packsize) {
			return DefineNestedType (name, attr, parent, null, packsize, UnspecifiedTypeSize);
		}

#if NET_2_0
		[ComVisible (true)]
#endif
		public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) {
			return DefineConstructor (attributes, callingConvention, parameterTypes, null, null);
		}

#if NET_2_0
		[ComVisible (true)]
#endif
#if NET_2_0 || BOOTSTRAP_NET_2_0
		public
#else
		internal
#endif
		ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
		{
			check_not_created ();
			ConstructorBuilder cb = new ConstructorBuilder (this, attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
			if (ctors != null) {
				ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
				System.Array.Copy (ctors, new_ctors, ctors.Length);
				new_ctors [ctors.Length] = cb;
				ctors = new_ctors;
			} else {
				ctors = new ConstructorBuilder [1];
				ctors [0] = cb;
			}
			return cb;
		}

#if NET_2_0
		[ComVisible (true)]
#endif
		public ConstructorBuilder DefineDefaultConstructor (MethodAttributes attributes)
		{
			Type parent_type;

			if (parent != null)
				parent_type = parent;
			else
				parent_type = pmodule.assemblyb.corlib_object_type;

			ConstructorInfo parent_constructor =
				parent_type.GetConstructor (
					BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
					null, Type.EmptyTypes, null);
			if (parent_constructor == null) {
				throw new NotSupportedException ("Parent does"
					+ " not have a default constructor."
					+ " The default constructor must be"
					+ " explicitly defined.");
			}

			ConstructorBuilder cb = DefineConstructor (attributes, 
				CallingConventions.Standard, new Type[0]);
			ILGenerator ig = cb.GetILGenerator ();
			ig.Emit (OpCodes.Ldarg_0);
			ig.Emit (OpCodes.Call, parent_constructor);
			ig.Emit (OpCodes.Ret);
			return cb;
		}

		private void append_method (MethodBuilder mb) {
			if (methods != null) {
				if (methods.Length == num_methods) {
					MethodBuilder[] new_methods = new MethodBuilder [methods.Length * 2];
					System.Array.Copy (methods, new_methods, num_methods);
					methods = new_methods;
				}
			} else {
				methods = new MethodBuilder [1];
			}
			methods [num_methods] = mb;
			num_methods ++;
		}

		public MethodBuilder DefineMethod( string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) {
			return DefineMethod (name, attributes, CallingConventions.Standard, returnType, parameterTypes);
		}

		public MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) {
			return DefineMethod (name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
		}

#if NET_2_0 || BOOTSTRAP_NET_2_0
		public
#else
		internal
#endif
		MethodBuilder DefineMethod( string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
			check_name ("name", name);
			check_not_created ();
			if (IsInterface && (
				!((attributes & MethodAttributes.Abstract) != 0) || 
				!((attributes & MethodAttributes.Virtual) != 0)))
				throw new ArgumentException ("attributes", "Interface method must be abstract and virtual.");

			if (returnType == null)
				returnType = pmodule.assemblyb.corlib_void_type;
			MethodBuilder res = new MethodBuilder (this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
			append_method (res);
			return res;
		}

		public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
			return DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet);
		}

#if NET_2_0 || BOOTSTRAP_NET_2_0
		public
#else
		internal
#endif
		MethodBuilder DefinePInvokeMethod (
						string name, 
						string dllName, 
						string entryName, MethodAttributes attributes, 
						CallingConventions callingConvention, 
						Type returnType, 
						Type[] returnTypeRequiredCustomModifiers, 
						Type[] returnTypeOptionalCustomModifiers, 
						Type[] parameterTypes, 
						Type[][] parameterTypeRequiredCustomModifiers, 
						Type[][] parameterTypeOptionalCustomModifiers, 
						CallingConvention nativeCallConv, 
						CharSet nativeCharSet) {
			check_name ("name", name);
			check_name ("dllName", dllName);
			check_name ("entryName", entryName);
			if ((attributes & MethodAttributes.Abstract) != 0)
				throw new ArgumentException ("attributes", "PInvoke methods must be static and native and cannot be abstract.");
			if (IsInterface)
				throw new ArgumentException ("PInvoke methods cannot exist on interfaces.");		
			check_not_created ();

			MethodBuilder res 
				= new MethodBuilder (
						this, 
						name, 
						attributes, 
						callingConvention,
						returnType, 
						returnTypeRequiredCustomModifiers, 
						returnTypeOptionalCustomModifiers, 
						parameterTypes, 
						parameterTypeRequiredCustomModifiers, 
						parameterTypeOptionalCustomModifiers,
						dllName, 
						entryName, 
						nativeCallConv, 
						nativeCharSet);
			append_method (res);
			return res;
		}

		public MethodBuilder DefinePInvokeMethod (string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) {
			return DefinePInvokeMethod (name, dllName, name, attributes, callingConvention, returnType, parameterTypes,
				nativeCallConv, nativeCharSet);
		}

#if NET_2_0 || BOOTSTRAP_NET_2_0
		public MethodBuilder DefineMethod (string name, MethodAttributes attributes) {
			return DefineMethod (name, attributes, CallingConventions.Standard);
		}

		public MethodBuilder DefineMethod (string name, MethodAttributes attributes, CallingConventions callConv) {
			return DefineMethod (name, attributes, callConv, null, null);
		}
#endif

		public void DefineMethodOverride( MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) {
			if (methodInfoBody == null)
				throw new ArgumentNullException ("methodInfoBody");
			if (methodInfoDeclaration == null)
				throw new ArgumentNullException ("methodInfoDeclaration");
			check_not_created ();

			if (methodInfoBody is MethodBuilder) {
				MethodBuilder mb = (MethodBuilder)methodInfoBody;
				mb.set_override (methodInfoDeclaration);
			}
		}

		public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) {
			return DefineField (fieldName, type, null, null, attributes);
		}

#if NET_2_0 || BOOTSTRAP_NET_2_0
		public
#else
		internal
#endif
	    FieldBuilder DefineField (string fieldName, Type type, Type[] requiredCustomAttributes, Type[] optionalCustomAttributes, FieldAttributes attributes) {
			check_name ("fieldName", fieldName);
			if (type == typeof (void))
				throw new ArgumentException ("type",  "Bad field type in defining field.");
			check_not_created ();

			FieldBuilder res = new FieldBuilder (this, fieldName, type, attributes, requiredCustomAttributes, optionalCustomAttributes);
			if (fields != null) {
				if (fields.Length == num_fields) {
					FieldBuilder[] new_fields = new FieldBuilder [fields.Length * 2];
					System.Array.Copy (fields, new_fields, num_fields);
					fields = new_fields;
				}
				fields [num_fields] = res;
				num_fields ++;
			} else {
				fields = new FieldBuilder [1];
				fields [0] = res;
				num_fields ++;
				create_internal_class (this);
			}
			return res;
		}

		public PropertyBuilder DefineProperty( string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) {
			return DefineProperty (name, attributes, returnType, null, null, parameterTypes, null, null);
		}

#if NET_2_0
		public 
#else
		internal
#endif
		PropertyBuilder DefineProperty (string name, PropertyAttributes attributes, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) {
			check_name ("name", name);
			if (parameterTypes != null)
				foreach (Type param in parameterTypes)
					if (param == null)
						throw new ArgumentNullException ("parameterTypes");
			check_not_created ();

			PropertyBuilder res = new PropertyBuilder (this, name, attributes, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);

			if (properties != null) {
				PropertyBuilder[] new_properties = new PropertyBuilder [properties.Length+1];
				System.Array.Copy (properties, new_properties, properties.Length);
				new_properties [properties.Length] = res;
				properties = new_properties;
			} else {
				properties = new PropertyBuilder [1];
				properties [0] = res;
			}
			return res;
		}

#if NET_2_0
		[ComVisible (true)]
#endif
		public ConstructorBuilder DefineTypeInitializer() {
			return DefineConstructor (MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, null);
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		private extern Type create_runtime_class (TypeBuilder tb);

		private bool is_nested_in (Type t) {
			while (t != null) {
				if (t == this)
					return true;
				else
					t = t.DeclaringType;
			}
			return false;
		}
		
		public Type CreateType() {
			/* handle nesting_type */
			if (created != null)
				return created;

			create_generic_class ();

			// Fire TypeResolve events for fields whose type is an unfinished
			// value type.
			if (fields != null) {
				foreach (FieldBuilder fb in fields) {
					if (fb == null)
						continue;
					Type ft = fb.FieldType;
					if (!fb.IsStatic && (ft is TypeBuilder) && ft.IsValueType && (ft != this) && is_nested_in (ft)) {
						TypeBuilder tb = (TypeBuilder)ft;
						if (!tb.is_created) {
							AppDomain.CurrentDomain.DoTypeResolve (tb);
							if (!tb.is_created) {
								// FIXME: We should throw an exception here,
								// but mcs expects that the type is created
								// even if the exception is thrown
								//throw new TypeLoadException ("Could not load type " + tb);
							}
						}
					}
				}
			}

			if ((parent != null) && parent.IsSealed)
				throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");

			if (methods != null) {
				for (int i = 0; i < num_methods; ++i)
					((MethodBuilder)(methods[i])).fixup ();
			}

			//
			// On classes, define a default constructor if not provided
			//
			if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") && 
				(GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed))
				DefineDefaultConstructor (MethodAttributes.Public);

			if (ctors != null){
				foreach (ConstructorBuilder ctor in ctors) 
					ctor.fixup ();
			}
			
			created = create_runtime_class (this);
			if (created != null)
				return created;
			return this;
		}

		internal void GenerateDebugInfo (ISymbolWriter symbolWriter)
		{
			symbolWriter.OpenNamespace (this.Namespace);

			if (methods != null) {
				for (int i = 0; i < num_methods; ++i) {
					MethodBuilder metb = (MethodBuilder) methods[i]; 
					metb.GenerateDebugInfo (symbolWriter);
				}
			}

			if (ctors != null) {
				foreach (ConstructorBuilder ctor in ctors)
					ctor.GenerateDebugInfo (symbolWriter);
			}
			
			symbolWriter.CloseNamespace ();
		}

#if NET_2_0
		[ComVisible (true)]
#endif
		public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
		{
			if (ctors == null)
				return new ConstructorInfo [0];
			ArrayList l = new ArrayList ();
			bool match;
			MethodAttributes mattrs;
			
			foreach (ConstructorBuilder c in ctors) {
				match = false;
				mattrs = c.Attributes;
				if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
					if ((bindingAttr & BindingFlags.Public) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.NonPublic) != 0)
						match = true;
				}
				if (!match)
					continue;
				match = false;
				if ((mattrs & MethodAttributes.Static) != 0) {
					if ((bindingAttr & BindingFlags.Static) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.Instance) != 0)
						match = true;
				}
				if (!match)
					continue;
				l.Add (c);
			}
			ConstructorInfo[] result = new ConstructorInfo [l.Count];
			l.CopyTo (result);
			return result;
		}

		public override Type GetElementType () { 
			check_created ();
			return created.GetElementType ();
		}

		public override EventInfo GetEvent (string name, BindingFlags bindingAttr) {
			check_created ();
			return created.GetEvent (name, bindingAttr);
		}

		/* Needed to keep signature compatibility with MS.NET */
		public override EventInfo[] GetEvents ()
		{
			return GetEvents (DefaultBindingFlags);
		}

		public override EventInfo[] GetEvents (BindingFlags bindingAttr) {
			/* FIXME: mcs calls this
			   check_created ();
			*/
			if (!is_created)
				return new EventInfo [0];
			else
				return created.GetEvents (bindingAttr);
		}

		// This is only used from MonoGenericInst.initialize().
		internal EventInfo[] GetEvents_internal (BindingFlags bindingAttr)
		{
			if (events == null)
				return new EventInfo [0];
			ArrayList l = new ArrayList ();
			bool match;
			MethodAttributes mattrs;
			MethodInfo accessor;

			foreach (EventBuilder eb in events) {
				if (eb == null)
					continue;
				EventInfo c = get_event_info (eb);
				match = false;
				accessor = c.GetAddMethod (true);
				if (accessor == null)
					accessor = c.GetRemoveMethod (true);
				if (accessor == null)
					continue;
				mattrs = accessor.Attributes;
				if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
					if ((bindingAttr & BindingFlags.Public) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.NonPublic) != 0)
						match = true;
				}
				if (!match)
					continue;
				match = false;
				if ((mattrs & MethodAttributes.Static) != 0) {
					if ((bindingAttr & BindingFlags.Static) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.Instance) != 0)
						match = true;
				}
				if (!match)
					continue;
				l.Add (c);
			}
			EventInfo[] result = new EventInfo [l.Count];
			l.CopyTo (result);
			return result;
		}

		public override FieldInfo GetField( string name, BindingFlags bindingAttr) {
			if (fields == null)
				return null;

			bool match;
			FieldAttributes mattrs;
			
			foreach (FieldInfo c in fields) {
				if (c == null)
					continue;
				if (c.Name != name)
					continue;
				match = false;
				mattrs = c.Attributes;
				if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
					if ((bindingAttr & BindingFlags.Public) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.NonPublic) != 0)
						match = true;
				}
				if (!match)
					continue;
				match = false;
				if ((mattrs & FieldAttributes.Static) != 0) {
					if ((bindingAttr & BindingFlags.Static) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.Instance) != 0)
						match = true;
				}
				if (!match)
					continue;
				return c;
			}
			return null;
		}

		public override FieldInfo[] GetFields (BindingFlags bindingAttr) {
			if (fields == null)
				return new FieldInfo [0];
			ArrayList l = new ArrayList ();
			bool match;
			FieldAttributes mattrs;
			
			foreach (FieldInfo c in fields) {
				if (c == null)
					continue;
				match = false;
				mattrs = c.Attributes;
				if ((mattrs & FieldAttributes.FieldAccessMask) == FieldAttributes.Public) {
					if ((bindingAttr & BindingFlags.Public) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.NonPublic) != 0)
						match = true;
				}
				if (!match)
					continue;
				match = false;
				if ((mattrs & FieldAttributes.Static) != 0) {
					if ((bindingAttr & BindingFlags.Static) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.Instance) != 0)
						match = true;
				}
				if (!match)
					continue;
				l.Add (c);
			}
			FieldInfo[] result = new FieldInfo [l.Count];
			l.CopyTo (result);
			return result;
		}

		public override Type GetInterface (string name, bool ignoreCase) {
			check_created ();
			return created.GetInterface (name, ignoreCase);
		}
		
		public override Type[] GetInterfaces () {
			if (interfaces != null) {
				Type[] ret = new Type [interfaces.Length];
				interfaces.CopyTo (ret, 0);
				return ret;
			} else {
				return Type.EmptyTypes;
			}
		}

		public override MemberInfo[] GetMember (string name, MemberTypes type,
												BindingFlags bindingAttr) {
			check_created ();
			return created.GetMember (name, type, bindingAttr);
		}

		public override MemberInfo[] GetMembers (BindingFlags bindingAttr) {
			check_created ();
			return created.GetMembers (bindingAttr);
		}

		private MethodInfo[] GetMethodsByName (string name, BindingFlags bindingAttr, bool ignoreCase, Type reflected_type) {
			MethodInfo[] candidates;
			if (((bindingAttr & BindingFlags.DeclaredOnly) == 0) && (parent != null)) {
				MethodInfo[] parent_methods = parent.GetMethods (bindingAttr);
				if (methods == null)
					candidates = parent_methods;
				else {
					candidates = new MethodInfo [methods.Length + parent_methods.Length];
					parent_methods.CopyTo (candidates, 0);
					methods.CopyTo (candidates, parent_methods.Length);
				}
			}
			else
				candidates = methods;

			if (candidates == null)
				return new MethodInfo [0];

			ArrayList l = new ArrayList ();
			bool match;
			MethodAttributes mattrs;

			foreach (MethodInfo c in candidates) {
				if (c == null)
					continue;
				if (name != null) {
					if (String.Compare (c.Name, name, ignoreCase) != 0)
						continue;
				}
				match = false;
				mattrs = c.Attributes;
				if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
					if ((bindingAttr & BindingFlags.Public) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.NonPublic) != 0)
						match = true;
				}
				if (!match)
					continue;
				match = false;
				if ((mattrs & MethodAttributes.Static) != 0) {
					if ((bindingAttr & BindingFlags.Static) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.Instance) != 0)
						match = true;
				}
				if (!match)
					continue;
				l.Add (c);
			}

			MethodInfo[] result = new MethodInfo [l.Count];
			l.CopyTo (result);
			return result;
		}

		public override MethodInfo[] GetMethods (BindingFlags bindingAttr) {
			return GetMethodsByName (null, bindingAttr, false, this);
		}

		protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr,
							     Binder binder,
							     CallingConventions callConvention,
							     Type[] types, ParameterModifier[] modifiers)
		{
			check_created ();

			bool ignoreCase = ((bindingAttr & BindingFlags.IgnoreCase) != 0);
			MethodInfo[] methods = GetMethodsByName (name, bindingAttr, ignoreCase, this);
			MethodInfo found = null;
			MethodBase[] match;
			int typesLen = (types != null) ? types.Length : 0;
			int count = 0;
			
			foreach (MethodInfo m in methods) {
				// Under MS.NET, Standard|HasThis matches Standard...
				if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
					continue;
				found = m;
				count++;
			}

			if (count == 0)
				return null;
			
			if (count == 1 && typesLen == 0) 
				return found;

			match = new MethodBase [count];
			if (count == 1)
				match [0] = found;
			else {
				count = 0;
				foreach (MethodInfo m in methods) {
					if (callConvention != CallingConventions.Any && ((m.CallingConvention & callConvention) != callConvention))
						continue;
					match [count++] = m;
				}
			}
			
			if (types == null) 
				return (MethodInfo) Binder.FindMostDerivedMatch (match);

			if (binder == null)
				binder = Binder.DefaultBinder;
			
			return (MethodInfo)binder.SelectMethod (bindingAttr, match, types, modifiers);
		}

		public override Type GetNestedType( string name, BindingFlags bindingAttr) {
			check_created ();
			return created.GetNestedType (name, bindingAttr);
		}

		public override Type[] GetNestedTypes (BindingFlags bindingAttr) {
			bool match;
			ArrayList result = new ArrayList ();

			if (subtypes == null)
				return Type.EmptyTypes;
			foreach (TypeBuilder t in subtypes) {
				match = false;
				if ((t.attrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) {
					if ((bindingAttr & BindingFlags.Public) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.NonPublic) != 0)
						match = true;
				}
				if (!match)
					continue;
				result.Add (t);
			}
			Type[] r = new Type [result.Count];
			result.CopyTo (r);
			return r;
		}

		public override PropertyInfo[] GetProperties( BindingFlags bindingAttr) {
			if (properties == null)
				return new PropertyInfo [0];
			ArrayList l = new ArrayList ();
			bool match;
			MethodAttributes mattrs;
			MethodInfo accessor;
			
			foreach (PropertyInfo c in properties) {
				match = false;
				accessor = c.GetGetMethod (true);
				if (accessor == null)
					accessor = c.GetSetMethod (true);
				if (accessor == null)
					continue;
				mattrs = accessor.Attributes;
				if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) {
					if ((bindingAttr & BindingFlags.Public) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.NonPublic) != 0)
						match = true;
				}
				if (!match)
					continue;
				match = false;
				if ((mattrs & MethodAttributes.Static) != 0) {
					if ((bindingAttr & BindingFlags.Static) != 0)
						match = true;
				} else {
					if ((bindingAttr & BindingFlags.Instance) != 0)
						match = true;
				}
				if (!match)
					continue;
				l.Add (c);
			}
			PropertyInfo[] result = new PropertyInfo [l.Count];
			l.CopyTo (result);
			return result;
		}
		
		protected override PropertyInfo GetPropertyImpl( string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
			throw not_supported ();
		}

		protected override bool HasElementTypeImpl () {
			check_created ();
			return created.HasElementType;
		}

		public override object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
			check_created ();
			return created.InvokeMember (name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
		}

		protected override bool IsArrayImpl ()
		{
			return Type.IsArrayImpl (this);
		}

		protected override bool IsByRefImpl () {
			// FIXME
			return false;
		}
		protected override bool IsCOMObjectImpl () {
			return false;
		}
		protected override bool IsPointerImpl () {
			// FIXME
			return false;
		}
		protected override bool IsPrimitiveImpl () {
			// FIXME
			return false;
		}
		protected override bool IsValueTypeImpl () {
			return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
				this != pmodule.assemblyb.corlib_value_type &&
				this != pmodule.assemblyb.corlib_enum_type);
		}
		
		public override RuntimeTypeHandle TypeHandle { 
			get { 
				check_created ();
				return created.TypeHandle;
			} 
		}

		public void SetCustomAttribute( CustomAttributeBuilder customBuilder) {
			if (customBuilder == null)
				throw new ArgumentNullException ("customBuilder");

			string attrname = customBuilder.Ctor.ReflectedType.FullName;
			if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") {
				byte[] data = customBuilder.Data;
				int layout_kind; /* the (stupid) ctor takes a short or an int ... */
				layout_kind = (int)data [2];
				layout_kind |= ((int)data [3]) << 8;
				attrs &= ~TypeAttributes.LayoutMask;
				switch ((LayoutKind)layout_kind) {
				case LayoutKind.Auto:
					attrs |= TypeAttributes.AutoLayout;
					break;
				case LayoutKind.Explicit:
					attrs |= TypeAttributes.ExplicitLayout;
					break;
				case LayoutKind.Sequential:
					attrs |= TypeAttributes.SequentialLayout;
					break;
				default:
					// we should ignore it since it can be any value anyway...
					throw new Exception ("Error in customattr");
				}
				string first_type_name = customBuilder.Ctor.GetParameters()[0].ParameterType.FullName;
				int pos = 6;
				if (first_type_name == "System.Int16")
					pos = 4;
				int nnamed = (int)data [pos++];
				nnamed |= ((int)data [pos++]) << 8;
				for (int i = 0; i < nnamed; ++i) {
					//byte named_type = data [pos++];
					pos ++;
					byte type = data [pos++];
					int len;
					string named_name;

					if (type == 0x55) {
						len = CustomAttributeBuilder.decode_len (data, pos, out pos);
						//string named_typename = 
						CustomAttributeBuilder.string_from_bytes (data, pos, len);
						pos += len;
						// FIXME: Check that 'named_type' and 'named_typename' match, etc.
						//        See related code/FIXME in mono/mono/metadata/reflection.c
					}

					len = CustomAttributeBuilder.decode_len (data, pos, out pos);
					named_name = CustomAttributeBuilder.string_from_bytes (data, pos, len);
					pos += len;
					/* all the fields are integers in StructLayout */
					int value = (int)data [pos++];
					value |= ((int)data [pos++]) << 8;
					value |= ((int)data [pos++]) << 16;
					value |= ((int)data [pos++]) << 24;
					switch (named_name) {
					case "CharSet":
						switch ((CharSet)value) {
						case CharSet.None:
						case CharSet.Ansi:
							attrs &= ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass);
							break;
						case CharSet.Unicode:
							attrs &= ~TypeAttributes.AutoClass;
							attrs |= TypeAttributes.UnicodeClass;
							break;
						case CharSet.Auto:
							attrs &= ~TypeAttributes.UnicodeClass;
							attrs |= TypeAttributes.AutoClass;
							break;
						default:
							break; // error out...
						}
						break;
					case "Pack":
						packing_size = (PackingSize)value;
						break;
					case "Size":
						class_size = value;
						break;
					default:
						break; // error out...
					}
				}
				return;
#if NET_2_0
			} else if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") {
				attrs |= TypeAttributes.SpecialName;
				return;
#endif
			} else if (attrname == "System.SerializableAttribute") {
				attrs |= TypeAttributes.Serializable;
				return;
			} else if (attrname == "System.Runtime.InteropServices.ComImportAttribute") {
				attrs |= TypeAttributes.Import;
				return;
			}

			if (cattrs != null) {
				CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
				cattrs.CopyTo (new_array, 0);
				new_array [cattrs.Length] = customBuilder;
				cattrs = new_array;
			} else {
				cattrs = new CustomAttributeBuilder [1];
				cattrs [0] = customBuilder;
			}
		}

#if NET_2_0
		[ComVisible (true)]
#endif
		public void SetCustomAttribute( ConstructorInfo con, byte[] binaryAttribute) {
			SetCustomAttribute (new CustomAttributeBuilder (con, binaryAttribute));
		}

		public EventBuilder DefineEvent( string name, EventAttributes attributes, Type eventtype) {
			check_name ("name", name);
			if (eventtype == null)
				throw new ArgumentNullException ("eventtype");
			check_not_created ();

			EventBuilder res = new EventBuilder (this, name, attributes, eventtype);
			if (events != null) {
				EventBuilder[] new_events = new EventBuilder [events.Length+1];
				System.Array.Copy (events, new_events, events.Length);
				new_events [events.Length] = res;
				events = new_events;
			} else {
				events = new EventBuilder [1];
				events [0] = res;
			}
			return res;
		}

		public FieldBuilder DefineInitializedData( string name, byte[] data, FieldAttributes attributes) {
			if (data == null)
				throw new ArgumentNullException ("data");
			if ((data.Length == 0) || (data.Length > 0x3f0000))
				throw new ArgumentException ("data", "Data size must be > 0 and < 0x3f0000");

			FieldBuilder res = DefineUninitializedData (name, data.Length, attributes);
			res.SetRVAData (data);

			return res;
		}

		static int UnmanagedDataCount = 0;
		
		public FieldBuilder DefineUninitializedData( string name, int size, FieldAttributes attributes) {
			check_name ("name", name);
			if ((size <= 0) || (size > 0x3f0000))
				throw new ArgumentException ("size", "Data size must be > 0 and < 0x3f0000");
			check_not_created ();

			string s = "$ArrayType$"+UnmanagedDataCount.ToString();
			UnmanagedDataCount++;
			TypeBuilder datablobtype = DefineNestedType (s,
				TypeAttributes.NestedPrivate|TypeAttributes.ExplicitLayout|TypeAttributes.Sealed,
				pmodule.assemblyb.corlib_value_type, null, PackingSize.Size1, size);
			datablobtype.CreateType ();
			return DefineField (name, datablobtype, attributes|FieldAttributes.Static|FieldAttributes.HasFieldRVA);
		}

		public TypeToken TypeToken {
			get {
				return new TypeToken (0x02000000 | table_idx);
			}
		}
		public void SetParent (Type parentType) {
			if (parentType == null)
				throw new ArgumentNullException ("parentType");
			check_not_created ();

			parent = parentType;
			// will just set the parent-related bits if called a second time
			setup_internal_class (this);
		}
		internal int get_next_table_index (object obj, int table, bool inc) {
			return pmodule.get_next_table_index (obj, table, inc);
		}

#if NET_2_0
		[ComVisible (true)]
#endif
		public override InterfaceMapping GetInterfaceMap (Type interfaceType)
		{
			if (created == null)
				throw new NotSupportedException ("This method is not implemented for incomplete types.");

			return created.GetInterfaceMap (interfaceType);
		}

		internal bool is_created {
			get {
				return created != null;
			}
		}

		private Exception not_supported ()
		{
			return new NotSupportedException ("The invoked member is not supported in a dynamic module.");
		}

		private void check_not_created ()
		{
			if (is_created)
				throw new InvalidOperationException ("Unable to change after type has been created.");
		}

		private void check_created ()
		{
			if (!is_created)
				throw not_supported ();
		}

		private void check_name (string argName, string name)
		{
			if (name == null)
				throw new ArgumentNullException (argName);
			if (name.Length == 0)
				throw new ArgumentException ("Empty name is not legal", argName);
			if (name.IndexOf ((char)0) != -1)
				throw new ArgumentException ("Illegal name", argName);
		}

		public override String ToString ()
		{
			return FullName;
		}

		[MonoTODO]
		public override bool IsAssignableFrom (Type c)
		{
			return base.IsAssignableFrom (c);
		}

#if NET_2_0
		[ComVisible (true)]
#endif
		[MonoTODO]
		public override bool IsSubclassOf (Type c)
		{
			return base.IsSubclassOf (c);
		}

		[MonoTODO ("arrays")]
		internal bool IsAssignableTo (Type c)
		{
			if (c == this)
				return true;

			if (c.IsInterface) {
				if (interfaces == null)
					return false;
				foreach (Type t in interfaces)
					if (c.IsAssignableFrom (t))
						return true;
				return false;
			}

			if (parent == null)
				return c == typeof (object);
			else
				return c.IsAssignableFrom (parent);
		}

#if NET_2_0 || BOOTSTRAP_NET_2_0
		public bool IsCreated () {
			return is_created;
		}

		public override Type[] GetGenericArguments ()
		{
			if (generic_params != null)
				return generic_params;

			throw new InvalidOperationException ();
		}

		public override Type GetGenericTypeDefinition ()
		{
			create_generic_class ();

			return base.GetGenericTypeDefinition ();
		}

		public override bool ContainsGenericParameters {
			get {
				return generic_params != null;
			}
		}

		public extern override bool IsGenericParameter {
			[MethodImplAttribute(MethodImplOptions.InternalCall)]
			get;
		}

		public override bool IsGenericTypeDefinition {
			get {
				return generic_params != null;
			}
		}

		public override bool IsGenericType {
			get { return IsGenericTypeDefinition; }
		}

		public override int GenericParameterPosition {
			get {
				throw new NotImplementedException ();
			}
		}

		public override MethodBase DeclaringMethod {
			get {
				throw new NotImplementedException ();
			}
		}

		public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
		{
			setup_generic_class ();

			generic_params = new GenericTypeParameterBuilder [names.Length];
			for (int i = 0; i < names.Length; i++)
				generic_params [i] = new GenericTypeParameterBuilder (
					this, null, names [i], i);

			return generic_params;
		}

                public static ConstructorInfo GetConstructor (Type instanciated, ConstructorInfo ctor)
                {
			ConstructorInfo res = instanciated.GetConstructor (ctor);
			if (res == null)
				throw new System.Exception ("constructor not found");
			else
				return res;
                }

                public static MethodInfo GetMethod (Type instanciated, MethodInfo meth)
                {
			MethodInfo res = instanciated.GetMethod (meth);
			if (res == null)
				throw new System.Exception ("method not found");
			else
				return res;
                }

                public static FieldInfo GetField (Type instanciated, FieldInfo fld)
                {
			FieldInfo res = instanciated.GetField (fld);
			if (res == null)
				throw new System.Exception ("field not found");
			else
				return res;
                }
#endif

                void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
                {
                        throw new NotImplementedException ();
                }

                void _TypeBuilder.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
                {
                        throw new NotImplementedException ();
                }

                void _TypeBuilder.GetTypeInfoCount (out uint pcTInfo)
                {
                        throw new NotImplementedException ();
                }

                void _TypeBuilder.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
                {
                        throw new NotImplementedException ();
                }
	}
}