hao 0.0.19

Read, edit, create and write .net assemblies
Documentation
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
//! Which tables a tables stream has, how many rows each has, and where each
//! one's rows are.

use super::coded_tokens::CodedTokenSizes;
use super::{tables::*, TableLocation, ValueSize};
use crate::dotnet::md::calculator::{SizeCalculator, TablePositionCalculator};
use crate::dotnet::md::streams::Version;
use crate::dotnet::md::MDStreamFlags;
use crate::io::ReadData;
use crate::{
    error::{HaoError, Result},
    io::DataReader,
};
use bitflags::bitflags;

bitflags! {
    /// One bit per table, in table number order: the tables stream header's
    /// `Valid` (which tables are present) and `Sorted` (which are sorted) masks
    /// (ECMA-335 §II.24.2.6).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct TableExistsFlags: u64 {
        /// Module: this module's name and MVID.
        const Module = 1<<0;
        /// TypeRef: types from other modules and assemblies.
        const TypeRef = 1<<1;
        /// TypeDef: types defined in this module.
        const TypeDef = 1<<2;
        /// FieldPtr: field indirection, in unoptimized `#-` metadata only.
        const FieldPtr = 1<<3;
        /// Field: fields defined in this module.
        const Field = 1<<4;
        /// MethodPtr: method indirection, in unoptimized `#-` metadata only.
        const MethodPtr = 1<<5;
        /// MethodDef: methods defined in this module.
        const Method = 1<<6;
        /// ParamPtr: parameter indirection, in unoptimized `#-` metadata only.
        const ParamPtr = 1<<7;
        /// Param: parameter names and flags.
        const Param = 1<<8;
        /// InterfaceImpl: the interfaces each type implements.
        const InterfaceImpl = 1<<9;
        /// MemberRef: references to methods and fields of other types.
        const MemberRef = 1<<10;
        /// Constant: default values of fields, parameters and properties.
        const Constant = 1<<11;
        /// CustomAttribute: custom attributes.
        const CustomAttribute = 1<<12;
        /// FieldMarshal: native marshalling of fields and parameters.
        const FieldMarshal = 1<<13;
        /// DeclSecurity: declarative security attributes.
        const DeclSecurity = 1<<14;
        /// ClassLayout: explicit packing and size of types.
        const ClassLayout = 1<<15;
        /// FieldLayout: explicit field offsets.
        const FieldLayout = 1<<16;
        /// StandAloneSig: local variable and `calli` signatures.
        const StandAloneSig = 1<<17;
        /// EventMap: which events each type owns.
        const EventMap = 1<<18;
        /// EventPtr: event indirection, in unoptimized `#-` metadata only.
        const EventPtr = 1<<19;
        /// Event: events.
        const Event = 1<<20;
        /// PropertyMap: which properties each type owns.
        const PropertyMap = 1<<21;
        /// PropertyPtr: property indirection, in unoptimized `#-` metadata only.
        const PropertyPtr = 1<<22;
        /// Property: properties.
        const Property = 1<<23;
        /// MethodSemantics: property and event accessors.
        const MethodSemantics = 1<<24;
        /// MethodImpl: explicit overrides.
        const MethodImpl = 1<<25;
        /// ModuleRef: referenced modules and native libraries.
        const ModuleRef = 1<<26;
        /// TypeSpec: constructed types: generic instances, arrays, pointers.
        const TypeSpec = 1<<27;
        /// ImplMap: P/Invoke mappings.
        const ImplMap = 1<<28;
        /// FieldRVA: initial data of fields.
        const FieldRva = 1<<29;
        /// ENCLog: the Edit and Continue log.
        const EncLog = 1<<30;
        /// ENCMap: the Edit and Continue token map.
        const EncMap = 1<<31;
        /// Assembly: this assembly's name, version and key.
        const Assembly = 1<<32;
        /// AssemblyProcessor: unused; ignored by the runtime.
        const AssemblyProcessor = 1<<33;
        /// AssemblyOS: unused; ignored by the runtime.
        const AssemblyOs = 1<<34;
        /// AssemblyRef: referenced assemblies.
        const AssemblyRef = 1<<35;
        /// AssemblyRefProcessor: unused; ignored by the runtime.
        const AssemblyRefProcessor = 1<<36;
        /// AssemblyRefOS: unused; ignored by the runtime.
        const AssemblyRefOs = 1<<37;
        /// File: the other files of a multi-file assembly.
        const File = 1<<38;
        /// ExportedType: exported and forwarded types.
        const ExportedType = 1<<39;
        /// ManifestResource: embedded and linked resources.
        const ManifestResource = 1<<40;
        /// NestedClass: the enclosing type of each nested type.
        const NestedClass = 1<<41;
        /// GenericParam: generic parameters of types and methods.
        const GenericParam = 1<<42;
        /// MethodSpec: generic method instances.
        const MethodSpec = 1<<43;
        /// GenericParamConstraint: constraints on generic parameters.
        const GenericParamConstraint = 1<<44;
        /// Document: Portable PDB: source files.
        const Document = 1<<48;
        /// MethodDebugInformation: Portable PDB: sequence points.
        const MethodDebugInformation = 1<<49;
        /// LocalScope: Portable PDB: local variable scopes.
        const LocalScope = 1<<50;
        /// LocalVariable: Portable PDB: local variable names.
        const LocalVariable = 1<<51;
        /// LocalConstant: Portable PDB: local constants.
        const LocalConstant = 1<<52;
        /// ImportScope: Portable PDB: namespace imports.
        const ImportScope = 1<<53;
        /// StateMachineMethod: Portable PDB: async and iterator kickoff methods.
        const StateMachineMethod = 1<<54;
        /// CustomDebugInformation: Portable PDB: custom debug information.
        const CustomDebugInformation = 1<<55;
    }
}

