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
use super::{
	code::{self, FunctionBuilder, SignaturesBuilder},
	data, export, global, import,
	invoke::{Identity, Invoke},
	memory::{self, MemoryBuilder},
	table::{self, TableBuilder},
};
use crate::elements;
use alloc::vec::Vec;

/// Module builder
pub struct ModuleBuilder<F = Identity> {
	callback: F,
	module: ModuleScaffold,
}

/// Location of the internal module function
pub struct CodeLocation {
	/// Location (index in 'functions' section) of the signature
	pub signature: u32,
	/// Location (index in the 'code' section) of the body
	pub body: u32,
}

#[derive(Default, PartialEq)]
struct ModuleScaffold {
	pub types: elements::TypeSection,
	pub import: elements::ImportSection,
	pub functions: elements::FunctionSection,
	pub table: elements::TableSection,
	pub memory: elements::MemorySection,
	pub global: elements::GlobalSection,
	pub export: elements::ExportSection,
	pub start: Option<u32>,
	pub element: elements::ElementSection,
	pub code: elements::CodeSection,
	pub data: elements::DataSection,
	pub other: Vec<elements::Section>,
}

impl From<elements::Module> for ModuleScaffold {
	fn from(module: elements::Module) -> Self {
		let mut types: Option<elements::TypeSection> = None;
		let mut import: Option<elements::ImportSection> = None;
		let mut funcs: Option<elements::FunctionSection> = None;
		let mut table: Option<elements::TableSection> = None;
		let mut memory: Option<elements::MemorySection> = None;
		let mut global: Option<elements::GlobalSection> = None;
		let mut export: Option<elements::ExportSection> = None;
		let mut start: Option<u32> = None;
		let mut element: Option<elements::ElementSection> = None;
		let mut code: Option<elements::CodeSection> = None;
		let mut data: Option<elements::DataSection> = None;

		let mut other = Vec::new();
		let mut sections = module.into_sections();
		while let Some(section) = sections.pop() {
			match section {
				elements::Section::Type(sect) => {
					types = Some(sect);
				},
				elements::Section::Import(sect) => {
					import = Some(sect);
				},
				elements::Section::Function(sect) => {
					funcs = Some(sect);
				},
				elements::Section::Table(sect) => {
					table = Some(sect);
				},
				elements::Section::Memory(sect) => {
					memory = Some(sect);
				},
				elements::Section::Global(sect) => {
					global = Some(sect);
				},
				elements::Section::Export(sect) => {
					export = Some(sect);
				},
				elements::Section::Start(index) => {
					start = Some(index);
				},
				elements::Section::Element(sect) => {
					element = Some(sect);
				},
				elements::Section::Code(sect) => {
					code = Some(sect);
				},
				elements::Section::Data(sect) => {
					data = Some(sect);
				},
				section => other.push(section),
			}
		}

		ModuleScaffold {
			types: types.unwrap_or_default(),
			import: import.unwrap_or_default(),
			functions: funcs.unwrap_or_default(),
			table: table.unwrap_or_default(),
			memory: memory.unwrap_or_default(),
			global: global.unwrap_or_default(),
			export: export.unwrap_or_default(),
			start,
			element: element.unwrap_or_default(),
			code: code.unwrap_or_default(),
			data: data.unwrap_or_default(),
			other,
		}
	}
}

impl From<ModuleScaffold> for elements::Module {
	fn from(module: ModuleScaffold) -> Self {
		let mut sections = Vec::new();

		let types = module.types;
		if !types.types().is_empty() {
			sections.push(elements::Section::Type(types));
		}
		let import = module.import;
		if !import.entries().is_empty() {
			sections.push(elements::Section::Import(import));
		}
		let functions = module.functions;
		if !functions.entries().is_empty() {
			sections.push(elements::Section::Function(functions));
		}
		let table = module.table;
		if !table.entries().is_empty() {
			sections.push(elements::Section::Table(table));
		}
		let memory = module.memory;
		if !memory.entries().is_empty() {
			sections.push(elements::Section::Memory(memory));
		}
		let global = module.global;
		if !global.entries().is_empty() {
			sections.push(elements::Section::Global(global));
		}
		let export = module.export;
		if !export.entries().is_empty() {
			sections.push(elements::Section::Export(export));
		}
		if let Some(start) = module.start {
			sections.push(elements::Section::Start(start));
		}
		let element = module.element;
		if !element.entries().is_empty() {
			sections.push(elements::Section::Element(element));
		}
		let code = module.code;
		if !code.bodies().is_empty() {
			sections.push(elements::Section::Code(code));
		}
		let data = module.data;
		if !data.entries().is_empty() {
			sections.push(elements::Section::Data(data));
		}
		sections.extend(module.other);
		elements::Module::new(sections)
	}
}

