-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathparse.all.js
More file actions
1153 lines (1060 loc) · 38.2 KB
/
parse.all.js
File metadata and controls
1153 lines (1060 loc) · 38.2 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
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
// Node.js API.
const util = require('util')
// Determine if an integer parse should be unrolled.
const { parse: homogeneous } = require('./homogeneous')
// Format source code maintaining indentation.
const $ = require('programmatic')
// Convert numbers and arrays to numbers to literals with hex literals.
const hex = require('./hex')
// Generate literal object construction.
const vivify = require('./vivify')
const Inliner = require('./inline')
// Generate two's compliment conversion.
const unsign = require('./fiddle/unsign')
// Generate integer unpacking.
const unpack = require('./unpack')
// Determine necessary variables.
const { parse: declare } = require('./declare')
// Generate required modules and functions.
const required = require('./required')
const map = require('./map')
// Format source code maintaining indentation.
const join = require('./join')
function expand (fields) {
const expanded = []
for (const field of fields) {
switch (field.type) {
case 'structure':
case 'inline':
case 'accumulator':
field.fields = expand(field.fields)
expanded.push(field)
break
case 'sip':
for (const condition of field.conditions) {
condition.fields = expand(condition.fields)
}
expanded.push(field)
break
case 'conditional':
for (const condition of field.parse.conditions) {
condition.fields = expand(condition.fields)
}
expanded.push(field)
break
case 'switch':
for (const when of field.cases) {
when.fields = expand(when.fields)
}
expanded.push(field)
break
case 'fixed':
if (field.calculated) {
expanded.push({ type: 'calculation', field, vivify: null })
}
field.fields = expand(field.fields)
expanded.push(field)
break
case 'terminated':
field.fields = [{
type: 'terminator', body: field, dotted: '', vivify: null
}, {
type: 'repeated',
body: field,
fields: expand(field.fields),
dotted: '',
vivify: 'array'
}]
expanded.push(field)
break
case 'lengthEncoded':
field.fields = expand(field.fields)
expanded.push({ type: 'lengthEncoding', body: field, vivify: null })
expanded.push(field)
break
default:
expanded.push(field)
break
}
}
return expanded
}
//
// Insert checkpoints for best-foot-forward search. See the detailed description
// of checkpoint inseration in [`serialize.all.js`](serialize.all.js.html),
// since it follows the same principle.
//
function checkpoints (path, fields, $i = 0, $I = 0) {
let checkpoint = { type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0 }
const checked = [ checkpoint ]
for (const field of fields) {
switch (field.type) {
case 'structure':
case 'accumulator':
case 'inline':
case 'inline':
checked.push(field)
if (field.fixed) {
checkpoint.lengths[0] += field.bits / 8
} else {
// TODO Could start from the nested checkpoint since we are are
// not actually looping for the structure.
field.fields = checkpoints(path + field.dotted, field.fields, $i, $I)
checked.push(checkpoint = {
type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0
})
}
break
case 'switch':
checked.push(field)
for (const when of field.cases) {
when.fields = checkpoints(path + field.dotted, when.fields, $i)
}
checked.push(checkpoint = {
type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0
})
break
case 'sip': {
checked.push(field)
field.sip = checkpoints(path + field.dotted, field.sip, $i, $I)
for (const condition of field.conditions) {
condition.fields = checkpoints(path + field.dotted, condition.fields, $i, $I)
}
checked.push(checkpoint = {
type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0
})
}
break
case 'conditional':
checked.push(field)
// TODO Sip belongs outside since it is generally a byte or so.
if (field.parse.sip != null) {
field.parse.sip = checkpoints(path + field.dotted, field.parse.sip, $i, $I)
}
for (const condition of field.parse.conditions) {
condition.fields = checkpoints(path + field.dotted, condition.fields, $i, $I)
}
checked.push(checkpoint = {
type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0
})
break
case 'fixed':
if (field.fixed) {
checked.push(field)
checkpoint.lengths[0] += field.bits / 8
} else {
checked.push(field)
if (field.calculated) {
field.fields = checkpoints(`${path}${field.dotted}[$i[${$i}]]`, field.fields, $i + 1, $I + 1)
} else {
field.fields = checkpoints(`${path}${field.dotted}[$i[${$i}]]`, field.fields, $i + 1, $I)
}
checked.push(checkpoint = {
type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0
})
}
break
case 'calculation':
if (field.field.fields[0].fixed) {
checked.push(field)
checked.push(checkpoint = { type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0 })
checkpoint.lengths.push(`$I[${$I}] * ${field.field.fields[0].bits >>> 3}`)
} else {
checked.push(field)
}
break
case 'terminator':
checked.push(field)
checkpoint.lengths[0] += field.body.terminator.length
break
// TODO Checkpoint invocation on fields in two places?
case 'repeated':
// TODO If the terminator is greater than or equal to the size of
// the repeated part, we do not have to perform the checkpoint.
checked.push(field)
field.fields = checkpoints(path, field.fields, $i, $I)
break
case 'terminated':
checked.push(field)
const element = field.fields.slice().pop().fields.slice().pop()
if (element.type != 'buffer') {
field.fields = checkpoints(path + `${field.dotted}[$i[${$i}]]`, field.fields, $i + 1, $I)
}
checked.push(checkpoint = {
type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0
})
break
case 'lengthEncoded':
checked.push(field)
if (field.fields[0].fixed) {
// Tricky, stick the checkpoint for a fixed array at the end of
// the encoding fields. Let any subsequent fields use the
// checkpoint.
checkpoint.lengths.push(`${field.fields[0].bits >>> 3} * $I[${$I}]`)
} else {
field.fields = checkpoints(`${path}${field.dotted}[$i[${$i}]]`, field.fields, $i + 1, $I + 1)
checked.push(checkpoint = {
type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0
})
}
break
case 'lengthEncoding':
checked.push(field)
if (field.body.encoding[0].fixed) {
checkpoint.lengths[0] += field.body.encoding[0].bits / 8
} else {
field.body.encoding = checkpoints(`${path}${field.dotted}.length`, field.body.encoding, $i, $I)
}
checked.push(checkpoint = {
type: 'checkpoint', lengths: [ 0 ], vivify: null, rewind: 0
})
break
default:
checked.push(field)
checkpoint.lengths[0] += field.bits / 8
break
}
}
// Remove any list of lengths that begins with a zero constant. There may
// still be calculated lengths following.
checked.forEach(field => {
if (field.type == 'checkpoint' && field.lengths[0] == 0) {
field.lengths.shift()
}
})
// Remove any checkpoints that only had the zero constant.
return checked.filter(field => {
return field.type != 'checkpoint' || field.lengths.length != 0
})
}
//
// Use only in testing. Inserts a checkpoint before every actual read to ensure
// that we're correctly incrementing the step. Otherwise we have to add a
// complicated subsequent field to every test that the step is set correctly
// because most of the time the checkpoint will evaluate the buffer for the
// length of the entire packet.
// That is, this is simply BFF with a checkpoint before every field.
//
function inquisition (fields, $I = 0) {
const checked = []
for (const field of fields) {
switch (field.type) {
case 'structure':
case 'accumulator':
case 'inline':
field.fields = inquisition(field.fields)
checked.push(field)
break
case 'sip':
if (field.sip != null) {
field.sip = inquisition(field.sip)
}
for (const condition of field.conditions) {
condition.fields = inquisition(condition.fields)
}
checked.push(field)
break
case 'conditional':
if (field.parse.sip != null) {
field.parse.sip = inquisition(field.parse.sip)
}
for (const condition of field.parse.conditions) {
condition.fields = inquisition(condition.fields)
}
checked.push(field)
break
case 'switch':
for (const when of field.cases) {
when.fields = inquisition(when.fields)
}
checked.push(field)
break
case 'fixed':
if (field.fixed) {
checked.push({
type: 'checkpoint',
lengths: [ field.bits / 8 ],
vivify: null,
rewind: 0
})
checked.push(field)
} else {
if (field.calculated) {
field.fields = inquisition(field.fields, $I + 1)
} else {
field.fields = inquisition(field.fields, $I)
}
checked.push(field)
}
break
case 'calculation':
if (field.field.fields[0].fixed) {
checked.push(field)
checked.push({
type: 'checkpoint',
lengths: [ `$I[${$I}] * ${field.field.fields[0].bits >>> 3}` ],
vivify: null,
rewind: 0
})
} else {
checked.push(field)
}
break
case 'terminator':
checked.push({
type: 'checkpoint',
lengths: [ 0 ],
vivify: null,
rewind: 0
})
if (field.body.fields[field.body.fields.length - 1].type != 'buffer') {
checked[checked.length - 1].lengths[0] += field.body.terminator.length
}
checked.push(field)
break
case 'repeated':
field.fields = inquisition(field.fields)
checked.push(field)
break
case 'terminated':
if (field.fields[field.fields.length - 1].type != 'buffer') {
field.fields = inquisition(field.fields)
}
checked.push(field)
break
case 'lengthEncoded': {
const element = field.fields[field.fields.length - 1]
if (element.fixed) {
const bytes = element.bits / 8
checked.push({
type: 'checkpoint',
lengths: [ `${bytes} * $I[${$I}]` ],
vivify: null,
rewind: 0
})
} else {
field.fields = inquisition(field.fields, $I + 1)
}
checked.push(field)
}
break
case 'lengthEncoding':
if (field.body.encoding[0].fixed) {
checked.push({
type: 'checkpoint',
lengths: [ field.body.encoding[0].bits / 8 ],
vivify: null,
rewind: 0
})
} else {
field.body.encoding = inquisition(field.body.encoding, $I)
}
checked.push(field)
break
case 'literal':
case 'bigint':
case 'integer':
checked.push({
type: 'checkpoint',
lengths: [ field.bits / 8 ],
vivify: null,
rewind: 0
})
checked.push(field)
break
case 'buffer':
case 'absent':
checked.push(field)
break
default:
throw new Error(field.type)
}
}
return checked
}
function generate (packet, { require, bff, chk }) {
let $i = -1, $I = -1, $step = 1, $sip = -1
const { variables, accumulators, parameters } = declare(packet)
const inliner = Inliner({
variables, accumulators, parameters, packet,
direction: 'parse'
})
function signature () {
const signatories = {
packet: packet.name,
parameters: '{}',
step: $step,
i: '$i',
I: '$I',
sip: '$sip',
accumulator: '$accumulator',
starts: '$starts'
}
if (Object.keys(parameters).length != 0) {
const properties = []
for (const parameter in parameters) {
properties.push(`${parameter}: ${parameter}`)
}
signatories.parameters = $(`
{
`, properties.join(', '), `
}
`)
}
return Object.keys(signatories)
.filter(key => variables[key])
.map(key => signatories[key])
}
function checkpoint (checkpoint, depth) {
if (checkpoint.lengths.length == 0) {
return null
}
if (checkpoint.rewind != 0) {
return $(`
if ($end - ($start - ${checkpoint.rewind}) < ${checkpoint.lengths.join(' + ')}) {
return $incremental.${packet.name}(`, signature().join(', '), `)($buffer, $start - ${checkpoint.rewind}, $end)
}
`)
}
return $(`
if ($end - $start < ${checkpoint.lengths.join(' + ')}) {
return $incremental.${packet.name}(`, signature().join(', '), `)($buffer, $start, $end)
}
`)
}
function absent (path, field) {
$step++
return `${path} = ${util.inspect(field.value)}`
}
//
// Assign an integer value to a member of the parsed object. This is the
// generated source common to `number` and `BigInt`. First read the bits
// from the underlying byte buffer, then transform the value if it is a
// lookup value, packed integer or two's compliment.
function read (path, field, read) {
if (homogeneous(field)) {
$step += 2
} else {
$step += 1 + field.bytes.length
}
const variable = field.lookup || field.fields || field.compliment ? '$_' : path
const parse = $(`
${variable} `, read, `
`)
if (field.fields) {
return $(`
`, parse, `
`, unpack(inliner, packet, path, field, '$_'), `
`)
} else if (field.lookup) {
if (Array.isArray(field.lookup.values)) {
return $(`
`, parse, `
${path} = $lookup[${field.lookup.index}][$_]
`)
}
return $(`
`, parse, `
${path} = $lookup[${field.lookup.index}].forward[$_]
`)
}
if (field.compliment) {
variables.register = true
return $(`
`, parse, `
${path} = ${unsign(variable, field.bits)}
`)
}
return parse
}
//
// Read a `number` from the underlying buffer. Will create a standard
// JavaScript `number` in the constructed object.
function integer (path, field) {
const reads = []
for (let i = 0, I = field.bits / 8; i < I; i++) {
const { shift, upper, mask } = field.bytes[i]
const bits = '$buffer[$start++]'
const masked = upper != 0 ? `(${bits} & ${hex(mask)})` : bits
if (shift == 0n) {
reads.push(`${masked}`)
} else {
reads.push(`${masked} << ${shift}`)
}
}
if (reads.length == 1) {
return read(path, field, `= ${reads[0]}`)
}
if (reads.length < 4) {
return read(path, field, $(`
=
`,reads.join(' |\n') , `
`))
}
return read(path, field, $(`
= (
`,reads.join(' |\n') , `
) >>> 0
`))
}
//
// Read a `BigInt` from the underlying buffer. Will create a `BigInt`
// variable in the constructed object.
function bigint (path, field) {
const reads = []
for (let i = 0, I = field.bits / 8; i < I; i++) {
const { shift, upper, mask } = field.bytes[i]
const bits = `($buffer[$start++])`
const masked = upper != 0 ? `(${bits} & ${hex(mask)})` : bits
if (shift == 0n) {
reads.push(`BigInt${masked}`)
} else {
reads.push(`BigInt${masked} << ${shift}n`)
}
}
if (reads.length != 1) {
return read(path, field, $(`
=
`, reads.join(' |\n'), `
`))
}
return read(path, field, `= ${reads[0]}`)
}
function literal (path, field) {
function write (literal) {
if (literal.value.length != 0) {
$step += 2
}
if (literal.repeat == 0) {
return null
}
return $(`
$start += ${(literal.value.length >>> 1) * literal.repeat}
`)
}
return $(`
`, write(field.before), -1, `
`, map(dispatch, path, field.fields), `
`, -1, write(field.after), `
`)
}
function inline (path, field) {
const inline = inliner.inline(path, field.after)
if (inline.starts != null) {
$step++
variables.starts = true
}
return $(`
`, inline.starts, -1, `
`, map(dispatch, path, field.fields), `
`, -1, inline.inlined, `
`, -1, inliner.pop(), `
`)
}
function accumulator (path, field) {
$step++
variables.accumulator = true
return $(`
`, inliner.accumulator(field), `
`, map(dispatch, path, field.fields), `
`)
}
//
// **Length-encoded arrays**: First first the length of the array as an
// integer followed by the array elements in a loop.
//
// Parse the length of the array into a variable we can pass to an
// incremental parser during best-foot-forward parsing. We zero the loop
// index right after reading the length-encoding because if the array
// elements are fixed width, we're about to preform a best-foot-forward
// check that will jump to the loop body of an incremental parser.
function lengthEncoding (path, field) {
const element = field.body.fields[field.body.fields.length - 1]
const I = `$I[${++$I}]`
if (element.type == 'buffer') {
return map(dispatch, I, field.body.encoding)
}
return $(`
`, map(dispatch, I, field.body.encoding), `
$i[${++$i}] = 0
`)
}
function lengthEncoded (path, field) {
const element = field.fields[field.fields.length - 1]
const I = `$I[${$I}]`
if (element.type == 'buffer') {
$step++
$I--
// Slice the buffer straight out of the parsed buffer. Wrap it in an
// array if the buffers are chunked.
return element.concat ? $(`
${path} = $buffer.slice($start, $start + ${I})
$start += ${I}
`) : $(`
${path} = [ $buffer.slice($start, $start + ${I}) ]
$start += ${I}
`)
}
// Loop overt the elements in an array running byte-by-byte parsers to
// create each element. Indices can be passed to an incremental during
// best-foot-forward parsing.
const i = `$i[${$i}]`
// Skip index initialization.
$step++
const vivification = vivify.assignment(`${path}[${i}]`, field)
// Step to skip incremental parser's vivification of the array element.
if (vivification != null) {
$step++
}
const source = $(`
for (; ${i} < ${I}; ${i}++) {
`, vivification, -1, `
`, map(dispatch, `${path}[${i}]`, field.fields), `
}
`)
$i--
$I--
return source
}
function terminated (path, field) {
const element = field.fields.slice().pop().fields.slice().pop()
if (element.type == 'buffer') {
const terminator = field.terminator
const assign = element.concat
? `${path} = $buffer.slice($start, $_)`
: `${path} = [ $buffer.slice($start, $_) ]`
if (bff || chk) {
const source = $(`
$_ = $buffer.indexOf(Buffer.from(${util.inspect(terminator)}), $start)
if (~$_) {
`, assign, `
$start = $_ + ${terminator.length}
} else {
return $incremental.${packet.name}(${signature().join(', ')})($buffer, $start, $end)
}
`)
$step += 2 + terminator.length
return source
}
// TODO What if you don't find? Here we create zero buffer.
return $(`
$_ = $buffer.indexOf(Buffer.from(${util.inspect(terminator)}), $start)
$_ = ~$_ ? $_ : $start
`, assign, `
$start = $_ + ${terminator.length}
`)
}
// Skip initialization of index.
$step++
variables.i = true
$i++
const looped = map(dispatch, path, field.fields)
const source = $(`
$i[${$i}] = 0
for (;;) {
`, looped, `
}
`)
$i--
return source
}
//
// Generate the body of a terminated array.
//
// We skip skip vivification on best-foot-forward because we perform it in
// the synchronous parser. We also skip the final step which is an empty
// step that the incremental parse uses as an exit target.
function repeated (path, field) {
const i = `$i[${$i}]`
const vivified = vivify.assignment(path + `[${i}]`, field)
if (vivified != null) {
$step++
}
const looped = map(dispatch, `${path}[${i}]`, field.fields)
$step += 2
return $(`
`, vivified, -1, `
`, looped, `
${i}++
`)
}
function terminator (field) {
$step += field.body.terminator.length
// TODO We really do not want to go beyond the end of the buffer in a
// whole parser and loop forever, so we still need the checkpoints. The
// same goes for length encoded. We don't want a malformed packet to
// cause an enormous loop. Checkpoints for loops only?
//
// TODO The above is for documentation. You can have the essence of a
// serializer, but you should always use a best-foot-forward parser to
// guard against evil coming in from the outside.
//
// TODO When the type is integer and the same size as the terminator
// lets create an integer sentry.
//
// TODO No, it's simple really. We don't need checked whole serializers,
// but all parsers should be checked somehow. You don't have to worry
// about running forever, because you can limit the file size, buffer
// size. Perhaps we have upper limits on arrays, sure. Add that to the
// langauge somehow, but we shouldn't have unchecked parsers. We use the
// `bff` logic and return an error if it doesn't fit.
const terminator = field.body.terminator.map((bite, index) => {
if (index == 0) {
return `$buffer[$start] == 0x${bite.toString(16)}`
} else {
return `$buffer[$start + ${index}] == 0x${bite.toString(16)}`
}
})
return $(`
if (
`, terminator.join(' &&\n'), `
) {
$start += ${terminator.length}
break
}
`)
}
function calculation (path, { field }) {
return $(`
$I[${++$I}] = `, inliner.test(path, field.length), `
`)
}
function fixed (path, field) {
const length = field.calculated ? `$I[${$I}]` : field.length
// Fetch the type of element.
const element = field.fields[field.fields.length - 1]
//
// Buffers can use `indexOf`, `fill` and `copy` and will be much faster
// than operating byte-by-byte.
//
if (element.type == 'buffer') {
variables.register = true
variables.slice = true
// Advance past buffer read to padding skip.
$step += field.pad.length == 0 ? 2 : 3
if (field.calculated) {
$I--
}
const slice = $(`
$slice = $buffer.slice($start, $start + ${length})
$start += ${length}
`)
const assign = element.concat ? `${path} = $slice` : `${path} = [ $slice ]`
if (field.pad.length != 0) {
$step += field.pad.length
const pad = field.pad.length > 1
? `Buffer.from(${util.format(field.pad)})`
: field.pad[0]
return ($(`
`, slice, `
$_ = $slice.indexOf(${pad})
if (~$_) {
$slice = $slice.slice(0, $_)
}
`, assign, `
`))
}
// See: https://marcradziwill.com/blog/mastering-javascript-high-performance/
return ($(`
`, slice, `
`, assign, `
`))
}
variables.i = true
const i = `$i[${++$i}]`
$step += 1
const check = bff && field.pad.length != 0
? checkpoint({ lengths: [ field.pad.length ], rewind: 0 })
: null
// Advance past initialization and terminator tests.
$step += 1 + field.pad.length
const looped = map(dispatch, path + `[${i}]`, field.fields)
// Advance past end-of-loop test and fill skip.
const vivified = vivify.assignment(`${path}[${i}]`, field)
if (vivified != null) {
$step++
}
$step += (field.pad.length != 0 ? 2 : 0)
const terminator = field.pad.map((bite, index) => {
if (index == 0) {
return `$buffer[$start] == ${hex(bite)}`
} else {
return `$buffer[$start + ${index}] == ${hex(bite)}`
}
})
const terminate = terminator.length != 0
? $(`
if (
`, terminator.join(' &&\n'), `
) {
$start += ${terminator.length}
break
}
`)
: null
let source = null
if (field.calculated) {
source = $(`
${i} = 0
do {
`, check, -1, `
`, terminate, -1, `
`, vivify.assignment(`${path}[${i}]`, field), -1, `
`, looped, `
} while (++${i} != ${length})
`)
$I--
} else {
source = $(`
${i} = 0
do {
`, check, -1, `
`, terminate, -1, `
`, vivify.assignment(`${path}[${i}]`, field), -1, `
`, looped, `
} while (++${i} != ${length})
`)
}
$i--
if (terminator.length) {
const element = field.fields[field.fields.length - 1]
return $(`
`, source, `
$start += ${length} != ${i}
? (${length} - ${i}) * ${element.bits >>> 3} - ${field.pad.length}
: 0
`)
}
return source
}
function rewind (field) {
return $(`
$start -= ${field.bytes}
`)
}
function switched (path, field) {
$step++
const cases = []
for (const when of field.cases) {
const vivified = vivify.assignment(path, when)
cases.push($(`
${when.otherwise ? 'default' : `case ${util.inspect(when.value)}`}:
`, vivified, -1, `
`, map(dispatch, path, when.fields), `
break
`))
}
const invocations = inliner.accumulations([ field.select ])
return $(`
`, invocations, -1, `
switch (`, inliner.test(path, field.select), `) {
`, join(cases), `
}
`)
}
function conditional (path, field, rewound = 0) {
if (field.parse.unconditional) {
return map(dispatch, path, field.parse.conditions[0].fields)
}
const tests = field.parse.conditions.filter(condition => condition.test != null)
.map(condition => condition.test)
const invocations = inliner.accumulations(tests)
const signature = []
const sip = function () {
if (field.parse.sip == null) {
return null
}
// TODO Decrement `$sip[]`.
const sip = `$sip[${++$sip}]`
signature.push(sip)
return map(dispatch, sip, field.parse.sip)
} ()
$step++
let ladder = '', keywords = 'if'
for (let i = 0, I = field.parse.conditions.length; i < I; i++) {
const condition = field.parse.conditions[i]
const rewind = function () {
if (field.parse.sip == null) {
return null
}
const sip = field.parse.sip[field.parse.sip.length - 1]
let sipped = sip.bits / 8
LITERALS: for (let j = 0, J = condition.fields.length; sipped != 0 && j < J; j++) {
switch (condition.fields[j].type) {
case 'literal':
const before = condition.fields[j].before
let advance = Math.min(sipped, before.value.length / 2 * before.repeat)
sipped -= advance
if (advance >= before.value.length / 2) {
const remove = Math.floor(advance / (before.value.length / 2))
advance -= remove
before.repeat -= remove
}
if (advance != 0) {
before.splice(0, advance * 2)
}
break
case 'absent':
case 'checkpoint':
break
default:
break LITERALS
}
}
const checkpoint = condition.fields[0].type == 'checkpoint'
if (sipped != 0) {
condition.fields.splice(checkpoint ? 1 : 0, 0, {
type: 'rewind', bytes: sipped + rewound
})
}
if (checkpoint) {
condition.fields[0].rewind = sip.bits / 8 + rewound
}
} ()
const vivified = vivify.assignment(path, condition)
let source = null
if (condition.fields[condition.fields.length - 1].type == 'sip') {
const parse = condition.fields.pop()
const rewind = condition.fields.pop()
source = conditional(path, { parse }, rewind.bytes)
} else {
source = map(dispatch, path, condition.fields)
}
ladder = condition.test != null ? $(`
`, ladder, `${keywords} (`, inliner.test(path, condition.test, signature), `) {
`, vivified, -1, `
`, source, `
}
`) : $(`