/// Number of rows in a table. It decides whether indexes into that table are
/// 2 or 4 bytes wide.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub struct TableRowCount(pub u32);

impl TableRowCount {
    /// Whether indexes into the table take 4 bytes: it has more than 65535 rows.
    pub fn is_large(&self) -> bool {
        self.0 > u16::MAX as u32
    }

    /// Width of a simple index into the table (not the size of a row).
    pub fn row_size(&self) -> ValueSize {
        if self.is_large() {
            ValueSize::Big
        } else {
            ValueSize::Small
        }
    }
}

impl PartialEq<usize> for TableRowCount {
    fn eq(&self, other: &usize) -> bool {
        self.0 as usize == *other
    }
}

/// Row count of every table, read from the tables stream header. Absent
/// tables have 0 rows.
#[derive(Debug, Clone, Default)]
pub struct TableRows {
    /// Rows in Module: this module's name and MVID.
    pub module: TableRowCount,
    /// Rows in TypeRef: types from other modules and assemblies.
    pub type_ref: TableRowCount,
    /// Rows in TypeDef: types defined in this module.
    pub type_def: TableRowCount,
    /// Rows in FieldPtr: field indirection, in unoptimized `#-` metadata only.
    pub field_ptr: TableRowCount,
    /// Rows in Field: fields defined in this module.
    pub field: TableRowCount,
    /// Rows in MethodPtr: method indirection, in unoptimized `#-` metadata only.
    pub method_ptr: TableRowCount,
    /// Rows in MethodDef: methods defined in this module.
    pub method: TableRowCount,
    /// Rows in ParamPtr: parameter indirection, in unoptimized `#-` metadata only.
    pub param_ptr: TableRowCount,
    /// Rows in Param: parameter names and flags.
    pub param: TableRowCount,
    /// Rows in InterfaceImpl: the interfaces each type implements.
    pub interface_impl: TableRowCount,
    /// Rows in MemberRef: references to methods and fields of other types.
    pub member_ref: TableRowCount,
    /// Rows in Constant: default values of fields, parameters and properties.
    pub constant: TableRowCount,
    /// Rows in CustomAttribute: custom attributes.
    pub custom_attribute: TableRowCount,
    /// Rows in FieldMarshal: native marshalling of fields and parameters.
    pub field_marshal: TableRowCount,
    /// Rows in DeclSecurity: declarative security attributes.
    pub decl_security: TableRowCount,
    /// Rows in ClassLayout: explicit packing and size of types.
    pub class_layout: TableRowCount,
    /// Rows in FieldLayout: explicit field offsets.
    pub field_layout: TableRowCount,
    /// Rows in StandAloneSig: local variable and `calli` signatures.
    pub stand_alone_sig: TableRowCount,
    /// Rows in EventMap: which events each type owns.
    pub event_map: TableRowCount,
    /// Rows in EventPtr: event indirection, in unoptimized `#-` metadata only.
    pub event_ptr: TableRowCount,
    /// Rows in Event: events.
    pub event: TableRowCount,
    /// Rows in PropertyMap: which properties each type owns.
    pub property_map: TableRowCount,
    /// Rows in PropertyPtr: property indirection, in unoptimized `#-` metadata only.
    pub property_ptr: TableRowCount,
    /// Rows in Property: properties.
    pub property: TableRowCount,
    /// Rows in MethodSemantics: property and event accessors.
    pub method_semantics: TableRowCount,
    /// Rows in MethodImpl: explicit overrides.
    pub method_impl: TableRowCount,
    /// Rows in ModuleRef: referenced modules and native libraries.
    pub module_ref: TableRowCount,
    /// Rows in TypeSpec: constructed types: generic instances, arrays, pointers.
    pub type_spec: TableRowCount,
    /// Rows in ImplMap: P/Invoke mappings.
    pub impl_map: TableRowCount,
    /// Rows in FieldRVA: initial data of fields.
    pub field_rva: TableRowCount,
    /// Rows in ENCLog: the Edit and Continue log.
    pub enc_log: TableRowCount,
    /// Rows in ENCMap: the Edit and Continue token map.
    pub enc_map: TableRowCount,
    /// Rows in Assembly: this assembly's name, version and key.
    pub assembly: TableRowCount,
    /// Rows in AssemblyProcessor: unused; ignored by the runtime.
    pub assembly_processor: TableRowCount,
    /// Rows in AssemblyOS: unused; ignored by the runtime.
    pub assembly_os: TableRowCount,
    /// Rows in AssemblyRef: referenced assemblies.
    pub assembly_ref: TableRowCount,
    /// Rows in AssemblyRefProcessor: unused; ignored by the runtime.
    pub assembly_ref_processor: TableRowCount,
    /// Rows in AssemblyRefOS: unused; ignored by the runtime.
    pub assembly_ref_os: TableRowCount,
    /// Rows in File: the other files of a multi-file assembly.
    pub file: TableRowCount,
    /// Rows in ExportedType: exported and forwarded types.
    pub exported_type: TableRowCount,
    /// Rows in ManifestResource: embedded and linked resources.
    pub manifest_resource: TableRowCount,
    /// Rows in NestedClass: the enclosing type of each nested type.
    pub nested_class: TableRowCount,
    /// Rows in GenericParam: generic parameters of types and methods.
    pub generic_param: TableRowCount,
    /// Rows in MethodSpec: generic method instances.
    pub method_spec: TableRowCount,
    /// Rows in GenericParamConstraint: constraints on generic parameters.
    pub generic_param_constraint: TableRowCount,
    /// Rows in Document: Portable PDB: source files.
    pub document: TableRowCount,
    /// Rows in MethodDebugInformation: Portable PDB: sequence points.
    pub method_debug_information: TableRowCount,
    /// Rows in LocalScope: Portable PDB: local variable scopes.
    pub local_scope: TableRowCount,
    /// Rows in LocalVariable: Portable PDB: local variable names.
    pub local_variable: TableRowCount,
    /// Rows in LocalConstant: Portable PDB: local constants.
    pub local_constant: TableRowCount,
    /// Rows in ImportScope: Portable PDB: namespace imports.
    pub import_scope: TableRowCount,
    /// Rows in StateMachineMethod: Portable PDB: async and iterator kickoff methods.
    pub state_machine_method: TableRowCount,
    /// Rows in CustomDebugInformation: Portable PDB: custom debug information.
    pub custom_debug_information: TableRowCount,
}