impl ModuleBuilder {
	/// New empty module builder
	pub fn new() -> Self {
		ModuleBuilder::with_callback(Identity)
	}
}

impl Default for ModuleBuilder {
	fn default() -> Self {
		Self::new()
	}
}

impl<F> ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	/// New module builder with bound callback
	pub fn with_callback(callback: F) -> Self {
		ModuleBuilder { callback, module: Default::default() }
	}

	/// Builder from raw module
	pub fn with_module(mut self, module: elements::Module) -> Self {
		self.module = module.into();
		self
	}

	/// Fill module with sections from iterator
	pub fn with_sections<I>(mut self, sections: I) -> Self
	where
		I: IntoIterator<Item = elements::Section>,
	{
		self.module.other.extend(sections);
		self
	}

	/// Add additional section
	pub fn with_section(mut self, section: elements::Section) -> Self {
		self.module.other.push(section);
		self
	}

	/// Binds to the type section, creates additional types when required
	pub fn with_signatures(mut self, bindings: code::SignatureBindings) -> Self {
		self.push_signatures(bindings);
		self
	}

	/// Push stand-alone function definition, creating sections, signature and code blocks
	/// in corresponding sections.
	/// `FunctionDefinition` can be build using `builder::function` builder
	pub fn push_function(&mut self, func: code::FunctionDefinition) -> CodeLocation {
		let signature = func.signature;
		let body = func.code;

		let type_ref = self.resolve_type_ref(signature);

		self.module.functions.entries_mut().push(elements::Func::new(type_ref));
		let signature_index = self.module.functions.entries_mut().len() as u32 - 1;
		self.module.code.bodies_mut().push(body);
		let body_index = self.module.code.bodies_mut().len() as u32 - 1;

		if func.is_main {
			self.module.start = Some(body_index);
		}

		CodeLocation { signature: signature_index, body: body_index }
	}

	/// Push linear memory region
	pub fn push_memory(&mut self, mut memory: memory::MemoryDefinition) -> u32 {
		let entries = self.module.memory.entries_mut();
		entries.push(elements::MemoryType::new(memory.min, memory.max));
		let memory_index = (entries.len() - 1) as u32;
		for data in memory.data.drain(..) {
			self.module.data.entries_mut().push(elements::DataSegment::new(
				memory_index,
				Some(data.offset),
				data.values,
			))
		}
		memory_index
	}

	/// Push table
	pub fn push_table(&mut self, mut table: table::TableDefinition) -> u32 {
		let entries = self.module.table.entries_mut();
		entries.push(elements::TableType::new(table.min, table.max));
		let table_index = (entries.len() - 1) as u32;
		for entry in table.elements.drain(..) {
			self.module.element.entries_mut().push(elements::ElementSegment::new(
				table_index,
				Some(entry.offset),
				entry.values,
			))
		}
		table_index
	}

	/// Push global.
	pub fn push_global(&mut self, global: elements::GlobalEntry) -> u32 {
		let entries = self.module.global.entries_mut();
		entries.push(global);
		entries.len() as u32 - 1
	}

	fn resolve_type_ref(&mut self, signature: code::Signature) -> u32 {
		match signature {
			code::Signature::Inline(func_type) => {
				if let Some(existing_entry) =
					self.module.types.types().iter().enumerate().find(|(_idx, t)| {
						let elements::Type::Function(ref existing) = t;
						*existing == func_type
					}) {
					return existing_entry.0 as u32
				}
				self.module.types.types_mut().push(elements::Type::Function(func_type));
				self.module.types.types().len() as u32 - 1
			},
			code::Signature::TypeReference(type_ref) => type_ref,
		}
	}

	/// Push one function signature, returning it's calling index.
	/// Can create corresponding type in type section.
	pub fn push_signature(&mut self, signature: code::Signature) -> u32 {
		self.resolve_type_ref(signature)
	}

	/// Push signatures in the module, returning corresponding indices of pushed signatures
	pub fn push_signatures(&mut self, signatures: code::SignatureBindings) -> Vec<u32> {
		signatures.into_iter().map(|binding| self.resolve_type_ref(binding)).collect()
	}

	/// Push import entry to module. Note that this does not update calling indices in
	/// function bodies.
	pub fn push_import(&mut self, import: elements::ImportEntry) -> u32 {
		self.module.import.entries_mut().push(import);
		// todo: actually update calling addresses in function bodies
		// todo: also batch push

		self.module.import.entries_mut().len() as u32 - 1
	}

	/// Push export entry to module.
	pub fn push_export(&mut self, export: elements::ExportEntry) -> u32 {
		self.module.export.entries_mut().push(export);
		self.module.export.entries_mut().len() as u32 - 1
	}

	/// Add new function using dedicated builder
	pub fn function(self) -> FunctionBuilder<Self> {
		FunctionBuilder::with_callback(self)
	}

	/// Add new linear memory using dedicated builder
	pub fn memory(self) -> MemoryBuilder<Self> {
		MemoryBuilder::with_callback(self)
	}

	/// Add new table using dedicated builder
	pub fn table(self) -> TableBuilder<Self> {
		TableBuilder::with_callback(self)
	}

	/// Define functions section
	pub fn functions(self) -> SignaturesBuilder<Self> {
		SignaturesBuilder::with_callback(self)
	}

	/// With inserted export entry
	pub fn with_export(mut self, entry: elements::ExportEntry) -> Self {
		self.module.export.entries_mut().push(entry);
		self
	}

	/// With inserted import entry
	pub fn with_import(mut self, entry: elements::ImportEntry) -> Self {
		self.module.import.entries_mut().push(entry);
		self
	}

	/// Import entry builder
	/// # Examples
	/// ```
	/// use parity_wasm::builder::module;
	///
	/// let module = module()
	///    .import()
	///        .module("env")
	///        .field("memory")
	///        .external().memory(256, Some(256))
	///        .build()
	///    .build();
	///
	/// assert_eq!(module.import_section().expect("import section to exist").entries().len(), 1);
	/// ```
	pub fn import(self) -> import::ImportBuilder<Self> {
		import::ImportBuilder::with_callback(self)
	}

	/// With global variable
	pub fn with_global(mut self, global: elements::GlobalEntry) -> Self {
		self.module.global.entries_mut().push(global);
		self
	}

	/// With table
	pub fn with_table(mut self, table: elements::TableType) -> Self {
		self.module.table.entries_mut().push(table);
		self
	}

	/// Export entry builder
	/// # Examples
	/// ```
	/// use parity_wasm::builder::module;
	/// use parity_wasm::elements::Instruction::*;
	///
	/// let module = module()
	///    .global()
	///         .value_type().i32()
	///         .init_expr(I32Const(0))
	///         .build()
	///    .export()
	///        .field("_zero")
	///        .internal().global(0)
	///        .build()
	///    .build();
	///
	/// assert_eq!(module.export_section().expect("export section to exist").entries().len(), 1);
	/// ```
	pub fn export(self) -> export::ExportBuilder<Self> {
		export::ExportBuilder::with_callback(self)
	}

	/// Glboal entry builder
	/// # Examples
	/// ```
	/// use parity_wasm::builder::module;
	/// use parity_wasm::elements::Instruction::*;
	///
	/// let module = module()
	///    .global()
	///         .value_type().i32()
	///         .init_expr(I32Const(0))
	///         .build()
	///    .build();
	///
	/// assert_eq!(module.global_section().expect("global section to exist").entries().len(), 1);
	/// ```
	pub fn global(self) -> global::GlobalBuilder<Self> {
		global::GlobalBuilder::with_callback(self)
	}

	/// Add data segment to the builder
	pub fn with_data_segment(mut self, segment: elements::DataSegment) -> Self {
		self.module.data.entries_mut().push(segment);
		self
	}

	/// Data entry builder
	pub fn data(self) -> data::DataSegmentBuilder<Self> {
		data::DataSegmentBuilder::with_callback(self)
	}

	/// Build module (final step)
	pub fn build(self) -> F::Result {
		self.callback.invoke(self.module.into())
	}
}

