-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathparse.rs
3374 lines (3064 loc) · 122 KB
/
parse.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
// Copyright 2017 Google Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! Tree-based two pass parser.
use std::cmp::{max, min};
use std::collections::{HashMap, VecDeque};
use std::ops::{Index, Range};
use unicase::UniCase;
use crate::linklabel::{scan_link_label_rest, LinkLabel, ReferenceLabel};
use crate::scanners::*;
use crate::strings::CowStr;
use crate::tree::{Tree, TreeIndex};
// Allowing arbitrary depth nested parentheses inside link destinations
// can create denial of service vulnerabilities if we're not careful.
// The simplest countermeasure is to limit their depth, which is
// explicitly allowed by the spec as long as the limit is at least 3:
// https://spec.commonmark.org/0.29/#link-destination
const LINK_MAX_NESTED_PARENS: usize = 5;
/// Codeblock kind.
#[derive(Clone, Debug, PartialEq)]
pub enum CodeBlockKind<'a> {
Indented,
/// The value contained in the tag describes the language of the code, which may be empty.
Fenced(CowStr<'a>),
}
impl<'a> CodeBlockKind<'a> {
pub fn is_indented(&self) -> bool {
match *self {
CodeBlockKind::Indented => true,
_ => false,
}
}
pub fn is_fenced(&self) -> bool {
match *self {
CodeBlockKind::Fenced(_) => true,
_ => false,
}
}
}
/// Tags for elements that can contain other elements.
#[derive(Clone, Debug, PartialEq)]
pub enum Tag<'a> {
/// A paragraph of text and other inline elements.
Paragraph,
/// A heading. The field indicates the level of the heading.
Heading(u32),
BlockQuote,
/// A code block.
CodeBlock(CodeBlockKind<'a>),
/// A list. If the list is ordered the field indicates the number of the first item.
/// Contains only list items.
List(Option<u64>), // TODO: add delim and tight for ast (not needed for html)
/// A list item.
Item,
/// A footnote definition. The value contained is the footnote's label by which it can
/// be referred to.
FootnoteDefinition(CowStr<'a>),
/// A table. Contains a vector describing the text-alignment for each of its columns.
Table(Vec<Alignment>),
/// A table header. Contains only `TableRow`s. Note that the table body starts immediately
/// after the closure of the `TableHead` tag. There is no `TableBody` tag.
TableHead,
/// A table row. Is used both for header rows as body rows. Contains only `TableCell`s.
TableRow,
TableCell,
// span-level tags
Emphasis,
Strong,
Strikethrough,
/// A link. The first field is the link type, the second the destination URL and the third is a title.
Link(LinkType, CowStr<'a>, CowStr<'a>),
/// An image. The first field is the link type, the second the destination URL and the third is a title.
Image(LinkType, CowStr<'a>, CowStr<'a>),
}
/// Type specifier for inline links. See [the Tag::Link](enum.Tag.html#variant.Link) for more information.
#[derive(Clone, Debug, PartialEq, Copy)]
pub enum LinkType {
/// Inline link like `[foo](bar)`
Inline,
/// Reference link like `[foo][bar]`
Reference,
/// Reference without destination in the document, but resolved by the broken_link_callback
ReferenceUnknown,
/// Collapsed link like `[foo][]`
Collapsed,
/// Collapsed link without destination in the document, but resolved by the broken_link_callback
CollapsedUnknown,
/// Shortcut link like `[foo]`
Shortcut,
/// Shortcut without destination in the document, but resolved by the broken_link_callback
ShortcutUnknown,
/// Autolink like `<http://foo.bar/baz>`
Autolink,
/// Email address in autolink like `<john@example.org>`
Email,
}
impl LinkType {
fn to_unknown(self) -> Self {
match self {
LinkType::Reference => LinkType::ReferenceUnknown,
LinkType::Collapsed => LinkType::CollapsedUnknown,
LinkType::Shortcut => LinkType::ShortcutUnknown,
_ => unreachable!(),
}
}
}
/// Markdown events that are generated in a preorder traversal of the document
/// tree, with additional `End` events whenever all of an inner node's children
/// have been visited.
#[derive(Clone, Debug, PartialEq)]
pub enum Event<'a> {
/// Start of a tagged element. Events that are yielded after this event
/// and before its corresponding `End` event are inside this element.
/// Start and end events are guaranteed to be balanced.
Start(Tag<'a>),
/// End of a tagged element.
End(Tag<'a>),
/// A text node.
Text(CowStr<'a>),
/// An inline code node.
Code(CowStr<'a>),
/// An HTML node.
Html(CowStr<'a>),
/// A reference to a footnote with given label, which may or may not be defined
/// by an event with a `Tag::FootnoteDefinition` tag. Definitions and references to them may
/// occur in any order.
FootnoteReference(CowStr<'a>),
/// A soft line break.
SoftBreak,
/// A hard line break.
HardBreak,
/// A horizontal ruler.
Rule,
/// A task list marker, rendered as a checkbox in HTML. Contains a true when it is checked.
TaskListMarker(bool),
}
/// Table column text alignment.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Alignment {
/// Default text alignment.
None,
Left,
Center,
Right,
}
bitflags! {
/// Option struct containing flags for enabling extra features
/// that are not part of the CommonMark spec.
pub struct Options: u32 {
const ENABLE_TABLES = 1 << 1;
const ENABLE_FOOTNOTES = 1 << 2;
const ENABLE_STRIKETHROUGH = 1 << 3;
const ENABLE_TASKLISTS = 1 << 4;
const ENABLE_SMART_PUNCTUATION = 1 << 5;
}
}
#[derive(Debug, Default, Clone, Copy)]
struct Item {
start: usize,
end: usize,
body: ItemBody,
}
#[derive(Debug, PartialEq, Clone, Copy)]
enum ItemBody {
Paragraph,
Text,
SoftBreak,
HardBreak,
// These are possible inline items, need to be resolved in second pass.
// repeats, can_open, can_close
MaybeEmphasis(usize, bool, bool),
// quote byte, can_open, can_close
MaybeSmartQuote(u8, bool, bool),
MaybeCode(usize, bool), // number of backticks, preceeded by backslash
MaybeHtml,
MaybeLinkOpen,
// bool indicates whether or not the preceeding section could be a reference
MaybeLinkClose(bool),
MaybeImage,
// These are inline items after resolution.
Emphasis,
Strong,
Strikethrough,
Code(CowIndex),
Link(LinkIndex),
Image(LinkIndex),
FootnoteReference(CowIndex),
TaskListMarker(bool), // true for checked
Rule,
Heading(u32), // heading level
FencedCodeBlock(CowIndex),
IndentCodeBlock,
Html,
OwnedHtml(CowIndex),
BlockQuote,
List(bool, u8, u64), // is_tight, list character, list start index
ListItem(usize), // indent level
SynthesizeText(CowIndex),
SynthesizeChar(char),
FootnoteDefinition(CowIndex),
// Tables
Table(AlignmentIndex),
TableHead,
TableRow,
TableCell,
// Dummy node at the top of the tree - should not be used otherwise!
Root,
}
impl<'a> ItemBody {
fn is_inline(&self) -> bool {
match *self {
ItemBody::MaybeEmphasis(..)
| ItemBody::MaybeSmartQuote(..)
| ItemBody::MaybeHtml
| ItemBody::MaybeCode(..)
| ItemBody::MaybeLinkOpen
| ItemBody::MaybeLinkClose(..)
| ItemBody::MaybeImage => true,
_ => false,
}
}
}
impl<'a> Default for ItemBody {
fn default() -> Self {
ItemBody::Root
}
}
/// Scanning modes for `Parser`'s `parse_line` method.
#[derive(PartialEq, Eq, Copy, Clone)]
enum TableParseMode {
/// Inside a paragraph, scanning for table headers.
Scan,
/// Inside a table.
Active,
/// Inside a paragraph, not scanning for table headers.
Disabled,
}
pub struct BrokenLink<'a> {
pub span: std::ops::Range<usize>,
pub link_type: LinkType,
pub reference: &'a str,
}
/// State for the first parsing pass.
///
/// The first pass resolves all block structure, generating an AST. Within a block, items
/// are in a linear chain with potential inline markup identified.
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 new(text: &'a str, options: Options, lookup_table: &'b LookupTable) -> FirstPass<'a, 'b> {
// This is a very naive heuristic for the number of nodes
// we'll need.
let start_capacity = max(128, text.len() / 32);
let tree = Tree::with_capacity(start_capacity);
FirstPass {
text,
tree,
begin_list_item: false,
last_line_blank: false,
allocs: Allocations::new(),
options,
list_nesting: 0,
lookup_table,
}
}
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.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'|');
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: ix,
end: ix,
body: ItemBody::TableCell,
});
self.tree.push();
let (next_ix, _brk) = self.parse_line(ix, TableParseMode::Active);
let trailing_whitespace = scan_rev_while(&bytes[..next_ix], is_ascii_whitespace);
if let Some(cur_ix) = self.tree.cur() {
self.tree[cur_ix].item.end -= trailing_whitespace;
}
self.tree[cell_ix].item.end = next_ix - trailing_whitespace;
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;
}