impl TableRows {
    /// Reads the row counts that follow the header: one `u32` for each table set in
    /// `valid_rows`, in table order. Errors if `valid_rows` has a bit for a table
    /// hao doesn't know, since its count can't be skipped.
    pub fn from_reader(reader: &mut DataReader, valid_rows: TableExistsFlags) -> Result<Self> {
        fn read_if_flag(
            reader: &mut DataReader,
            valid_rows: TableExistsFlags,
            flag: TableExistsFlags,
        ) -> Result<TableRowCount> {
            if valid_rows.contains(flag) {
                reader.read().map(TableRowCount)
            } else {
                Ok(TableRowCount(0))
            }
        }

        // A count is stored for every set bit, so an unknown table would shift
        // every count after it.
        if valid_rows.bits() & !TableExistsFlags::all().bits() != 0 {
            return Err(HaoError::BadImageFormat(
                "tables stream has a table hao doesn't know",
            ));
        }

        Ok(Self {
            module: read_if_flag(reader, valid_rows, TableExistsFlags::Module)?,
            type_ref: read_if_flag(reader, valid_rows, TableExistsFlags::TypeRef)?,
            type_def: read_if_flag(reader, valid_rows, TableExistsFlags::TypeDef)?,
            field_ptr: read_if_flag(reader, valid_rows, TableExistsFlags::FieldPtr)?,
            field: read_if_flag(reader, valid_rows, TableExistsFlags::Field)?,
            method_ptr: read_if_flag(reader, valid_rows, TableExistsFlags::MethodPtr)?,
            method: read_if_flag(reader, valid_rows, TableExistsFlags::Method)?,
            param_ptr: read_if_flag(reader, valid_rows, TableExistsFlags::ParamPtr)?,
            param: read_if_flag(reader, valid_rows, TableExistsFlags::Param)?,
            interface_impl: read_if_flag(reader, valid_rows, TableExistsFlags::InterfaceImpl)?,
            member_ref: read_if_flag(reader, valid_rows, TableExistsFlags::MemberRef)?,
            constant: read_if_flag(reader, valid_rows, TableExistsFlags::Constant)?,
            custom_attribute: read_if_flag(reader, valid_rows, TableExistsFlags::CustomAttribute)?,
            field_marshal: read_if_flag(reader, valid_rows, TableExistsFlags::FieldMarshal)?,
            decl_security: read_if_flag(reader, valid_rows, TableExistsFlags::DeclSecurity)?,
            class_layout: read_if_flag(reader, valid_rows, TableExistsFlags::ClassLayout)?,
            field_layout: read_if_flag(reader, valid_rows, TableExistsFlags::FieldLayout)?,
            stand_alone_sig: read_if_flag(reader, valid_rows, TableExistsFlags::StandAloneSig)?,
            event_map: read_if_flag(reader, valid_rows, TableExistsFlags::EventMap)?,
            event_ptr: read_if_flag(reader, valid_rows, TableExistsFlags::EventPtr)?,
            event: read_if_flag(reader, valid_rows, TableExistsFlags::Event)?,
            property_map: read_if_flag(reader, valid_rows, TableExistsFlags::PropertyMap)?,
            property_ptr: read_if_flag(reader, valid_rows, TableExistsFlags::PropertyPtr)?,
            property: read_if_flag(reader, valid_rows, TableExistsFlags::Property)?,
            method_semantics: read_if_flag(reader, valid_rows, TableExistsFlags::MethodSemantics)?,
            method_impl: read_if_flag(reader, valid_rows, TableExistsFlags::MethodImpl)?,
            module_ref: read_if_flag(reader, valid_rows, TableExistsFlags::ModuleRef)?,
            type_spec: read_if_flag(reader, valid_rows, TableExistsFlags::TypeSpec)?,
            impl_map: read_if_flag(reader, valid_rows, TableExistsFlags::ImplMap)?,
            field_rva: read_if_flag(reader, valid_rows, TableExistsFlags::FieldRva)?,
            enc_log: read_if_flag(reader, valid_rows, TableExistsFlags::EncLog)?,
            enc_map: read_if_flag(reader, valid_rows, TableExistsFlags::EncMap)?,
            assembly: read_if_flag(reader, valid_rows, TableExistsFlags::Assembly)?,
            assembly_processor: read_if_flag(
                reader,
                valid_rows,
                TableExistsFlags::AssemblyProcessor,
            )?,
            assembly_os: read_if_flag(reader, valid_rows, TableExistsFlags::AssemblyOs)?,
            assembly_ref: read_if_flag(reader, valid_rows, TableExistsFlags::AssemblyRef)?,
            assembly_ref_processor: read_if_flag(
                reader,
                valid_rows,
                TableExistsFlags::AssemblyRefProcessor,
            )?,
            assembly_ref_os: read_if_flag(reader, valid_rows, TableExistsFlags::AssemblyRefOs)?,
            file: read_if_flag(reader, valid_rows, TableExistsFlags::File)?,
            exported_type: read_if_flag(reader, valid_rows, TableExistsFlags::ExportedType)?,
            manifest_resource: read_if_flag(
                reader,
                valid_rows,
                TableExistsFlags::ManifestResource,
            )?,
            nested_class: read_if_flag(reader, valid_rows, TableExistsFlags::NestedClass)?,
            generic_param: read_if_flag(reader, valid_rows, TableExistsFlags::GenericParam)?,
            method_spec: read_if_flag(reader, valid_rows, TableExistsFlags::MethodSpec)?,
            generic_param_constraint: read_if_flag(
                reader,
                valid_rows,
                TableExistsFlags::GenericParamConstraint,
            )?,
            document: read_if_flag(reader, valid_rows, TableExistsFlags::Document)?,
            method_debug_information: read_if_flag(
                reader,
                valid_rows,
                TableExistsFlags::MethodDebugInformation,
            )?,
            local_scope: read_if_flag(reader, valid_rows, TableExistsFlags::LocalScope)?,
            local_variable: read_if_flag(reader, valid_rows, TableExistsFlags::LocalVariable)?,
            local_constant: read_if_flag(reader, valid_rows, TableExistsFlags::LocalConstant)?,
            import_scope: read_if_flag(reader, valid_rows, TableExistsFlags::ImportScope)?,
            state_machine_method: read_if_flag(
                reader,
                valid_rows,
                TableExistsFlags::StateMachineMethod,
            )?,
            custom_debug_information: read_if_flag(
                reader,
                valid_rows,
                TableExistsFlags::CustomDebugInformation,
            )?,
        })
    }
}