impl<F> Invoke<elements::FunctionSection> for ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	type Result = Self;

	fn invoke(self, section: elements::FunctionSection) -> Self {
		self.with_section(elements::Section::Function(section))
	}
}

impl<F> Invoke<code::SignatureBindings> for ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	type Result = Self;

	fn invoke(self, bindings: code::SignatureBindings) -> Self {
		self.with_signatures(bindings)
	}
}

impl<F> Invoke<code::FunctionDefinition> for ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	type Result = Self;

	fn invoke(self, def: code::FunctionDefinition) -> Self {
		let mut b = self;
		b.push_function(def);
		b
	}
}

impl<F> Invoke<memory::MemoryDefinition> for ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	type Result = Self;

	fn invoke(self, def: memory::MemoryDefinition) -> Self {
		let mut b = self;
		b.push_memory(def);
		b
	}
}

impl<F> Invoke<table::TableDefinition> for ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	type Result = Self;

	fn invoke(self, def: table::TableDefinition) -> Self {
		let mut b = self;
		b.push_table(def);
		b
	}
}

impl<F> Invoke<elements::ImportEntry> for ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	type Result = Self;

	fn invoke(self, entry: elements::ImportEntry) -> Self::Result {
		self.with_import(entry)
	}
}

impl<F> Invoke<elements::ExportEntry> for ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	type Result = Self;

	fn invoke(self, entry: elements::ExportEntry) -> Self::Result {
		self.with_export(entry)
	}
}

