-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathEncoder.swift
More file actions
803 lines (737 loc) · 29.4 KB
/
Copy pathEncoder.swift
File metadata and controls
803 lines (737 loc) · 29.4 KB
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
import WasmParser
import WasmTypes
struct Encoder {
var output: [UInt8] = []
mutating func writeHeader() {
output.append(contentsOf: [
0x00, 0x61, 0x73, 0x6D, // magic
0x01, 0x00, 0x00, 0x00, // version
])
}
mutating func section<E: Error>(id: UInt8, _ sectionContent: (inout Encoder) throws(E) -> Void) throws(E) {
output.append(id)
var contentEncoder = Encoder()
try sectionContent(&contentEncoder)
writeUnsignedLEB128(UInt32(contentEncoder.output.count))
output.append(contentsOf: contentEncoder.output)
}
mutating func encodeVector<Source: Collection, E: Error>(
_ values: Source, encodeElement: (Source.Element, inout Encoder) throws(E) -> Void
) throws(E) {
writeUnsignedLEB128(UInt32(values.count))
for value in values {
try encodeElement(value, &self)
}
}
mutating func encodeVector<Source: Collection, Element: WasmEncodable>(_ values: Source, transform: (Source.Element) -> (Element)) {
encodeVector(
values,
encodeElement: { element, encoder in
transform(element).encode(to: &encoder)
})
}
mutating func encodeVector<Source: Collection>(_ values: Source) where Source.Element: WasmEncodable {
encodeVector(values, encodeElement: { $0.encode(to: &$1) })
}
mutating func encodeByteVector(_ values: [UInt8]) {
writeUnsignedLEB128(UInt32(values.count))
output.append(contentsOf: values)
}
mutating func encode<T: WasmEncodable>(_ value: T) {
value.encode(to: &self)
}
mutating func writeUnsignedLEB128<T: UnsignedInteger & FixedWidthInteger>(_ value: T) {
var value = value
repeat {
var byte = UInt8(value & 0b0111_1111)
value >>= 7
if value != 0 {
byte |= 0b1000_0000
}
output.append(byte)
} while value != 0
}
mutating func writeSignedLEB128<T: SignedInteger & FixedWidthInteger>(_ value: T) {
func leb128LoopUntil(_ until: (T, UInt8) -> Bool) {
var value = value
while true {
let byte = UInt8(value & 0b0111_1111)
value >>= 7
if until(value, byte) {
output.append(byte)
break
} else {
output.append(byte | 0b1000_0000)
}
}
}
if value < 0 {
leb128LoopUntil { value, byte in
return value == -1 && (byte & 0b0100_0000) != 0
}
} else {
leb128LoopUntil { value, byte in
return value == 0 && (byte & 0b0100_0000) == 0
}
}
}
mutating func writeExpression(lexer: inout Lexer, wat: inout Wat) throws(WatParserError) {
var parser = ExpressionParser<ExpressionEncoder>(lexer: lexer, features: wat.features)
var exprEncoder = ExpressionEncoder()
try parser.parse(visitor: &exprEncoder, wat: &wat)
try exprEncoder.visitEnd()
output.append(contentsOf: exprEncoder.encoder.output)
lexer = parser.parser.lexer
}
mutating func writeInstruction(lexer: inout Lexer, wat: inout Wat) throws(WatParserError) {
var parser = ExpressionParser<ExpressionEncoder>(lexer: lexer, features: wat.features)
var exprEncoder = ExpressionEncoder()
guard try parser.instruction(visitor: &exprEncoder, wat: &wat) else {
throw WatParserError("unexpected end of instruction", location: lexer.location())
}
try exprEncoder.visitEnd()
output.append(contentsOf: exprEncoder.encoder.output)
lexer = parser.parser.lexer
}
}
protocol WasmEncodable {
func encode(to encoder: inout Encoder)
}
extension ValueType: WasmEncodable {
func encode(to encoder: inout Encoder) {
switch self {
case .i32: encoder.output.append(0x7F)
case .i64: encoder.output.append(0x7E)
case .f32: encoder.output.append(0x7D)
case .f64: encoder.output.append(0x7C)
case .v128: encoder.output.append(0x7B)
case .ref(let refType): encoder.encode(refType)
}
}
}
extension ReferenceType: WasmEncodable {
func encode(to encoder: inout Encoder) {
switch (isNullable, heapType) {
// Use short form when available
case (true, .externRef): encoder.output.append(0x6F)
case (true, .funcRef): encoder.output.append(0x70)
case (true, .exnRef): encoder.output.append(0x69)
default:
encoder.output.append(isNullable ? 0x63 : 0x64)
encoder.encode(heapType)
}
}
}
extension HeapType: WasmEncodable {
func encode(to encoder: inout Encoder) {
switch self {
case .abstract(.externRef): encoder.output.append(0x6F)
case .abstract(.funcRef): encoder.output.append(0x70)
case .abstract(.exnRef): encoder.output.append(0x69)
case .concrete(let typeIndex):
// Note that the typeIndex is decoded as s33,
// so we need to encode it as signed.
encoder.writeSignedLEB128(Int64(typeIndex))
}
}
}
extension FunctionType: WasmEncodable {
func encode(to encoder: inout Encoder) {
encoder.output.append(0x60)
encoder.writeUnsignedLEB128(UInt32(parameters.count))
for param in parameters {
param.encode(to: &encoder)
}
encoder.writeUnsignedLEB128(UInt32(results.count))
for result in results {
result.encode(to: &encoder)
}
}
}
extension TableType: WasmEncodable {
func encode(to encoder: inout Encoder) {
elementType.encode(to: &encoder)
limits.encode(to: &encoder)
}
}
struct ElementExprCollector: AnyInstructionVisitor {
typealias VisitorError = WatParserError
typealias Output = Void
var binaryOffset: Int = 0
var isAllRefFunc: Bool = true
var instructions: [Instruction] = []
mutating func parse(indices: WatParser.ElementDecl.Indices, wat: inout Wat) throws(WatParserError) {
switch indices {
case .elementExprList(let lexer):
var parser = ExpressionParser<ElementExprCollector>(lexer: lexer, features: wat.features)
try parser.parseElemExprList(visitor: &self, wat: &wat)
case .functionList(let lexer):
try self.parseFunctionList(lexer: lexer, wat: wat)
}
}
private mutating func addFunctionIndex(_ index: UInt32) {
instructions.append(.refFunc(functionIndex: index))
}
private mutating func parseFunctionList(lexer: Lexer, wat: Wat) throws(WatParserError) {
var parser = Parser(lexer)
while let funcUse = try parser.takeIndexOrId() {
let (_, funcIndex) = try wat.functionsMap.resolve(use: funcUse)
addFunctionIndex(UInt32(funcIndex))
}
}
mutating func visit(_ instruction: Instruction) {
if case .refFunc = instruction {
} else {
isAllRefFunc = false
}
instructions.append(instruction)
}
}
extension WAT.WatParser.ElementDecl {
func encode(to encoder: inout Encoder, wat: inout Wat) throws(WatParserError) {
func isMemory64(tableIndex: Int) throws(WatParserError) -> Bool {
guard tableIndex < wat.tablesMap.count else { return false }
return try wat.tablesMap[tableIndex].type.resolve(wat.types).limits.isMemory64
}
var flags: UInt32 = 0
var tableIndex: UInt32? = nil
var isPassive = false
var hasTableIndex = false
let type = try type.resolve(wat.types)
switch self.mode {
case .active(let table, _):
let index: Int?
if let table {
index = try wat.tablesMap.resolve(use: table).index
} else {
index = nil
}
if type != .funcRef || (index != nil && index != 0) {
// has index
flags |= 0b0010
tableIndex = UInt32(index ?? 0)
hasTableIndex = true
}
case .passive:
// is passive
flags |= 0b0001
isPassive = true
case .declarative:
// is declarative
flags |= 0b0011
isPassive = true
case .inline:
fatalError("Inline element segment should be replaced with active mode")
}
var collector = ElementExprCollector()
try collector.parse(indices: indices, wat: &wat)
var useExpression: Bool {
// if all instructions are ref.func, use function indices representation
return !collector.isAllRefFunc || type != .funcRef
}
if useExpression {
// use expression
flags |= 0b0100
}
encoder.writeUnsignedLEB128(flags)
if let tableIndex = tableIndex {
encoder.writeUnsignedLEB128(tableIndex)
}
if case .active(_, let offset) = self.mode {
switch offset {
case .expression(var lexer):
try encoder.writeExpression(lexer: &lexer, wat: &wat)
case .singleInstruction(var lexer):
try encoder.writeInstruction(lexer: &lexer, wat: &wat)
case .synthesized(let offset):
var exprEncoder = ExpressionEncoder()
if try isMemory64(tableIndex: Int(tableIndex ?? 0)) {
try exprEncoder.visitI64Const(value: Int64(offset))
} else {
try exprEncoder.visitI32Const(value: Int32(offset))
}
try exprEncoder.visitEnd()
encoder.output.append(contentsOf: exprEncoder.encoder.output)
}
}
if isPassive || hasTableIndex {
if useExpression {
encoder.encode(type)
} else {
// Write ExternKind.func
encoder.writeUnsignedLEB128(UInt8(0x00))
}
}
if useExpression {
try encoder.encodeVector(collector.instructions) { instruction, encoder throws(WatParserError) in
var exprEncoder = ExpressionEncoder()
switch instruction {
case .globalGet(let globalIndex):
try exprEncoder.visitGlobalGet(globalIndex: globalIndex)
case .refFunc(let functionIndex):
try exprEncoder.visitRefFunc(functionIndex: functionIndex)
case .refNull(let type):
try exprEncoder.visitRefNull(type: type)
default:
throw WatParserError("unexpected instruction in element expression (\(instruction)", location: nil)
}
try exprEncoder.visitEnd()
encoder.output.append(contentsOf: exprEncoder.encoder.output)
}
} else {
encoder.encodeVector(collector.instructions) { instruction, encoder in
guard case .refFunc(let funcIndex) = instruction else { fatalError("non-ref.func instruction in non-expression mode") }
encoder.writeUnsignedLEB128(funcIndex)
}
}
}
}
extension String: WasmEncodable {
func encode(to encoder: inout Encoder) {
encoder.writeUnsignedLEB128(UInt32(utf8.count))
encoder.output.append(contentsOf: utf8)
}
}
extension Export: WasmEncodable {
func encode(to encoder: inout Encoder) {
encoder.encode(name)
switch descriptor {
case .function(let index):
encoder.output.append(0x00)
encoder.writeUnsignedLEB128(UInt32(index))
case .table(let index):
encoder.output.append(0x01)
encoder.writeUnsignedLEB128(UInt32(index))
case .memory(let index):
encoder.output.append(0x02)
encoder.writeUnsignedLEB128(UInt32(index))
case .global(let index):
encoder.output.append(0x03)
encoder.writeUnsignedLEB128(UInt32(index))
case .tag(let index):
encoder.output.append(0x04)
encoder.writeUnsignedLEB128(UInt32(index))
}
}
}
extension WatParser.GlobalDecl {
func encode(to encoder: inout Encoder, wat: inout Wat) throws(WatParserError) {
let type = try self.type.resolve(wat.types)
encoder.encode(type)
guard case .definition(var expr) = kind else {
fatalError("imported global declaration should not be encoded here")
}
try encoder.writeExpression(lexer: &expr, wat: &wat)
}
}
extension WatParser.MemoryDecl: WasmEncodable {
func encode(to encoder: inout Encoder) {
encoder.encode(type)
}
}
extension Limits: WasmEncodable {
func encode(to encoder: inout Encoder) {
var flags = 0
if max != nil {
flags |= 0b0001
}
if shared {
flags |= 0b0010
}
if isMemory64 {
flags |= 0b0100
}
encoder.output.append(UInt8(flags))
encoder.writeUnsignedLEB128(min)
if let max = max {
encoder.writeUnsignedLEB128(max)
}
}
}
extension GlobalType: WasmEncodable {
func encode(to encoder: inout Encoder) {
encoder.encode(self.valueType)
switch self.mutability {
case .constant:
encoder.output.append(0x00)
case .variable:
encoder.output.append(0x01)
}
}
}
extension Import: WasmEncodable {
func encode(to encoder: inout Encoder) {
encoder.encode(module)
encoder.encode(name)
switch descriptor {
case .function(let typeIndex):
encoder.output.append(0x00)
encoder.writeUnsignedLEB128(UInt32(typeIndex))
case .table(let tableType):
encoder.output.append(0x01)
tableType.encode(to: &encoder)
case .memory(let memoryType):
encoder.output.append(0x02)
memoryType.encode(to: &encoder)
case .global(let globalType):
encoder.output.append(0x03)
globalType.encode(to: &encoder)
case .tag(let typeIndex):
encoder.output.append(0x04)
encoder.output.append(0x00) // attribute: exception
encoder.writeUnsignedLEB128(UInt32(typeIndex))
}
}
}
extension WatParser.DataSegmentDecl.Offset {
func encode(to encoder: inout Encoder, wat: inout Wat, isMemory64: Bool) throws(WatParserError) {
switch self {
case .source(var offset):
try encoder.writeExpression(lexer: &offset, wat: &wat)
case .synthesized(let index):
var exprEncoder = ExpressionEncoder()
if isMemory64 {
try exprEncoder.visitI64Const(value: Int64(index))
} else {
try exprEncoder.visitI32Const(value: Int32(index))
}
try exprEncoder.visitEnd()
encoder.output.append(contentsOf: exprEncoder.encoder.output)
}
}
}
extension WatParser.DataSegmentDecl {
func encode(to encoder: inout Encoder, wat: inout Wat) throws(WatParserError) {
func isMemory64(memoryIndex: Int) -> Bool {
guard memoryIndex < wat.memories.count else { return false }
return wat.memories[memoryIndex].type.isMemory64
}
switch (self.memory, self.offset) {
case (nil, let offset?):
// active with default memory
encoder.output.append(0x00)
try offset.encode(to: &encoder, wat: &wat, isMemory64: isMemory64(memoryIndex: 0))
case (nil, nil):
// passive
encoder.output.append(0x01)
case (let memory?, let offset?):
let memoryIndex = try wat.memories.resolve(use: memory).index
if memoryIndex == 0 {
// active with default memory
encoder.output.append(0x00)
} else {
// active with explicit memory index
encoder.output.append(0x02)
encoder.writeUnsignedLEB128(UInt32(memoryIndex))
}
try offset.encode(to: &encoder, wat: &wat, isMemory64: isMemory64(memoryIndex: memoryIndex))
case (_?, nil):
fatalError("memory with memory index but no offset")
}
encoder.encodeByteVector(data)
}
}
struct ExpressionEncoder: BinaryInstructionEncoder {
typealias VisitorError = WatParserError
var binaryOffset: Int = 0
var encoder = Encoder()
var hasDataSegmentInstruction: Bool = false
mutating func encodeUnsigned<T: UnsignedInteger & FixedWidthInteger>(_ value: T) {
encoder.writeUnsignedLEB128(value)
}
mutating func encodeSigned<T: SignedInteger & FixedWidthInteger>(_ value: T) {
encoder.writeSignedLEB128(value)
}
mutating func encodeByte(_ value: UInt8) {
encoder.output.append(value)
}
mutating func encodeFixedWidth<T: FixedWidthInteger>(_ value: T) {
let value = value.littleEndian
withUnsafeBytes(of: value) { bytes in
encoder.output.append(contentsOf: bytes)
}
}
// MARK: Special instructions
mutating func visitMemoryInit(dataIndex: UInt32) {
encodeInstruction([0xFC, 0x08])
encodeImmediates(dataIndex: dataIndex)
encodeByte(0x00) // reserved value
}
mutating func visitTypedSelect(type: ValueType) {
encodeInstruction([0x1C])
encodeByte(0x01) // number of result types
encodeImmediates(type: type)
}
// MARK: InstructionEncoder conformance
mutating func encodeInstruction(_ opcode: [UInt8]) {
encoder.output.append(contentsOf: opcode)
}
mutating func encodeImmediates(blockType: WasmParser.BlockType) {
switch blockType {
case .empty: encoder.output.append(0x40)
case .type(let valueType): encoder.encode(valueType)
case .funcType(let typeIndex):
encoder.writeSignedLEB128(Int64(typeIndex))
}
}
mutating func encodeImmediates(dataIndex: UInt32) {
hasDataSegmentInstruction = true
encodeUnsigned(dataIndex)
}
mutating func encodeImmediates(elemIndex: UInt32) { encodeUnsigned(elemIndex) }
mutating func encodeImmediates(functionIndex: UInt32) { encodeUnsigned(functionIndex) }
mutating func encodeImmediates(globalIndex: UInt32) { encodeUnsigned(globalIndex) }
mutating func encodeImmediates(localIndex: UInt32) { encodeUnsigned(localIndex) }
mutating func encodeImmediates(typeIndex: UInt32) { encodeUnsigned(typeIndex) }
mutating func encodeImmediates(memarg: WasmParser.MemArg) {
encodeUnsigned(UInt(memarg.align))
encodeUnsigned(memarg.offset)
}
mutating func encodeImmediates(lane: UInt8) { encoder.output.append(lane) }
mutating func encodeImmediates(memarg: WasmParser.MemArg, lane: UInt8) {
encodeImmediates(memarg: memarg)
encodeImmediates(lane: lane)
}
mutating func encodeImmediates(lanes: WasmTypes.V128ShuffleMask) {
encoder.output.append(contentsOf: lanes.lanes)
}
mutating func encodeImmediates(memory: UInt32) { encodeUnsigned(memory) }
mutating func encodeImmediates(relativeDepth: UInt32) { encodeUnsigned(relativeDepth) }
mutating func encodeImmediates(table: UInt32) { encodeUnsigned(table) }
mutating func encodeImmediates(targets: WasmParser.BrTable) {
encoder.encodeVector(targets.labelIndices) { value, encoder in
encoder.writeUnsignedLEB128(value)
}
encodeUnsigned(targets.defaultIndex)
}
mutating func encodeImmediates(type: WasmTypes.ValueType) { encoder.encode(type) }
mutating func encodeImmediates(type: WasmTypes.HeapType) { encoder.encode(type) }
mutating func encodeImmediates(value: Int32) { encodeSigned(value) }
mutating func encodeImmediates(value: Int64) { encodeSigned(value) }
mutating func encodeImmediates(value: WasmTypes.V128) { encoder.output.append(contentsOf: value.bytes) }
mutating func encodeImmediates(value: WasmParser.IEEE754.Float32) { encodeFixedWidth(value.bitPattern) }
mutating func encodeImmediates(value: WasmParser.IEEE754.Float64) { encodeFixedWidth(value.bitPattern) }
mutating func encodeImmediates(tagIndex: UInt32) { encodeUnsigned(tagIndex) }
mutating func encodeImmediates(blockType: WasmParser.BlockType, tryCatch: WasmParser.TryCatch) {
encodeImmediates(blockType: blockType)
encoder.writeUnsignedLEB128(UInt32(tryCatch.catches.count))
for clause in tryCatch.catches {
switch clause {
case .catch(let tagIndex, let labelIndex):
encoder.output.append(0x00)
encoder.writeUnsignedLEB128(tagIndex)
encoder.writeUnsignedLEB128(labelIndex)
case .catchRef(let tagIndex, let labelIndex):
encoder.output.append(0x01)
encoder.writeUnsignedLEB128(tagIndex)
encoder.writeUnsignedLEB128(labelIndex)
case .catchAll(let labelIndex):
encoder.output.append(0x02)
encoder.writeUnsignedLEB128(labelIndex)
case .catchAllRef(let labelIndex):
encoder.output.append(0x03)
encoder.writeUnsignedLEB128(labelIndex)
}
}
}
mutating func encodeImmediates(dstMem: UInt32, srcMem: UInt32) {
encodeUnsigned(dstMem)
encodeUnsigned(srcMem)
}
mutating func encodeImmediates(dstTable: UInt32, srcTable: UInt32) {
encodeUnsigned(dstTable)
encodeUnsigned(srcTable)
}
mutating func encodeImmediates(elemIndex: UInt32, table: UInt32) {
encodeUnsigned(elemIndex)
encodeUnsigned(table)
}
mutating func encodeImmediates(typeIndex: UInt32, tableIndex: UInt32) {
encodeUnsigned(typeIndex)
encodeUnsigned(tableIndex)
}
}
func encode(module: inout Wat, options: EncodeOptions) throws(WatParserError) -> [UInt8] {
var encoder = Encoder()
encoder.writeHeader()
var codeEncoder = Encoder()
let functions = module.functionsMap.compactMap { (function: WatParser.FunctionDecl) -> ([WatParser.LocalDecl], WatParser.FunctionDecl)? in
guard case .definition(let locals, _) = function.kind else {
return nil
}
return (locals, function)
}
var functionSection: [UInt32] = []
var tagSection: [UInt32] = []
var hasDataSegmentInstruction = false
if !functions.isEmpty {
try codeEncoder.section(id: 0x0A) { encoder throws(WatParserError) in
try encoder.encodeVector(
functions,
encodeElement: { source, encoder throws(WatParserError) in
let (locals, function) = source
var exprEncoder = ExpressionEncoder()
// Encode locals
var localsEntries: [(type: ValueType, count: UInt32)] = []
for local in locals {
let type = try local.type.resolve(module.types)
if localsEntries.last?.type == type {
localsEntries[localsEntries.count - 1].count += 1
} else {
localsEntries.append((type: type, count: 1))
}
}
exprEncoder.encoder.encodeVector(localsEntries) { local, encoder in
encoder.writeUnsignedLEB128(local.count)
local.type.encode(to: &encoder)
}
let funcTypeIndex = try function.parse(visitor: &exprEncoder, wat: &module, features: module.features)
functionSection.append(UInt32(funcTypeIndex))
// TODO?
try exprEncoder.visitEnd()
encoder.writeUnsignedLEB128(UInt(exprEncoder.encoder.output.count))
encoder.output.append(contentsOf: exprEncoder.encoder.output)
hasDataSegmentInstruction = hasDataSegmentInstruction || exprEncoder.hasDataSegmentInstruction
})
}
}
// Pre-resolve tag type indices so their types are in the type section.
let tagDefinitions = module.tagsMap.definitions()
for tag in tagDefinitions {
let typeIndex = try module.types.resolveIndex(use: tag.typeUse)
tagSection.append(UInt32(typeIndex))
}
// Section 1: Type section
if !module.types.isEmpty {
encoder.section(id: 0x01) { encoder in
encoder.encodeVector(module.types, transform: \.type.signature)
}
}
// Section 2: Import section
if !module.imports.isEmpty {
encoder.section(id: 0x02) { encoder in
encoder.encodeVector(module.imports)
}
}
// Section 3: Function section
if !functionSection.isEmpty {
encoder.section(id: 0x03) { encoder in
encoder.encodeVector(functionSection) { typeIndex, encoder in
encoder.writeUnsignedLEB128(UInt32(typeIndex))
}
}
}
// Section 4: Table section
let tables = module.tablesMap.definitions()
if !tables.isEmpty {
try encoder.section(id: 0x04) { encoder throws(WatParserError) in
try encoder.encodeVector(tables) { table, encoder throws(WatParserError) in
try table.type.resolve(module.types).encode(to: &encoder)
}
}
}
// Section 5: Memory section
let memories = module.memories.definitions()
if !memories.isEmpty {
encoder.section(id: 0x05) { encoder in
encoder.encodeVector(memories)
}
}
// Section 13: Tag section
// Note: tagsec is placed between memsec and globalsec in the module grammar.
// https://webassembly.github.io/exception-handling/core/binary/modules.html#binary-module
if !tagSection.isEmpty {
encoder.section(id: 0x0D) { encoder in
encoder.encodeVector(tagSection) { typeIndex, encoder in
encoder.output.append(0x00) // attribute: exception
encoder.writeUnsignedLEB128(typeIndex)
}
}
}
// Section 6: Global section
let globals = module.globals.definitions()
if !globals.isEmpty {
try encoder.section(id: 0x06) { encoder throws(WatParserError) in
try encoder.encodeVector(globals) { global, encoder throws(WatParserError) in
try global.encode(to: &encoder, wat: &module)
}
}
}
// Section 7: Export section
if !module.exports.isEmpty {
encoder.section(id: 0x07) { encoder in
encoder.encodeVector(module.exports) { export, encoder in
export.encode(to: &encoder)
}
}
}
// Section 8: Start section
if let start = module.start {
encoder.section(id: 0x08) { encoder in
encoder.writeUnsignedLEB128(start)
}
}
// Section 9: Element section
if !module.elementsMap.isEmpty {
try encoder.section(id: 0x09) { encoder throws(WatParserError) in
try encoder.encodeVector(module.elementsMap) { element, encoder throws(WatParserError) in
try element.encode(to: &encoder, wat: &module)
}
}
}
// Section 12: DataCount section
if !module.data.isEmpty, hasDataSegmentInstruction {
encoder.section(id: 0x0C) { encoder in
encoder.writeUnsignedLEB128(UInt32(module.data.count))
}
}
// Section 10: Code section
encoder.output.append(contentsOf: codeEncoder.output)
// Section 11: Data section
if !module.data.isEmpty {
try encoder.section(id: 0x0B) { encoder throws(WatParserError) in
try encoder.encodeVector(module.data) { data, encoder throws(WatParserError) in
try data.encode(to: &encoder, wat: &module)
}
}
}
// (Optional) Name Section
let hasFunctionNames = module.functionsMap.contains { $0.id != nil }
let hasGlobalNames = module.globals.contains { $0.id != nil }
if options.nameSection && (hasFunctionNames || hasGlobalNames) {
encoder.section(id: 0) { encoder in
encoder.encode("name")
// Subsection 1: Function names
if hasFunctionNames {
encoder.section(id: 1) { encoder in
let functionNames = module.functionsMap.enumerated().compactMap { i, decl -> (Int, String)? in
guard let name = decl.id else { return nil }
return (i, name.value)
}
encoder.encodeVector(functionNames) { entry, encoder in
let (index, name) = entry
encoder.writeUnsignedLEB128(UInt(index))
// Drop initial "$"
encoder.encode(String(name.dropFirst()))
}
}
}
// Subsection 7: Global names
if hasGlobalNames {
encoder.section(id: 7) { encoder in
let globalNames = module.globals.enumerated().compactMap { i, decl -> (Int, String)? in
guard let name = decl.id else { return nil }
return (i, name.value)
}
encoder.encodeVector(globalNames) { entry, encoder in
let (index, name) = entry
encoder.writeUnsignedLEB128(UInt(index))
// Drop initial "$"
encoder.encode(String(name.dropFirst()))
}
}
}
}
}
return encoder.output
}