/// Where every table's rows are in the tables stream, computed from the row
/// counts and column widths.
#[derive(Debug, Clone)]
pub struct TableLocations {
    /// Module: this module's name and MVID.
    pub module: TableLocation,
    /// TypeRef: types from other modules and assemblies.
    pub type_ref: TableLocation,
    /// TypeDef: types defined in this module.
    pub type_def: TableLocation,
    /// FieldPtr: field indirection, in unoptimized `#-` metadata only.
    pub field_ptr: TableLocation,
    /// Field: fields defined in this module.
    pub field: TableLocation,
    /// MethodPtr: method indirection, in unoptimized `#-` metadata only.
    pub method_ptr: TableLocation,
    /// MethodDef: methods defined in this module.
    pub method: TableLocation,
    /// ParamPtr: parameter indirection, in unoptimized `#-` metadata only.
    pub param_ptr: TableLocation,
    /// Param: parameter names and flags.
    pub param: TableLocation,
    /// InterfaceImpl: the interfaces each type implements.
    pub interface_impl: TableLocation,
    /// MemberRef: references to methods and fields of other types.
    pub member_ref: TableLocation,
    /// Constant: default values of fields, parameters and properties.
    pub constant: TableLocation,
    /// CustomAttribute: custom attributes.
    pub custom_attribute: TableLocation,
    /// FieldMarshal: native marshalling of fields and parameters.
    pub field_marshal: TableLocation,
    /// DeclSecurity: declarative security attributes.
    pub decl_security: TableLocation,
    /// ClassLayout: explicit packing and size of types.
    pub class_layout: TableLocation,
    /// FieldLayout: explicit field offsets.
    pub field_layout: TableLocation,
    /// StandAloneSig: local variable and `calli` signatures.
    pub stand_alone_sig: TableLocation,
    /// EventMap: which events each type owns.
    pub event_map: TableLocation,
    /// EventPtr: event indirection, in unoptimized `#-` metadata only.
    pub event_ptr: TableLocation,
    /// Event: events.
    pub event: TableLocation,
    /// PropertyMap: which properties each type owns.
    pub property_map: TableLocation,
    /// PropertyPtr: property indirection, in unoptimized `#-` metadata only.
    pub property_ptr: TableLocation,
    /// Property: properties.
    pub property: TableLocation,
    /// MethodSemantics: property and event accessors.
    pub method_semantics: TableLocation,
    /// MethodImpl: explicit overrides.
    pub method_impl: TableLocation,
    /// ModuleRef: referenced modules and native libraries.
    pub module_ref: TableLocation,
    /// TypeSpec: constructed types: generic instances, arrays, pointers.
    pub type_spec: TableLocation,
    /// ImplMap: P/Invoke mappings.
    pub impl_map: TableLocation,
    /// FieldRVA: initial data of fields.
    pub field_rva: TableLocation,
    /// ENCLog: the Edit and Continue log.
    pub enc_log: TableLocation,
    /// ENCMap: the Edit and Continue token map.
    pub enc_map: TableLocation,
    /// Assembly: this assembly's name, version and key.
    pub assembly: TableLocation,
    /// AssemblyProcessor: unused; ignored by the runtime.
    pub assembly_processor: TableLocation,
    /// AssemblyOS: unused; ignored by the runtime.
    pub assembly_os: TableLocation,
    /// AssemblyRef: referenced assemblies.
    pub assembly_ref: TableLocation,
    /// AssemblyRefProcessor: unused; ignored by the runtime.
    pub assembly_ref_processor: TableLocation,
    /// AssemblyRefOS: unused; ignored by the runtime.
    pub assembly_ref_os: TableLocation,
    /// File: the other files of a multi-file assembly.
    pub file: TableLocation,
    /// ExportedType: exported and forwarded types.
    pub exported_type: TableLocation,
    /// ManifestResource: embedded and linked resources.
    pub manifest_resource: TableLocation,
    /// NestedClass: the enclosing type of each nested type.
    pub nested_class: TableLocation,
    /// GenericParam: generic parameters of types and methods.
    pub generic_param: TableLocation,
    /// MethodSpec: generic method instances.
    pub method_spec: TableLocation,
    /// GenericParamConstraint: constraints on generic parameters.
    pub generic_param_constraint: TableLocation,
    /// Document: Portable PDB: source files.
    pub document: TableLocation,
    /// MethodDebugInformation: Portable PDB: sequence points.
    pub method_debug_information: TableLocation,
    /// LocalScope: Portable PDB: local variable scopes.
    pub local_scope: TableLocation,
    /// LocalVariable: Portable PDB: local variable names.
    pub local_variable: TableLocation,
    /// LocalConstant: Portable PDB: local constants.
    pub local_constant: TableLocation,
    /// ImportScope: Portable PDB: namespace imports.
    pub import_scope: TableLocation,
    /// StateMachineMethod: Portable PDB: async and iterator kickoff methods.
    pub state_machine_method: TableLocation,
    /// CustomDebugInformation: Portable PDB: custom debug information.
    pub custom_debug_information: TableLocation,
}