impl<F> Invoke<elements::GlobalEntry> for ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	type Result = Self;

	fn invoke(self, entry: elements::GlobalEntry) -> Self::Result {
		self.with_global(entry)
	}
}

impl<F> Invoke<elements::DataSegment> for ModuleBuilder<F>
where
	F: Invoke<elements::Module>,
{
	type Result = Self;

	fn invoke(self, segment: elements::DataSegment) -> Self {
		self.with_data_segment(segment)
	}
}

/// Start new module builder
/// # Examples
///
/// ```
/// use parity_wasm::builder;
///
/// let module = builder::module()
///     .function()
///         .signature().param().i32().build()
///         .body().build()
///         .build()
///     .build();
///
/// assert_eq!(module.type_section().expect("type section to exist").types().len(), 1);
/// assert_eq!(module.function_section().expect("function section to exist").entries().len(), 1);
/// assert_eq!(module.code_section().expect("code section to exist").bodies().len(), 1);
/// ```
pub fn module() -> ModuleBuilder {
	ModuleBuilder::new()
}

/// Start builder to extend existing module
pub fn from_module(module: elements::Module) -> ModuleBuilder {
	ModuleBuilder::new().with_module(module)
}

#[cfg(test)]
mod tests {

	use super::module;
	use crate::elements;

	#[test]
	fn smoky() {
		let module = module().build();
		assert_eq!(module.sections().len(), 0);
	}

	#[test]
	fn functions() {
		let module = module()
			.function()
			.signature()
			.param()
			.i32()
			.build()
			.body()
			.build()
			.build()
			.build();

		assert_eq!(module.type_section().expect("type section to exist").types().len(), 1);
		assert_eq!(
			module.function_section().expect("function section to exist").entries().len(),
			1
		);
		assert_eq!(module.code_section().expect("code section to exist").bodies().len(), 1);
	}

	#[test]
	fn export() {
		let module = module().export().field("call").internal().func(0).build().build();

		assert_eq!(module.export_section().expect("export section to exist").entries().len(), 1);
	}

	#[test]
	fn global() {
		let module = module()
			.global()
			.value_type()
			.i64()
			.mutable()
			.init_expr(elements::Instruction::I64Const(5))
			.build()
			.build();

		assert_eq!(module.global_section().expect("global section to exist").entries().len(), 1);
	}

	#[test]
	fn data() {
		let module = module()
			.data()
			.offset(elements::Instruction::I32Const(16))
			.value(vec![0u8, 15, 10, 5, 25])
			.build()
			.build();

		assert_eq!(module.data_section().expect("data section to exist").entries().len(), 1);
	}

	#[test]
	fn reuse_types() {
		let module = module()
			.function()
			.signature()
			.param()
			.i32()
			.build()
			.body()
			.build()
			.build()
			.function()
			.signature()
			.param()
			.i32()
			.build()
			.body()
			.build()
			.build()
			.build();

		assert_eq!(module.type_section().expect("type section failed").types().len(), 1);
	}
}