1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
//! The one parser of the base grammar (GRAMMAR.md). It walks a buffer,
//! fails on the first structural error, builds the document model with
//! dead elements dropped, notes every canonical violation when asked, and
//! counts the dead elements met in bodies for tools above the format.
//! [`Body`], [`Document`], [`Container`], [`Validator`] and the stream
//! reader are all built on it.
//!
//! Body level is a flat state machine over lines (file line, group line,
//! header row, record, note, commit); records and their values are
//! recursive, since a level holds a body.
use crate::*;
use std::borrow::Cow;
use std::collections::HashMap;
pub struct Parser<'a> {
buf: &'a [u8],
canonical: bool,
ok: bool,
warnings: Vec<&'static str>,
dead_elements: usize,
// Regions to jump over at a block boundary, start => end: the damaged
// blocks of a stream (see StreamReader).
skip: Option<HashMap<usize, usize>>,
}
impl<'a> Parser<'a> {
/// A parser over `buf`. With `canonical` it also records every
/// canonical violation (see [`Parser::warnings`]).
pub fn new(buf: &'a [u8], canonical: bool) -> Self {
Parser {
buf,
canonical,
ok: true,
warnings: Vec::new(),
dead_elements: 0,
skip: None,
}
}
/// A parser that jumps over the given regions (`start => end`).
pub(crate) fn with_skip(buf: &'a [u8], skip: HashMap<usize, usize>) -> Self {
let mut p = Parser::new(buf, false);
p.skip = Some(skip);
p
}
/// Whether nothing non-canonical has been met.
pub fn ok(&self) -> bool {
self.ok
}
/// Canonical violations met, one entry per finding.
pub fn warnings(&self) -> &[&'static str] {
&self.warnings
}
/// Dead elements met in bodies (the heading's dead keys are not counted).
pub fn dead_elements(&self) -> usize {
self.dead_elements
}
pub(crate) fn not_canonical(&mut self, why: &'static str) {
self.ok = false;
self.warnings.push(why);
}
// Jump over skipped regions beginning at pos.
#[inline]
fn skip(&self, mut pos: usize) -> usize {
if let Some(s) = &self.skip {
while let Some(&e) = s.get(&pos) {
pos = e;
}
}
pos
}
/// Skip layout (and skipped regions). Layout is a canonical violation.
pub(crate) fn layout(&mut self, pos: usize, stop: usize) -> usize {
let pos = self.skip(pos);
let p2 = scan::layout(self.buf, pos, stop);
if p2 != pos {
self.not_canonical("layout bytes");
}
self.skip(p2)
}
// ---- heading --------------------------------------------------------
/// After SYN. Returns the heading (dead keys dropped, duplicates kept)
/// and the position of the first body code.
pub fn heading(&mut self, mut pos: usize, stop: usize) -> Result<(Heading<'a>, usize)> {
let buf = self.buf;
let hs = pos;
let mut pairs: Vec<(&'a [u8], Cow<'a, [u8]>)> = Vec::new();
let mut raw_pairs: Vec<(&'a [u8], &'a [u8])> = Vec::new();
loop {
pos = self.layout(pos, stop);
if pos >= stop {
break;
}
let b = buf[pos];
if b == SOH {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 < stop && buf[p2] == RS {
break; // a header row begins the body
}
let (key, vs, p) = self.keyed_unit(pos + 1, stop, true)?;
pos = p;
self.heading_pair(&mut pairs, &mut raw_pairs, key, trim(&buf[vs..pos]), vs)?;
} else if b == BEL {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 >= stop {
return Err(Error::end("BEL at end of input", p2));
}
let c = buf[p2];
if c == SOH {
let p3 = scan::layout(buf, p2 + 1, stop);
if p3 < stop && buf[p3] == RS {
break; // a dead header row begins the body
}
self.not_canonical("dead element");
let (_key, _vs, p) = self.keyed_unit(p2 + 1, stop, true)?;
pos = p;
} else if c >= 0x20 || c == STX {
self.not_canonical("comment");
pos = self.note_content(p2, stop)?;
} else if matches!(c, RS | GS | FS | DLE) {
break; // a dead body element
} else {
return Err(Error::syntax(
"BEL before a code that is not an element",
p2,
));
}
} else if b == SUB {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 >= stop {
return Err(Error::syntax("SUB at the end of input", pos));
}
if buf[p2] == US {
return Err(Error::syntax("the heading's values take no sub-units", pos));
}
break; // SUB before a body code: the body's business
} else if b >= 0x20 {
return Err(Error::syntax("plain text directly after SYN", pos));
} else {
break;
}
}
Ok((Heading::new(&buf[hs..pos], pairs, raw_pairs), pos))
}
fn heading_pair(
&mut self,
pairs: &mut Vec<(&'a [u8], Cow<'a, [u8]>)>,
raw_pairs: &mut Vec<(&'a [u8], &'a [u8])>,
key: &'a [u8],
rawv: &'a [u8],
at: usize,
) -> Result<()> {
raw_pairs.push((key, rawv));
let v = if rawv.first() == Some(&DLE) {
Cow::Borrowed(rawv)
} else {
value(rawv)?
};
pairs.push((key, v));
if key == b"schema" {
self.check_schema(rawv, at)?;
}
Ok(())
}
// The `schema` key: a plain name, or a level holding one keyed record
// whose keys are drawn from name, url and hash (DESIGN.md, Start).
fn check_schema(&mut self, rawv: &'a [u8], at: usize) -> Result<()> {
let t = trim(rawv);
let Some(&first) = t.first() else {
return Err(Error::syntax("schema needs a value", at));
};
if first == DLE {
let body = Body::of_level(t)?;
if !(body.bare() && body.records().len() == 1) {
return Err(Error::syntax("a schema level holds one keyed record", at));
}
let rec = body.record(0);
if !rec.keyed() {
return Err(Error::syntax(
"a schema level holds a keyed record, not a positional one",
at,
));
}
let pairs = rec.pairs()?;
if pairs.is_empty() {
return Err(Error::syntax("a schema record needs name, url or hash", at));
}
for (k, v) in &pairs {
if !matches!(*k, b"name" | b"url" | b"hash") {
return Err(Error::syntax(
format!("unknown schema key '{}'", String::from_utf8_lossy(k)),
at,
));
}
if v.is_empty() || !is_name(v) {
return Err(Error::syntax(
format!("a schema {} is a name", String::from_utf8_lossy(k)),
at,
));
}
}
} else if first == STX {
return Err(Error::syntax("a schema name cannot be text", at));
} else {
let v = value(t)?;
if v.is_empty() || !is_name(&v) {
return Err(Error::syntax("a schema name is a name", at));
}
}
Ok(())
}
// ---- body -----------------------------------------------------------
/// A body from pos to stop. At depth zero (`level` false) commits are
/// legal and the body ends at EOT, SYN, EM or stop; in a level it ends
/// at CAN. Returns the files (dead elements dropped) and the position
/// of the code that ended the body.
pub fn body(
&mut self,
mut pos: usize,
stop: usize,
level: bool,
) -> Result<(Vec<FileView<'a>>, usize)> {
let buf = self.buf;
let mut files: Vec<FileView<'a>> = Vec::new();
let mut file = FileView::new(buf, 0, 0, true);
let mut group = Group::new(buf, 0, 0, 0); // the unnamed group
let mut group_live = true; // whether `group` joins its file when it ends
let mut header_ok = true; // a header row may still begin this group
let mut dead_file = false; // inside a dead file: everything to the next file line is discarded
let mut dead_depth: Option<usize> = None; // inside a dead group of this depth
let mut dead = false; // BEL seen: the next element is dead
let mut prefix = 0usize; // SUB run read before a GS: the subsection's depth less one
let mut prev_depth = 0usize; // depth of the group line before, as written (dead or not)
let mut mark_at = pos; // position of that BEL, for errors
// A group joins its file when it ends: a named one always, the
// unnamed one once it has content.
fn flush<'b>(file: &mut FileView<'b>, group: Group<'b>, live: bool) {
if live && (group.depth > 0 || group.header.is_some() || !group.records.is_empty()) {
file.groups.push(group);
}
}
loop {
pos = self.layout(pos, stop);
if pos >= stop {
break;
}
let b = buf[pos];
match b {
RS => {
let (rec, p) = self.record(pos + 1, stop)?;
pos = p;
if dead {
self.dead_elements += 1;
} else {
group.records.push(rec);
header_ok = false;
}
dead = false;
}
SOH => {
let p2 = scan::layout(buf, pos + 1, stop);
if !(p2 < stop && buf[p2] == RS) {
return Err(Error::syntax("keyed unit outside a record", pos));
}
if !header_ok {
return Err(Error::syntax(
"header row not at the start of its group",
pos,
));
}
let (hdr, p) = self.header_row(p2 + 1, stop)?;
pos = p;
if dead {
self.dead_elements += 1;
} else {
group.header = Some(hdr);
header_ok = false;
}
dead = false;
}
GS => {
// depth is one plus the SUB prefix; a skip is measured
// against the group line before, as written, dead or not
let depth = 1 + prefix;
prefix = 0;
if depth > prev_depth + 1 {
return Err(Error::syntax(
"depth skipped: a group is at most one deeper than the group line before it",
pos,
));
}
prev_depth = depth;
let (ns, ne, p) = self.name(pos + 1, stop)?;
pos = p;
let done = std::mem::replace(&mut group, Group::new(buf, depth, ns, ne));
flush(&mut file, done, group_live);
if dead_depth.is_some_and(|dd| depth <= dd) {
dead_depth = None; // the dead group's span ends here
}
if dead {
self.dead_elements += 1;
if !dead_file && dead_depth.is_none() {
dead_depth = Some(depth);
}
group_live = false; // a dead group is parsed, never attached
} else {
group_live = !(dead_file || dead_depth.is_some());
}
header_ok = true;
dead = false;
}
FS => {
let (ns, ne, p) = self.name(pos + 1, stop)?;
pos = p;
let done = std::mem::replace(&mut group, Group::new(buf, 0, 0, 0));
flush(&mut file, done, group_live);
// close the current file: an empty leading file is
// dropped when a file line follows it
let done = std::mem::replace(&mut file, FileView::new(buf, ns, ne, false));
if !(dead_file || (done.leading && done.groups.is_empty())) {
files.push(done);
}
if dead {
self.dead_elements += 1;
dead_file = true;
} else {
dead_file = false;
}
group_live = !dead_file;
dead_depth = None;
prev_depth = 0; // FS restarts the depth count
header_ok = true;
dead = false;
}
BEL => {
if dead {
return Err(Error::syntax(
"BEL before a code that is not an element",
pos,
));
}
let p2 = scan::layout(buf, pos + 1, stop);
if p2 >= stop {
return Err(Error::end("BEL at end of input", p2));
}
let c = buf[p2];
if c >= 0x20 || c == STX {
self.not_canonical("comment");
pos = self.note_content(p2, stop)?;
} else if matches!(c, RS | SOH | GS | FS) {
self.not_canonical("dead element");
dead = true;
mark_at = pos;
pos = p2;
} else if c == SUB {
// BEL kills a group line whole, its SUB prefix included
let mut p3 = p2;
while p3 < stop && buf[p3] == SUB {
p3 = scan::layout(buf, p3 + 1, stop);
}
if p3 < stop && buf[p3] == GS {
self.not_canonical("dead element");
dead = true;
mark_at = pos;
pos = p2;
} else if p3 < stop && buf[p3] == US {
return Err(Error::syntax(
"BEL before a sub-unit: a unit cannot be dead",
pos,
));
} else {
return Err(Error::syntax(
"BEL before a code that is not an element",
p2,
));
}
} else if c == DLE {
return Err(Error::syntax("a nested level is not an item", p2));
} else {
return Err(Error::syntax(
"BEL before a code that is not an element",
p2,
));
}
}
SUB => {
// A run of SUB before GS is the subsection's depth prefix;
// before RS, FS or SOH it is reserved; a sub-unit (SUB US)
// lives inside a record and never reaches here.
let start = pos;
let mut run = 0usize;
while pos < stop && buf[pos] == SUB {
run += 1;
pos = self.layout(pos + 1, stop);
}
if pos >= stop {
return Err(Error::syntax("SUB at the end of input", start));
}
match buf[pos] {
GS => prefix = run,
RS => {
return Err(Error::syntax(
"SUB before RS is reserved (a sub-record)",
start,
))
}
FS => {
return Err(Error::syntax(
"SUB before FS is reserved (a sub-file)",
start,
))
}
SOH => {
return Err(Error::syntax(
"SUB before SOH is reserved (a sub-key); a header row admits none",
start,
))
}
US => return Err(Error::syntax("US outside a record", pos)),
BEL => return Err(Error::syntax("SUB before BEL", start)),
_ => {
return Err(Error::syntax(
"SUB before a byte that is not a separator",
start,
))
}
}
}
ETB => {
if level {
return Err(Error::syntax("commit inside a nested level", pos));
}
if dead {
return Err(Error::syntax(
"BEL before ETB: framing cannot be commented out",
mark_at,
));
}
self.not_canonical("commit");
let p = self.layout(pos + 1, stop);
pos = scan::plain(buf, p, stop);
}
EOT | SYN | EM => {
if level {
return Err(Error::syntax("framing inside open level", pos));
}
if dead {
return Err(Error::syntax("BEL before framing", mark_at));
}
break;
}
CAN => {
if !level {
return Err(Error::syntax("CAN with no open level", pos));
}
if dead {
return Err(Error::syntax("BEL before CAN", mark_at));
}
break;
}
US => return Err(Error::syntax("US outside a record", pos)),
STX => return Err(Error::syntax("text outside a record", pos)),
DLE => return Err(Error::syntax("a nested level is not an item", pos)),
ENQ => return Err(Error::syntax("a reference outside a record", pos)),
_ => {
if b >= 0x20 {
return Err(Error::syntax("plain text outside a record", pos));
}
return Err(Error::UnassignedCode {
byte: b,
position: pos,
});
}
}
}
flush(&mut file, group, group_live);
if !(dead_file || (file.leading && file.groups.is_empty() && !files.is_empty())) {
files.push(file);
}
// a body whose every element is dead is an empty body: one empty
// leading file, so there is always a file to report
if files.is_empty() {
files.push(FileView::new(buf, 0, 0, true));
}
Ok((files, pos))
}
// A label or path: plain, never text. Returns (name start, name end, pos).
fn name(&mut self, pos: usize, stop: usize) -> Result<(usize, usize, usize)> {
let buf = self.buf;
let pos = self.layout(pos, stop);
if pos < stop && buf[pos] == STX {
return Err(Error::syntax("a name cannot be text", pos));
}
let ns = pos;
let pos = scan::plain(buf, pos, stop);
let mut ne = pos;
while ne > ns && is_layout(buf[ne - 1]) {
ne -= 1;
}
if ne != pos {
self.not_canonical("layout bytes");
}
Ok((ns, ne, pos))
}
// After SOH RS: names, each followed by notes, separated by US.
fn header_row(&mut self, mut pos: usize, stop: usize) -> Result<(Record<'a>, usize)> {
let buf = self.buf;
let start = pos;
loop {
let (_ns, _ne, p) = self.name(pos, stop)?;
let p = self.layout(p, stop);
pos = self.trailing_notes(p, stop)?;
if !(pos < stop && buf[pos] == US) {
break;
}
pos += 1;
}
if pos < stop && buf[pos] == SUB {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 < stop && buf[p2] == US {
return Err(Error::syntax("a header row admits no sub-units", pos));
}
}
Ok((Record::new(buf, start, trim_end(buf, start, pos)), pos))
}
// ---- records --------------------------------------------------------
/// After RS. Returns the record and the position after it.
pub fn record(&mut self, pos: usize, stop: usize) -> Result<(Record<'a>, usize)> {
let start = pos;
let pos = if self.keyed_start(pos, stop)? {
self.keyed(pos, stop)?
} else {
self.positional(pos, stop)?
};
Ok((
Record::new(self.buf, start, trim_end(self.buf, start, pos)),
pos,
))
}
// Does the record starting here begin with a keyed unit, live or dead?
fn keyed_start(&self, mut pos: usize, stop: usize) -> Result<bool> {
let buf = self.buf;
loop {
pos = scan::layout(buf, pos, stop);
if pos >= stop {
return Ok(false);
}
let b = buf[pos];
if b == SOH {
let p2 = scan::layout(buf, pos + 1, stop);
return Ok(!(p2 < stop && buf[p2] == RS));
} else if b == BEL {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 >= stop {
return Ok(false);
}
let c = buf[p2];
if c == SOH {
let p3 = scan::layout(buf, p2 + 1, stop);
return Ok(!(p3 < stop && buf[p3] == RS));
}
if !(c >= 0x20 || c == STX) {
return Ok(false);
}
pos = self.note_content(p2, stop)?; // a note: look past it
} else {
return Ok(false);
}
}
}
fn positional(&mut self, mut pos: usize, stop: usize) -> Result<usize> {
let buf = self.buf;
loop {
pos = self.value(pos, stop, false)?;
pos = self.sub_units(pos, stop)?;
pos = self.layout(pos, stop);
if pos >= stop {
break;
}
let b = buf[pos];
if b == US {
pos += 1;
} else if b == SUB {
break; // a prefix before the next line: the body's business
} else if b == SOH {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 < stop && buf[p2] == RS {
break; // a header row ends the record
}
return Err(Error::syntax(
"keyed unit in a positional record (mixed record)",
pos,
));
} else {
break;
}
}
Ok(pos)
}
fn keyed(&mut self, mut pos: usize, stop: usize) -> Result<usize> {
let buf = self.buf;
let mut keys: Vec<&'a [u8]> = Vec::new(); // the result's keys
loop {
pos = self.layout(pos, stop);
if pos >= stop {
break;
}
let b = buf[pos];
if b == SOH {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 < stop && buf[p2] == RS {
break;
}
let (key, _vs, p) = self.keyed_unit(pos + 1, stop, false)?;
pos = self.sub_units(p, stop)?;
keys.push(key);
} else if b == BEL {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 >= stop {
return Err(Error::end("BEL at end of input", p2));
}
let c = buf[p2];
if c == SOH {
let p3 = scan::layout(buf, p2 + 1, stop);
if p3 < stop && buf[p3] == RS {
break;
}
self.not_canonical("dead element");
let (_key, _vs, p) = self.keyed_unit(p2 + 1, stop, false)?;
pos = self.sub_units(p, stop)?; // a dead keyed unit takes its sub-units
} else if c >= 0x20 || c == STX {
pos = self.trailing_notes(pos, stop)?;
} else if c == SUB {
return Err(Error::syntax(
"BEL before a sub-unit: a unit cannot be dead",
p2,
));
} else {
break;
}
} else if b == SUB {
break; // a prefix before the next line: the body's business
} else {
break;
}
}
if pos < stop && buf[pos] == US {
return Err(Error::syntax("US after a keyed value (mixed record)", pos));
}
for (i, k) in keys.iter().enumerate() {
if keys[..i].contains(k) {
self.not_canonical("duplicate key");
break;
}
}
Ok(pos)
}
// After SOH (not a header row). Returns (key, value start, pos after the value).
fn keyed_unit(
&mut self,
pos: usize,
stop: usize,
heading: bool,
) -> Result<(&'a [u8], usize, usize)> {
let buf = self.buf;
let (ks, ke, pos) = self.name(pos, stop)?;
if !(pos < stop && buf[pos] == US) {
return Err(Error::syntax("key without a value (no US)", pos));
}
let vs = pos + 1;
let pos = self.value(vs, stop, heading)?;
Ok((&buf[ks..ke], vs, pos))
}
// The sub-units after a unit's value: runs of SUB then US then a value,
// each run's length the sub-unit's depth, at most one deeper than the
// sub-unit before it. Returns the position after the last; a SUB run
// that prefixes a line code is left for the body, a reserved grain fails.
fn sub_units(&mut self, mut pos: usize, stop: usize) -> Result<usize> {
let buf = self.buf;
let mut prev = 0usize;
loop {
let mut p = self.layout(pos, stop);
if !(p < stop && buf[p] == SUB) {
return Ok(pos);
}
let start = p;
let mut run = 0usize;
while p < stop && buf[p] == SUB {
run += 1;
p = self.layout(p + 1, stop);
}
if p >= stop {
return Err(Error::syntax("SUB at the end of input", start));
}
match buf[p] {
US => {
if run > prev + 1 {
return Err(Error::syntax(
"depth skipped: a sub-unit is at most one deeper than the sub-unit before it",
start,
));
}
prev = run;
pos = self.value(p + 1, stop, false)?;
}
RS | GS | FS => return Ok(pos), // the body's business
SOH => {
let p2 = scan::layout(buf, p + 1, stop);
if p2 < stop && buf[p2] == RS {
return Err(Error::syntax("a header row admits no SUB", start));
}
return Err(Error::syntax(
"SUB before SOH is reserved (a sub-key)",
start,
));
}
BEL => return Err(Error::syntax("SUB before BEL", start)),
_ => {
return Err(Error::syntax(
"SUB before a byte that is not a separator",
start,
))
}
}
}
}
// ---- values ---------------------------------------------------------
// One unit's value, possibly empty, with the notes after it. Returns
// the position of the next code at this depth.
fn value(&mut self, pos: usize, stop: usize, heading: bool) -> Result<usize> {
let buf = self.buf;
let pos = self.layout(pos, stop);
if pos >= stop {
return Ok(pos);
}
let b = buf[pos];
let pos = if b >= 0x20 {
let p = scan::plain(buf, pos, stop);
if buf[p - 1] == SP {
self.not_canonical("layout bytes");
}
p
} else if b == STX {
let start = pos;
let p = scan::text(buf, pos, stop)?;
if self.canonical {
let inside = &buf[start + 1..p - 1];
if inside.is_empty() {
self.not_canonical("empty text");
} else if is_plain(&decode_text(inside)) {
self.not_canonical("gratuitous text");
}
}
p
} else if b == DLE {
let (_files, p) = self.level(pos, stop)?;
p
} else if b == ENQ {
if heading {
return Err(Error::syntax("reference in a heading", pos));
}
let (_r, p) = self.reference(pos, stop)?;
p
} else if b == BEL {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 >= stop {
return Err(Error::end("BEL at end of input", p2));
}
let c = buf[p2];
if c == DLE {
self.not_canonical("dead element"); // a dead level: the unit is empty
let (_files, p) = self.level(p2, stop)?;
p
} else if c >= 0x20 || c == STX {
let p = self.trailing_notes(pos, stop)?;
if self.value_start(p, stop) {
return Err(Error::syntax("value after a note in the same unit", p));
}
return Ok(p);
} else {
return Ok(pos); // a dead element after this empty unit: the caller's business
}
} else {
return Ok(pos); // an empty unit
};
let p = self.layout(pos, stop);
let after = self.trailing_notes(p, stop)?;
if self.value_start(after, stop) {
return Err(Error::syntax("two values in one unit", after));
}
Ok(after)
}
#[inline]
fn value_start(&self, pos: usize, stop: usize) -> bool {
if pos >= stop {
return false;
}
let b = self.buf[pos];
b >= 0x20 || b == STX || b == DLE || b == ENQ
}
// The content of a note, from the byte after BEL and layout.
fn note_content(&self, pos: usize, stop: usize) -> Result<usize> {
if self.buf[pos] == STX {
scan::text(self.buf, pos, stop)
} else {
Ok(scan::plain(self.buf, pos, stop))
}
}
// Notes after a value. A BEL before a code is left for the caller.
fn trailing_notes(&mut self, mut pos: usize, stop: usize) -> Result<usize> {
let buf = self.buf;
while pos < stop && buf[pos] == BEL {
let p2 = scan::layout(buf, pos + 1, stop);
if p2 >= stop {
return Err(Error::end("BEL at end of input", p2));
}
let c = buf[p2];
if !(c >= 0x20 || c == STX) {
break;
}
self.not_canonical("comment");
let p = self.note_content(p2, stop)?;
pos = self.layout(p, stop);
}
Ok(pos)
}
/// DLE at pos: a nested level. Returns its files and the position after CAN.
pub fn level(&mut self, pos: usize, stop: usize) -> Result<(Vec<FileView<'a>>, usize)> {
let buf = self.buf;
let start = pos;
let pos = self.layout(pos + 1, stop);
if pos >= stop {
return Err(Error::end(
format!("level opened at {start} is not closed"),
pos,
));
}
let b = buf[pos];
if b == CAN {
return Ok((vec![FileView::new(buf, 0, 0, true)], pos + 1));
}
if !matches!(b, FS | GS | RS | SOH | BEL | SUB) {
return Err(Error::syntax(
"DLE must be followed by a structural code",
pos,
));
}
let (files, pos) = self.body(pos, stop, true)?;
let pos = self.layout(pos, stop);
if pos >= stop {
return Err(Error::end(
format!("level opened at {start} is not closed"),
pos,
));
}
if buf[pos] != CAN {
return Err(Error::syntax("unexpected byte inside level", pos));
}
Ok((files, pos + 1))
}
/// ENQ at pos: a group name, or a pattern (DESIGN.md, References).
/// Returns the reference and the position after it.
pub fn reference(&mut self, pos: usize, stop: usize) -> Result<(Reference<'a>, usize)> {
let buf = self.buf;
let at = pos;
let pos = self.layout(pos + 1, stop);
if pos >= stop {
return Err(Error::syntax("reference without a name", at));
}
let b = buf[pos];
if b == DLE {
let dead0 = self.dead_elements;
let (files, after) = self.level(pos, stop)?;
if self.dead_elements != dead0 {
return Err(Error::syntax(
"a dead element is not a step of a pattern",
pos,
));
}
let body = Body::from_parts(buf, pos + 1, after - 1, files);
self.check_pattern(&body, pos, false)?;
Ok((Reference::new(None, Some(body)), after))
} else if b == STX {
Err(Error::syntax(
"a reference is a name or a pattern, not text",
pos,
))
} else if b >= 0x20 {
let (ns, ne, p) = self.name(pos, stop)?;
if ne == ns {
return Err(Error::syntax("reference without a name", at));
}
Ok((Reference::new(Some(&buf[ns..ne]), None), p))
} else {
Err(Error::syntax("reference without a name", at))
}
}
// A pattern is one branch of the target with its values left out.
// `inner` is a pattern continued into a level, whose records may stand
// in the unnamed group.
fn check_pattern(&mut self, body: &Body<'a>, at: usize, inner: bool) -> Result<()> {
let files = body.files();
if files.len() > 1 {
return Err(Error::syntax("a pattern is one branch: two files", at));
}
let groups = files[0].groups();
if groups.is_empty() {
return Err(Error::syntax(
if inner {
"an empty level continues nothing"
} else {
"an empty level is not a reference"
},
at,
));
}
if !inner && groups[0].depth() == 0 {
return Err(Error::syntax(
"a pattern begins with a file or group line",
at,
));
}
let mut prev: Option<usize> = None;
for (i, g) in groups.iter().enumerate() {
if g.has_header() {
return Err(Error::syntax("a header row is not a step of a pattern", at));
}
if prev.is_some_and(|p| g.depth() <= p) {
return Err(Error::syntax(
"a pattern is one branch: two groups at one depth",
at,
));
}
prev = Some(g.depth());
if i < groups.len() - 1 && !g.records().is_empty() {
return Err(Error::syntax("nothing follows the record in a pattern", at));
}
}
let recs = groups[groups.len() - 1].records();
if recs.len() > 1 {
return Err(Error::syntax("a pattern is one branch: two records", at));
}
let Some(rec) = recs.first() else {
if !inner {
self.not_canonical("group reference written as a pattern");
}
return Ok(());
};
// `fields` and `pairs` hide sub-units, so look for them explicitly
if rec.has_sub_units() {
return Err(Error::syntax("a sub-unit is not a step of a pattern", at));
}
if rec.keyed() {
let pairs = rec.pairs()?;
if pairs.len() != 1 {
return Err(Error::syntax(
"a keyed record in a pattern holds one keyed unit",
at,
));
}
if !pairs[0].1.is_empty() {
return Err(Error::syntax("a keyed unit in a pattern has no value", at));
}
if pairs[0].0.is_empty() || !is_name(pairs[0].0) {
return Err(Error::syntax("a step of a pattern is a name", at));
}
return Ok(());
}
let units = rec.fields();
if units.len() > 3 {
return Err(Error::syntax(
"a pattern record holds at most a record id, a field name and a level",
at,
));
}
for (i, raw) in units.iter().enumerate() {
let t = trim(raw);
if i == 2 {
if t.first() != Some(&DLE) {
return Err(Error::syntax(
"the third unit of a pattern record is a level",
at,
));
}
let inner_body = Body::of_level(t)?;
self.check_pattern(&inner_body, at, true)?;
} else {
if t.first().is_some_and(|&c| c == DLE || c == ENQ || c == STX) {
return Err(Error::syntax("a step of a pattern is a name", at));
}
let v = value(t)?;
if v.is_empty() || !is_name(&v) {
return Err(Error::syntax("a step of a pattern is a name", at));
}
}
}
Ok(())
}
}
#[inline]
pub(crate) fn trim_end(buf: &[u8], start: usize, mut stop: usize) -> usize {
while stop > start && is_layout(buf[stop - 1]) {
stop -= 1;
}
stop
}