-
Notifications
You must be signed in to change notification settings - Fork 241
/
firstpass.rs
1745 lines (1583 loc) · 64.6 KB
/
firstpass.rs
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
//! The first pass resolves all block structure, generating an AST. Within a block, items
//! are in a linear chain with potential inline markup identified.
use std::cmp::max;
use crate::parse::{scan_containers, Allocations, Item, ItemBody, LinkDef};
use crate::scanners::*;
use crate::strings::CowStr;
use crate::tree::{Tree, TreeIndex};
use crate::Options;
use crate::{
linklabel::{scan_link_label_rest, LinkLabel},
HeadingLevel,
};
use unicase::UniCase;
/// Runs the first pass, which resolves the block structure of the document,
/// and returns the resulting tree.
pub(crate) fn run_first_pass<'a>(text: &'a str, options: Options) -> (Tree<Item>, Allocations<'a>) {
// This is a very naive heuristic for the number of nodes
// we'll need.
let start_capacity = max(128, text.len() / 32);
let lookup_table = &create_lut(&options);
let first_pass = FirstPass {
text,
tree: Tree::with_capacity(start_capacity),
begin_list_item: false,
last_line_blank: false,
allocs: Allocations::new(),
options,
list_nesting: 0,
lookup_table,
};
first_pass.run()
}
/// State for the first parsing pass.
struct FirstPass<'a, 'b> {
text: &'a str,
tree: Tree<Item>,
begin_list_item: bool,
last_line_blank: bool,
allocs: Allocations<'a>,
options: Options,
list_nesting: usize,
lookup_table: &'b LookupTable,
}
impl<'a, 'b> FirstPass<'a, 'b> {
fn run(mut self) -> (Tree<Item>, Allocations<'a>) {
let mut ix = 0;
while ix < self.text.len() {
ix = self.parse_block(ix);
}
for _ in 0..self.tree.spine_len() {
self.pop(ix);
}
(self.tree, self.allocs)
}
/// Returns offset after block.
fn parse_block(&mut self, mut start_ix: usize) -> usize {
let bytes = self.text.as_bytes();
let mut line_start = LineStart::new(&bytes[start_ix..]);
let i = scan_containers(&self.tree, &mut line_start);
for _ in i..self.tree.spine_len() {
self.pop(start_ix);
}
if self.options.contains(Options::ENABLE_FOOTNOTES) {
// finish footnote if it's still open and was preceeded by blank line
if let Some(node_ix) = self.tree.peek_up() {
if let ItemBody::FootnoteDefinition(..) = self.tree[node_ix].item.body {
if self.last_line_blank {
self.pop(start_ix);
}
}
}
// Footnote definitions of the form
// [^bar]:
// * anything really
let container_start = start_ix + line_start.bytes_scanned();
if let Some(bytecount) = self.parse_footnote(container_start) {
start_ix = container_start + bytecount;
start_ix += scan_blank_line(&bytes[start_ix..]).unwrap_or(0);
line_start = LineStart::new(&bytes[start_ix..]);
}
}
// Process new containers
loop {
let container_start = start_ix + line_start.bytes_scanned();
if let Some((ch, index, indent)) = line_start.scan_list_marker() {
let after_marker_index = start_ix + line_start.bytes_scanned();
self.continue_list(container_start, ch, index);
self.tree.append(Item {
start: container_start,
end: after_marker_index, // will get updated later if item not empty
body: ItemBody::ListItem(indent),
});
self.tree.push();
if let Some(n) = scan_blank_line(&bytes[after_marker_index..]) {
self.begin_list_item = true;
return after_marker_index + n;
}
if self.options.contains(Options::ENABLE_TASKLISTS) {
if let Some(is_checked) = line_start.scan_task_list_marker() {
self.tree.append(Item {
start: after_marker_index,
end: start_ix + line_start.bytes_scanned(),
body: ItemBody::TaskListMarker(is_checked),
});
}
}
} else if line_start.scan_blockquote_marker() {
self.finish_list(start_ix);
self.tree.append(Item {
start: container_start,
end: 0, // will get set later
body: ItemBody::BlockQuote,
});
self.tree.push();
} else {
break;
}
}
let ix = start_ix + line_start.bytes_scanned();
if let Some(n) = scan_blank_line(&bytes[ix..]) {
if let Some(node_ix) = self.tree.peek_up() {
match self.tree[node_ix].item.body {
ItemBody::BlockQuote => (),
_ => {
if self.begin_list_item {
// A list item can begin with at most one blank line.
self.pop(start_ix);
}
self.last_line_blank = true;
}
}
}
return ix + n;
}
self.begin_list_item = false;
self.finish_list(start_ix);
// Save `remaining_space` here to avoid needing to backtrack `line_start` for HTML blocks
let remaining_space = line_start.remaining_space();
let indent = line_start.scan_space_upto(4);
if indent == 4 {
let ix = start_ix + line_start.bytes_scanned();
let remaining_space = line_start.remaining_space();
return self.parse_indented_code_block(ix, remaining_space);
}
let ix = start_ix + line_start.bytes_scanned();
// HTML Blocks
if bytes[ix] == b'<' {
// Types 1-5 are all detected by one function and all end with the same
// pattern
if let Some(html_end_tag) = get_html_end_tag(&bytes[(ix + 1)..]) {
return self.parse_html_block_type_1_to_5(ix, html_end_tag, remaining_space);
}
// Detect type 6
let possible_tag = scan_html_block_tag(&bytes[(ix + 1)..]).1;
if is_html_tag(possible_tag) {
return self.parse_html_block_type_6_or_7(ix, remaining_space);
}
// Detect type 7
if let Some(_html_bytes) = scan_html_type_7(&bytes[ix..]) {
return self.parse_html_block_type_6_or_7(ix, remaining_space);
}
}
if let Ok(n) = scan_hrule(&bytes[ix..]) {
return self.parse_hrule(n, ix);
}
if let Some(atx_size) = scan_atx_heading(&bytes[ix..]) {
return self.parse_atx_heading(ix, atx_size);
}
// parse refdef
if let Some((bytecount, label, link_def)) = self.parse_refdef_total(ix) {
self.allocs.refdefs.0.entry(label).or_insert(link_def);
let ix = ix + bytecount;
// try to read trailing whitespace or it will register as a completely blank line
// TODO: shouldn't we do this for all block level items?
return ix + scan_blank_line(&bytes[ix..]).unwrap_or(0);
}
if let Some((n, fence_ch)) = scan_code_fence(&bytes[ix..]) {
return self.parse_fenced_code_block(ix, indent, fence_ch, n);
}
self.parse_paragraph(ix)
}
/// Returns the offset of the first line after the table.
/// Assumptions: current focus is a table element and the table header
/// matches the separator line (same number of columns).
fn parse_table(&mut self, table_cols: usize, head_start: usize, body_start: usize) -> usize {
// parse header. this shouldn't fail because we made sure the table header is ok
let (_sep_start, thead_ix) = self.parse_table_row_inner(head_start, table_cols);
self.tree[thead_ix].item.body = ItemBody::TableHead;
// parse body
let mut ix = body_start;
while let Some((next_ix, _row_ix)) = self.parse_table_row(ix, table_cols) {
ix = next_ix;
}
self.pop(ix);
ix
}
/// Call this when containers are taken care of.
/// Returns bytes scanned, row_ix
fn parse_table_row_inner(&mut self, mut ix: usize, row_cells: usize) -> (usize, TreeIndex) {
let bytes = self.text.as_bytes();
let mut cells = 0;
let mut final_cell_ix = None;
let row_ix = self.tree.append(Item {
start: ix,
end: 0, // set at end of this function
body: ItemBody::TableRow,
});
self.tree.push();
loop {
ix += scan_ch(&bytes[ix..], b'|');
let start_ix = ix;
ix += scan_whitespace_no_nl(&bytes[ix..]);
if let Some(eol_bytes) = scan_eol(&bytes[ix..]) {
ix += eol_bytes;
break;
}
let cell_ix = self.tree.append(Item {
start: start_ix,
end: ix,
body: ItemBody::TableCell,
});
self.tree.push();
let (next_ix, _brk) = self.parse_line(ix, TableParseMode::Active);
if let Some(cur_ix) = self.tree.cur() {
let trailing_whitespace = scan_rev_while(&bytes[..next_ix], is_ascii_whitespace);
self.tree[cur_ix].item.end -= trailing_whitespace;
}
self.tree[cell_ix].item.end = next_ix;
self.tree.pop();
ix = next_ix;
cells += 1;
if cells == row_cells {
final_cell_ix = Some(cell_ix);
}
}
// fill empty cells if needed
// note: this is where GFM and commonmark-extra diverge. we follow
// GFM here
for _ in cells..row_cells {
self.tree.append(Item {
start: ix,
end: ix,
body: ItemBody::TableCell,
});
}
// drop excess cells
if let Some(cell_ix) = final_cell_ix {
self.tree[cell_ix].next = None;
}
self.pop(ix);
(ix, row_ix)
}
/// Returns first offset after the row and the tree index of the row.
fn parse_table_row(&mut self, mut ix: usize, row_cells: usize) -> Option<(usize, TreeIndex)> {
let bytes = self.text.as_bytes();
let mut line_start = LineStart::new(&bytes[ix..]);
let containers = scan_containers(&self.tree, &mut line_start);
if containers != self.tree.spine_len() {
return None;
}
line_start.scan_all_space();
ix += line_start.bytes_scanned();
if scan_paragraph_interrupt(&bytes[ix..]) {
return None;
}
let (ix, row_ix) = self.parse_table_row_inner(ix, row_cells);
Some((ix, row_ix))
}
/// Returns offset of line start after paragraph.
fn parse_paragraph(&mut self, start_ix: usize) -> usize {
let node_ix = self.tree.append(Item {
start: start_ix,
end: 0, // will get set later
body: ItemBody::Paragraph,
});
self.tree.push();
let bytes = self.text.as_bytes();
let mut ix = start_ix;
loop {
let scan_mode = if self.options.contains(Options::ENABLE_TABLES) && ix == start_ix {
TableParseMode::Scan
} else {
TableParseMode::Disabled
};
let (next_ix, brk) = self.parse_line(ix, scan_mode);
// break out when we find a table
if let Some(Item {
body: ItemBody::Table(alignment_ix),
..
}) = brk
{
let table_cols = self.allocs[alignment_ix].len();
self.tree[node_ix].item.body = ItemBody::Table(alignment_ix);
// this clears out any stuff we may have appended - but there may
// be a cleaner way
self.tree[node_ix].child = None;
self.tree.pop();
self.tree.push();
return self.parse_table(table_cols, ix, next_ix);
}
ix = next_ix;
let mut line_start = LineStart::new(&bytes[ix..]);
let n_containers = scan_containers(&self.tree, &mut line_start);
if !line_start.scan_space(4) {
let ix_new = ix + line_start.bytes_scanned();
if n_containers == self.tree.spine_len() {
if let Some(ix_setext) = self.parse_setext_heading(ix_new, node_ix) {
if let Some(Item {
start,
body: ItemBody::HardBreak,
..
}) = brk
{
if bytes[start] == b'\\' {
self.tree.append_text(start, start + 1);
}
}
ix = ix_setext;
break;
}
}
// first check for non-empty lists, then for other interrupts
let suffix = &bytes[ix_new..];
if self.interrupt_paragraph_by_list(suffix) || scan_paragraph_interrupt(suffix) {
break;
}
}
line_start.scan_all_space();
if line_start.is_at_eol() {
break;
}
ix = next_ix + line_start.bytes_scanned();
if let Some(item) = brk {
self.tree.append(item);
}
}
self.pop(ix);
ix
}
/// Returns end ix of setext_heading on success.
fn parse_setext_heading(&mut self, ix: usize, node_ix: TreeIndex) -> Option<usize> {
let bytes = self.text.as_bytes();
let (n, level) = scan_setext_heading(&bytes[ix..])?;
self.tree[node_ix].item.body = ItemBody::Heading(level);
// strip trailing whitespace
if let Some(cur_ix) = self.tree.cur() {
self.tree[cur_ix].item.end -= scan_rev_while(
&bytes[..self.tree[cur_ix].item.end],
is_ascii_whitespace_no_nl,
);
}
Some(ix + n)
}
/// Parse a line of input, appending text and items to tree.
///
/// Returns: index after line and an item representing the break.
fn parse_line(&mut self, start: usize, mode: TableParseMode) -> (usize, Option<Item>) {
let bytes = &self.text.as_bytes();
let mut pipes = 0;
let mut last_pipe_ix = start;
let mut begin_text = start;
let (final_ix, brk) =
iterate_special_bytes(&self.lookup_table, bytes, start, |ix, byte| {
match byte {
b'\n' | b'\r' => {
if let TableParseMode::Active = mode {
return LoopInstruction::BreakAtWith(ix, None);
}
let mut i = ix;
let eol_bytes = scan_eol(&bytes[ix..]).unwrap();
if mode == TableParseMode::Scan && pipes > 0 {
// check if we may be parsing a table
let next_line_ix = ix + eol_bytes;
let mut line_start = LineStart::new(&bytes[next_line_ix..]);
if scan_containers(&self.tree, &mut line_start) == self.tree.spine_len()
{
let table_head_ix = next_line_ix + line_start.bytes_scanned();
let (table_head_bytes, alignment) =
scan_table_head(&bytes[table_head_ix..]);
if table_head_bytes > 0 {
// computing header count from number of pipes
let header_count =
count_header_cols(bytes, pipes, start, last_pipe_ix);
// make sure they match the number of columns we find in separator line
if alignment.len() == header_count {
let alignment_ix =
self.allocs.allocate_alignment(alignment);
let end_ix = table_head_ix + table_head_bytes;
return LoopInstruction::BreakAtWith(
end_ix,
Some(Item {
start: i,
end: end_ix, // must update later
body: ItemBody::Table(alignment_ix),
}),
);
}
}
}
}
let end_ix = ix + eol_bytes;
let trailing_backslashes = scan_rev_while(&bytes[..ix], |b| b == b'\\');
if trailing_backslashes % 2 == 1 && end_ix < self.text.len() {
i -= 1;
self.tree.append_text(begin_text, i);
return LoopInstruction::BreakAtWith(
end_ix,
Some(Item {
start: i,
end: end_ix,
body: ItemBody::HardBreak,
}),
);
}
let trailing_whitespace =
scan_rev_while(&bytes[..ix], is_ascii_whitespace_no_nl);
if trailing_whitespace >= 2 {
i -= trailing_whitespace;
self.tree.append_text(begin_text, i);
return LoopInstruction::BreakAtWith(
end_ix,
Some(Item {
start: i,
end: end_ix,
body: ItemBody::HardBreak,
}),
);
}
self.tree.append_text(begin_text, ix);
LoopInstruction::BreakAtWith(
end_ix,
Some(Item {
start: i,
end: end_ix,
body: ItemBody::SoftBreak,
}),
)
}
b'\\' => {
if ix + 1 < self.text.len() && is_ascii_punctuation(bytes[ix + 1]) {
self.tree.append_text(begin_text, ix);
if bytes[ix + 1] == b'`' {
let count = 1 + scan_ch_repeat(&bytes[(ix + 2)..], b'`');
self.tree.append(Item {
start: ix + 1,
end: ix + count + 1,
body: ItemBody::MaybeCode(count, true),
});
begin_text = ix + 1 + count;
LoopInstruction::ContinueAndSkip(count)
} else {
begin_text = ix + 1;
LoopInstruction::ContinueAndSkip(1)
}
} else {
LoopInstruction::ContinueAndSkip(0)
}
}
c @ b'*' | c @ b'_' | c @ b'~' => {
let string_suffix = &self.text[ix..];
let count = 1 + scan_ch_repeat(&string_suffix.as_bytes()[1..], c);
let can_open = delim_run_can_open(self.text, string_suffix, count, ix);
let can_close = delim_run_can_close(self.text, string_suffix, count, ix);
let is_valid_seq = c != b'~' || count == 2;
if (can_open || can_close) && is_valid_seq {
self.tree.append_text(begin_text, ix);
for i in 0..count {
self.tree.append(Item {
start: ix + i,
end: ix + i + 1,
body: ItemBody::MaybeEmphasis(count - i, can_open, can_close),
});
}
begin_text = ix + count;
}
LoopInstruction::ContinueAndSkip(count - 1)
}
b'`' => {
self.tree.append_text(begin_text, ix);
let count = 1 + scan_ch_repeat(&bytes[(ix + 1)..], b'`');
self.tree.append(Item {
start: ix,
end: ix + count,
body: ItemBody::MaybeCode(count, false),
});
begin_text = ix + count;
LoopInstruction::ContinueAndSkip(count - 1)
}
b'<' => {
// Note: could detect some non-HTML cases and early escape here, but not
// clear that's a win.
self.tree.append_text(begin_text, ix);
self.tree.append(Item {
start: ix,
end: ix + 1,
body: ItemBody::MaybeHtml,
});
begin_text = ix + 1;
LoopInstruction::ContinueAndSkip(0)
}
b'!' => {
if ix + 1 < self.text.len() && bytes[ix + 1] == b'[' {
self.tree.append_text(begin_text, ix);
self.tree.append(Item {
start: ix,
end: ix + 2,
body: ItemBody::MaybeImage,
});
begin_text = ix + 2;
LoopInstruction::ContinueAndSkip(1)
} else {
LoopInstruction::ContinueAndSkip(0)
}
}
b'[' => {
self.tree.append_text(begin_text, ix);
self.tree.append(Item {
start: ix,
end: ix + 1,
body: ItemBody::MaybeLinkOpen,
});
begin_text = ix + 1;
LoopInstruction::ContinueAndSkip(0)
}
b']' => {
self.tree.append_text(begin_text, ix);
self.tree.append(Item {
start: ix,
end: ix + 1,
body: ItemBody::MaybeLinkClose(true),
});
begin_text = ix + 1;
LoopInstruction::ContinueAndSkip(0)
}
b'&' => match scan_entity(&bytes[ix..]) {
(n, Some(value)) => {
self.tree.append_text(begin_text, ix);
self.tree.append(Item {
start: ix,
end: ix + n,
body: ItemBody::SynthesizeText(self.allocs.allocate_cow(value)),
});
begin_text = ix + n;
LoopInstruction::ContinueAndSkip(n - 1)
}
_ => LoopInstruction::ContinueAndSkip(0),
},
b'|' => {
if let TableParseMode::Active = mode {
LoopInstruction::BreakAtWith(ix, None)
} else {
last_pipe_ix = ix;
pipes += 1;
LoopInstruction::ContinueAndSkip(0)
}
}
b'.' => {
if ix + 2 < bytes.len() && bytes[ix + 1] == b'.' && bytes[ix + 2] == b'.' {
self.tree.append_text(begin_text, ix);
self.tree.append(Item {
start: ix,
end: ix + 3,
body: ItemBody::SynthesizeChar('…'),
});
begin_text = ix + 3;
LoopInstruction::ContinueAndSkip(2)
} else {
LoopInstruction::ContinueAndSkip(0)
}
}
b'-' => {
let count = 1 + scan_ch_repeat(&bytes[(ix + 1)..], b'-');
if count == 1 {
LoopInstruction::ContinueAndSkip(0)
} else {
let itembody = if count == 2 {
ItemBody::SynthesizeChar('–')
} else if count == 3 {
ItemBody::SynthesizeChar('—')
} else {
let (ems, ens) = match count % 6 {
0 | 3 => (count / 3, 0),
2 | 4 => (0, count / 2),
1 => (count / 3 - 1, 2),
_ => (count / 3, 1),
};
// – and — are 3 bytes each in utf8
let mut buf = String::with_capacity(3 * (ems + ens));
for _ in 0..ems {
buf.push('—');
}
for _ in 0..ens {
buf.push('–');
}
ItemBody::SynthesizeText(self.allocs.allocate_cow(buf.into()))
};
self.tree.append_text(begin_text, ix);
self.tree.append(Item {
start: ix,
end: ix + count,
body: itembody,
});
begin_text = ix + count;
LoopInstruction::ContinueAndSkip(count - 1)
}
}
c @ b'\'' | c @ b'"' => {
let string_suffix = &self.text[ix..];
let can_open = delim_run_can_open(self.text, string_suffix, 1, ix);
let can_close = delim_run_can_close(self.text, string_suffix, 1, ix);
self.tree.append_text(begin_text, ix);
self.tree.append(Item {
start: ix,
end: ix + 1,
body: ItemBody::MaybeSmartQuote(c, can_open, can_close),
});
begin_text = ix + 1;
LoopInstruction::ContinueAndSkip(0)
}
_ => LoopInstruction::ContinueAndSkip(0),
}
});
if brk.is_none() {
// need to close text at eof
self.tree.append_text(begin_text, final_ix);
}
(final_ix, brk)
}
/// Check whether we should allow a paragraph interrupt by lists. Only non-empty
/// lists are allowed.
fn interrupt_paragraph_by_list(&self, suffix: &[u8]) -> bool {
scan_listitem(suffix).map_or(false, |(ix, delim, index, _)| {
self.list_nesting > 0 ||
// we don't allow interruption by either empty lists or
// numbered lists starting at an index other than 1
!scan_empty_list(&suffix[ix..]) && (delim == b'*' || delim == b'-' || index == 1)
})
}
/// When start_ix is at the beginning of an HTML block of type 1 to 5,
/// this will find the end of the block, adding the block itself to the
/// tree and also keeping track of the lines of HTML within the block.
///
/// The html_end_tag is the tag that must be found on a line to end the block.
fn parse_html_block_type_1_to_5(
&mut self,
start_ix: usize,
html_end_tag: &str,
mut remaining_space: usize,
) -> usize {
let bytes = self.text.as_bytes();
let mut ix = start_ix;
loop {
let line_start_ix = ix;
ix += scan_nextline(&bytes[ix..]);
self.append_html_line(remaining_space, line_start_ix, ix);
let mut line_start = LineStart::new(&bytes[ix..]);
let n_containers = scan_containers(&self.tree, &mut line_start);
if n_containers < self.tree.spine_len() {
break;
}
if (&self.text[line_start_ix..ix]).contains(html_end_tag) {
break;
}
let next_line_ix = ix + line_start.bytes_scanned();
if next_line_ix == self.text.len() {
break;
}
ix = next_line_ix;
remaining_space = line_start.remaining_space();
}
ix
}
/// When start_ix is at the beginning of an HTML block of type 6 or 7,
/// this will consume lines until there is a blank line and keep track of
/// the HTML within the block.
fn parse_html_block_type_6_or_7(
&mut self,
start_ix: usize,
mut remaining_space: usize,
) -> usize {
let bytes = self.text.as_bytes();
let mut ix = start_ix;
loop {
let line_start_ix = ix;
ix += scan_nextline(&bytes[ix..]);
self.append_html_line(remaining_space, line_start_ix, ix);
let mut line_start = LineStart::new(&bytes[ix..]);
let n_containers = scan_containers(&self.tree, &mut line_start);
if n_containers < self.tree.spine_len() || line_start.is_at_eol() {
break;
}
let next_line_ix = ix + line_start.bytes_scanned();
if next_line_ix == self.text.len() || scan_blank_line(&bytes[next_line_ix..]).is_some()
{
break;
}
ix = next_line_ix;
remaining_space = line_start.remaining_space();
}
ix
}
fn parse_indented_code_block(&mut self, start_ix: usize, mut remaining_space: usize) -> usize {
self.tree.append(Item {
start: start_ix,
end: 0, // will get set later
body: ItemBody::IndentCodeBlock,
});
self.tree.push();
let bytes = self.text.as_bytes();
let mut last_nonblank_child = None;
let mut last_nonblank_ix = 0;
let mut end_ix = 0;
let mut last_line_blank = false;
let mut ix = start_ix;
loop {
let line_start_ix = ix;
ix += scan_nextline(&bytes[ix..]);
self.append_code_text(remaining_space, line_start_ix, ix);
// TODO(spec clarification): should we synthesize newline at EOF?
if !last_line_blank {
last_nonblank_child = self.tree.cur();
last_nonblank_ix = ix;
end_ix = ix;
}
let mut line_start = LineStart::new(&bytes[ix..]);
let n_containers = scan_containers(&self.tree, &mut line_start);
if n_containers < self.tree.spine_len()
|| !(line_start.scan_space(4) || line_start.is_at_eol())
{
break;
}
let next_line_ix = ix + line_start.bytes_scanned();
if next_line_ix == self.text.len() {
break;
}
ix = next_line_ix;
remaining_space = line_start.remaining_space();
last_line_blank = scan_blank_line(&bytes[ix..]).is_some();
}
// Trim trailing blank lines.
if let Some(child) = last_nonblank_child {
self.tree[child].next = None;
self.tree[child].item.end = last_nonblank_ix;
}
self.pop(end_ix);
ix
}
fn parse_fenced_code_block(
&mut self,
start_ix: usize,
indent: usize,
fence_ch: u8,
n_fence_char: usize,
) -> usize {
let bytes = self.text.as_bytes();
let mut info_start = start_ix + n_fence_char;
info_start += scan_whitespace_no_nl(&bytes[info_start..]);
// TODO: info strings are typically very short. wouldnt it be faster
// to just do a forward scan here?
let mut ix = info_start + scan_nextline(&bytes[info_start..]);
let info_end = ix - scan_rev_while(&bytes[info_start..ix], is_ascii_whitespace);
let info_string = unescape(&self.text[info_start..info_end]);
self.tree.append(Item {
start: start_ix,
end: 0, // will get set later
body: ItemBody::FencedCodeBlock(self.allocs.allocate_cow(info_string)),
});
self.tree.push();
loop {
let mut line_start = LineStart::new(&bytes[ix..]);
let n_containers = scan_containers(&self.tree, &mut line_start);
if n_containers < self.tree.spine_len() {
break;
}
line_start.scan_space(indent);
let mut close_line_start = line_start.clone();
if !close_line_start.scan_space(4) {
let close_ix = ix + close_line_start.bytes_scanned();
if let Some(n) = scan_closing_code_fence(&bytes[close_ix..], fence_ch, n_fence_char)
{
ix = close_ix + n;
break;
}
}
let remaining_space = line_start.remaining_space();
ix += line_start.bytes_scanned();
let next_ix = ix + scan_nextline(&bytes[ix..]);
self.append_code_text(remaining_space, ix, next_ix);
ix = next_ix;
}
self.pop(ix);
// try to read trailing whitespace or it will register as a completely blank line
ix + scan_blank_line(&bytes[ix..]).unwrap_or(0)
}
fn append_code_text(&mut self, remaining_space: usize, start: usize, end: usize) {
if remaining_space > 0 {
let cow_ix = self.allocs.allocate_cow(" "[..remaining_space].into());
self.tree.append(Item {
start,
end: start,
body: ItemBody::SynthesizeText(cow_ix),
});
}
if self.text.as_bytes()[end - 2] == b'\r' {
// Normalize CRLF to LF
self.tree.append_text(start, end - 2);
self.tree.append_text(end - 1, end);
} else {
self.tree.append_text(start, end);
}
}
/// Appends a line of HTML to the tree.
fn append_html_line(&mut self, remaining_space: usize, start: usize, end: usize) {
if remaining_space > 0 {
let cow_ix = self.allocs.allocate_cow(" "[..remaining_space].into());
self.tree.append(Item {
start,
end: start,
// TODO: maybe this should synthesize to html rather than text?
body: ItemBody::SynthesizeText(cow_ix),
});
}
if self.text.as_bytes()[end - 2] == b'\r' {
// Normalize CRLF to LF
self.tree.append(Item {
start,
end: end - 2,
body: ItemBody::Html,
});
self.tree.append(Item {
start: end - 1,
end,
body: ItemBody::Html,
});
} else {
self.tree.append(Item {
start,
end,
body: ItemBody::Html,
});
}
}
/// Pop a container, setting its end.
fn pop(&mut self, ix: usize) {
let cur_ix = self.tree.pop().unwrap();
self.tree[cur_ix].item.end = ix;
if let ItemBody::List(true, _, _) = self.tree[cur_ix].item.body {
surgerize_tight_list(&mut self.tree, cur_ix);
}
}
/// Close a list if it's open. Also set loose if last line was blank
fn finish_list(&mut self, ix: usize) {
if let Some(node_ix) = self.tree.peek_up() {
if let ItemBody::List(_, _, _) = self.tree[node_ix].item.body {
self.pop(ix);
self.list_nesting -= 1;
}
}
if self.last_line_blank {
if let Some(node_ix) = self.tree.peek_grandparent() {
if let ItemBody::List(ref mut is_tight, _, _) = self.tree[node_ix].item.body {
*is_tight = false;
}
}
self.last_line_blank = false;
}
}
/// Continue an existing list or start a new one if there's not an open
/// list that matches.
fn continue_list(&mut self, start: usize, ch: u8, index: u64) {
if let Some(node_ix) = self.tree.peek_up() {
if let ItemBody::List(ref mut is_tight, existing_ch, _) = self.tree[node_ix].item.body {
if existing_ch == ch {
if self.last_line_blank {
*is_tight = false;
self.last_line_blank = false;
}
return;
}
}
// TODO: this is not the best choice for end; maybe get end from last list item.
self.finish_list(start);
}
self.tree.append(Item {
start,
end: 0, // will get set later
body: ItemBody::List(true, ch, index),
});
self.list_nesting += 1;
self.tree.push();
self.last_line_blank = false;
}
/// Parse a thematic break.
///
/// Returns index of start of next line.
fn parse_hrule(&mut self, hrule_size: usize, ix: usize) -> usize {
self.tree.append(Item {
start: ix,
end: ix + hrule_size,
body: ItemBody::Rule,
});
ix + hrule_size
}
/// Parse an ATX heading.
///
/// Returns index of start of next line.
fn parse_atx_heading(&mut self, mut ix: usize, atx_level: HeadingLevel) -> usize {
let heading_ix = self.tree.append(Item {
start: ix,
end: 0, // set later
body: ItemBody::Heading(atx_level),
});
ix += atx_level as usize;
// next char is space or eol (guaranteed by scan_atx_heading)
let bytes = self.text.as_bytes();