impl TableLocations {
    /// Lays the tables out back to back in table order, sizing each row from the
    /// row counts, coded index widths, heap index flags and schema version.
    pub fn from_metadata(
        rows: &TableRows,
        coded_tokens_sizes: &CodedTokenSizes,
        flags: MDStreamFlags,
        version: Version,
    ) -> Self {
        let size_calculator = SizeCalculator {
            coded_tokens_sizes,
            flags,
            rows,
            version,
        };
        let mut calc = TablePositionCalculator::new(&size_calculator);
        Self {
            module: calc.calculate_location::<ModulesTableRow>(rows.module),
            type_ref: calc.calculate_location::<TypeRefTableRow>(rows.type_ref),
            type_def: calc.calculate_location::<TypeDefTableRow>(rows.type_def),
            field_ptr: calc.calculate_location::<FieldPtrTableRow>(rows.field_ptr),
            field: calc.calculate_location::<FieldTableRow>(rows.field),
            method_ptr: calc.calculate_location::<MethodPtrTableRow>(rows.method_ptr),
            method: calc.calculate_location::<MethodTableRow>(rows.method),
            param_ptr: calc.calculate_location::<ParamPtrTableRow>(rows.param_ptr),
            param: calc.calculate_location::<ParamTableRow>(rows.param),
            interface_impl: calc.calculate_location::<InterfaceImplTableRow>(rows.interface_impl),
            member_ref: calc.calculate_location::<MemberRefTableRow>(rows.member_ref),
            constant: calc.calculate_location::<ConstantTableRow>(rows.constant),
            custom_attribute: calc
                .calculate_location::<CustomAttributeTableRow>(rows.custom_attribute),
            field_marshal: calc.calculate_location::<FieldMarshalTableRow>(rows.field_marshal),
            decl_security: calc.calculate_location::<DeclSecurityTableRow>(rows.decl_security),
            class_layout: calc.calculate_location::<ClassLayoutTableRow>(rows.class_layout),
            field_layout: calc.calculate_location::<FieldLayoutTableRow>(rows.field_layout),
            stand_alone_sig: calc.calculate_location::<StandAloneSigTableRow>(rows.stand_alone_sig),
            event_map: calc.calculate_location::<EventMapTableRow>(rows.event_map),
            event_ptr: calc.calculate_location::<EventPtrTableRow>(rows.event_ptr),
            event: calc.calculate_location::<EventTableRow>(rows.event),
            property_map: calc.calculate_location::<PropertyMapTableRow>(rows.property_map),
            property_ptr: calc.calculate_location::<PropertyPtrTableRow>(rows.property_ptr),
            property: calc.calculate_location::<PropertyTableRow>(rows.property),
            method_semantics: calc
                .calculate_location::<MethodSemanticsTableRow>(rows.method_semantics),
            method_impl: calc.calculate_location::<MethodImplTableRow>(rows.method_impl),
            module_ref: calc.calculate_location::<ModuleRefTableRow>(rows.module_ref),
            type_spec: calc.calculate_location::<TypeSpecTableRow>(rows.type_spec),
            impl_map: calc.calculate_location::<ImplMapTableRow>(rows.impl_map),
            field_rva: calc.calculate_location::<FieldRVATableRow>(rows.field_rva),
            enc_log: calc.calculate_location::<ENCLogTableRow>(rows.enc_log),
            enc_map: calc.calculate_location::<ENCMapTableRow>(rows.enc_map),
            assembly: calc.calculate_location::<AssemblyTableRow>(rows.assembly),
            assembly_processor: calc
                .calculate_location::<AssemblyProcessorTableRow>(rows.assembly_processor),
            assembly_os: calc.calculate_location::<AssemblyOSTableRow>(rows.assembly_os),
            assembly_ref: calc.calculate_location::<AssemblyRefTableRow>(rows.assembly_ref),
            assembly_ref_processor: calc
                .calculate_location::<AssemblyRefProcessorTableRow>(rows.assembly_ref_processor),
            assembly_ref_os: calc.calculate_location::<AssemblyRefOSTableRow>(rows.assembly_ref_os),
            file: calc.calculate_location::<FileTableRow>(rows.file),
            exported_type: calc.calculate_location::<ExportedTypeTableRow>(rows.exported_type),
            manifest_resource: calc
                .calculate_location::<ManifestResourceTableRow>(rows.manifest_resource),
            nested_class: calc.calculate_location::<NestedClassTableRow>(rows.nested_class),
            generic_param: calc.calculate_location::<GenericParamTableRow>(rows.generic_param),
            method_spec: calc.calculate_location::<MethodSpecTableRow>(rows.method_spec),
            generic_param_constraint: calc.calculate_location::<GenericParamConstraintTableRow>(
                rows.generic_param_constraint,
            ),
            document: calc.calculate_location::<DocumentTableRow>(rows.document),
            method_debug_information: calc.calculate_location::<MethodDebugInformationTableRow>(
                rows.method_debug_information,
            ),
            local_scope: calc.calculate_location::<LocalScopeTableRow>(rows.local_scope),
            local_variable: calc.calculate_location::<LocalVariableTableRow>(rows.local_variable),
            local_constant: calc.calculate_location::<LocalConstantTableRow>(rows.local_constant),
            import_scope: calc.calculate_location::<ImportScopeTableRow>(rows.import_scope),
            state_machine_method: calc
                .calculate_location::<StateMachineMethodTableRow>(rows.state_machine_method),
            custom_debug_information: calc.calculate_location::<CustomDebugInformationTableRow>(
                rows.custom_debug_information,
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn table_bits_are_table_numbers() {
        // ECMA-335 §II.22 and the Portable PDB spec number the tables.
        let numbers = [
            (TableExistsFlags::Module, 0x00),
            (TableExistsFlags::TypeDef, 0x02),
            (TableExistsFlags::Field, 0x04),
            (TableExistsFlags::Method, 0x06),
            (TableExistsFlags::Param, 0x08),
            (TableExistsFlags::CustomAttribute, 0x0C),
            (TableExistsFlags::StandAloneSig, 0x11),
            (TableExistsFlags::Property, 0x17),
            (TableExistsFlags::FieldRva, 0x1D),
            (TableExistsFlags::Assembly, 0x20),
            (TableExistsFlags::AssemblyRef, 0x23),
            (TableExistsFlags::ManifestResource, 0x28),
            (TableExistsFlags::GenericParamConstraint, 0x2C),
            (TableExistsFlags::Document, 0x30),
            (TableExistsFlags::MethodDebugInformation, 0x31),
            (TableExistsFlags::LocalScope, 0x32),
            (TableExistsFlags::LocalVariable, 0x33),
            (TableExistsFlags::LocalConstant, 0x34),
            (TableExistsFlags::ImportScope, 0x35),
            (TableExistsFlags::StateMachineMethod, 0x36),
            (TableExistsFlags::CustomDebugInformation, 0x37),
        ];
        for (flag, number) in numbers {
            assert_eq!(flag.bits(), 1 << number, "{flag:?}");
        }
    }

    fn counts(counts: &[u32]) -> Vec<u8> {
        counts.iter().flat_map(|c| c.to_le_bytes()).collect()
    }

    #[test]
    fn row_counts_in_table_order() {
        // Module (bit 0) and Document (bit 0x30).
        let valid = TableExistsFlags::from_bits_retain(1 | 1 << 0x30);
        let data = counts(&[1, 5]);
        let rows = TableRows::from_reader(&mut DataReader::new(&data), valid).unwrap();
        assert_eq!(rows.module, 1);
        assert_eq!(rows.document, 5);
        assert_eq!(rows.local_variable, 0);
    }

    #[test]
    fn unknown_table_bit_is_an_error() {
        // Bit 0x2D names no table; its row count would shift every later one.
        let valid = TableExistsFlags::from_bits_retain(1 | 1 << 0x2D | 1 << 0x30);
        let data = counts(&[1, 7, 5]);
        assert!(TableRows::from_reader(&mut DataReader::new(&data), valid).is_err());
    }
}