html-to-markdown-rs 3.18.7

High-performance HTML to Markdown converter using the astral-tl parser. Part of the Xberg ecosystem.
Documentation
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
use super::prepare::{keep_inert_wrappers, preprocess_initial_html, preprocess_repaired_html};
use super::trace_parse_complete;
use crate::converter::DomContext;
use crate::converter::main_helpers::{has_custom_element_tags, preserves_menu, repair_with_html5ever};
use crate::converter::preprocessing_helpers::{
    has_discarded_end_tag, has_omitted_end_tag, readable_text_len, tree_repair_reasons, written_title_len,
};
use crate::converter::utility::caching::build_dom_context;
use crate::converter::utility::preprocessing::{KeptScripts, normalize_inert_bodies_with_preservation};
use crate::error::{ConversionError, Result};
use crate::options::{ConversionOptions, HiddenContent};

#[cfg(test)]
thread_local! {
    static PARSE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    static FORCE_INVALID_LENGTH: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

pub(super) fn parse_html(input: &str) -> Result<tl::VDom<'_>> {
    #[cfg(test)]
    PARSE_CALLS.with(|calls| calls.set(calls.get() + 1));
    #[cfg(test)]
    if FORCE_INVALID_LENGTH.with(std::cell::Cell::get) {
        return Err(invalid_length(input));
    }
    tl::parse(input, tl::ParserOptions::default()).map_err(|tl::ParseError::InvalidLength| invalid_length(input))
}

fn invalid_length(input: &str) -> ConversionError {
    tracing::error!(
        target: "html_to_markdown::convert",
        input_len = input.len(),
        "failed to parse HTML; input length exceeds parser capacity"
    );
    ConversionError::ParseError("Failed to parse HTML".to_string())
}

/// The tree that the converter reads, the length of the page that the tree is made of, and the
/// limit that stopped the tree builder when the first parse was kept for that reason.
pub(super) struct ParsedPage<'a> {
    pub(super) source: &'a str,
    pub(super) dom: tl::VDom<'a>,
    pub(super) dom_ctx: DomContext,
    pub(super) len: usize,
    pub(super) repair_limit: Option<crate::types::WarningKind>,
}

impl<'a> ParsedPage<'a> {
    fn first_parse(dom: tl::VDom<'a>, source: &'a str) -> Self {
        let len = source.len();
        let dom_ctx = build_dom_context(&dom, dom.parser(), len);
        Self {
            source,
            dom,
            dom_ctx,
            len,
            repair_limit: None,
        }
    }
}

/// Parse `input`, and parse it a second time through the HTML tree builder when it has an
/// omitted end tag or a misnest. `repaired_page` holds the page of the second parse.
///
/// ~keep The repair must never lose text. The tree builder drops text that the first parse
/// ~keep keeps (all that follows `</frameset>` in a frameset document), and no list of such
/// ~keep cases is kept here: both pages are read by `tl` and measured by
/// ~keep [`readable_text_len`], and a repaired page with a smaller count is not used. The
/// ~keep page then converts as it did before issue #772.
///
/// ~keep `as_written` is the page before the passes of this conversion, when the tree builder
/// ~keep has not written the page of `input`. With it, a page that asks for no second parse
/// ~keep takes one all the same when a narrower choice of `hidden_content` takes one:
/// ~keep [`narrower_choice_asks`].
pub(super) fn parse_for_conversion<'a>(
    input: &'a str,
    repaired_page: &'a std::cell::OnceCell<String>,
    options: &ConversionOptions,
    as_written: Option<&str>,
) -> Result<ParsedPage<'a>> {
    let (preserve_menu, hidden_content) = (preserves_menu(options), options.hidden_content);
    let dom = parse_html(input)?;
    let parser = dom.parser();
    let len = input.len();
    let asked = Asked::of(&dom, parser, input, options);
    let misnest = asked.misnest;
    let for_narrower_choice = match as_written {
        Some(html) if !asked.any() => narrower_choice_asks(html, input, options, hidden_content)?,
        _ => false,
    };
    // ~keep The second parse for a narrower choice has the text rule and the limits of the one
    // ~keep for an omitted end tag: the first parse holds every word of the page.
    let omitted_end_tag = asked.omitted_end_tag || for_narrower_choice;
    if !omitted_end_tag && !misnest {
        return Ok(ParsedPage::first_parse(dom, input));
    }
    // ~keep Every route to the tree builder has the node budget and the depth limit (issues
    // ~keep #808 and #809). When only an omitted end tag asked for the repair, a tree that
    // ~keep reached a limit is not used: the first parse holds every word of the input and is
    // ~keep kept, with the warning. The first parse of a misnest can hide content, so a misnest
    // ~keep takes the tree up to the depth limit and the rest of the input as written.
    let Some((repaired, repair_limit)) = repair_with_html5ever(input, keep_inert_wrappers(options, hidden_content))
    else {
        tracing::warn!(
            target: "html_to_markdown::convert",
            "html5ever repair gave no tree (the document cannot be written back); proceeding with original structure"
        );
        return Ok(ParsedPage::first_parse(dom, input));
    };
    if repair_limit.is_some() && !misnest {
        let dom_ctx = build_dom_context(&dom, parser, len);
        return Ok(ParsedPage {
            source: input,
            dom,
            dom_ctx,
            len,
            repair_limit,
        });
    }
    let page = repaired_page.get_or_init(|| preprocess_repaired_html(&repaired, preserve_menu, hidden_content));
    let second = parse_html(page)?;
    // ~keep The text rule is for the second parse that an omitted end tag asks for. The first
    // ~keep parse of a misnest can hide content, so its count is not a measure.
    let loses_text = omitted_end_tag
        && (readable_text_len(&second) < readable_text_len(&dom)
            || loses_a_title_of_a_wider_choice(&dom, &second, as_written, options, hidden_content)?);
    if loses_text && !misnest {
        // ~keep A frameset page with every end tag written comes here, so this is no warning.
        tracing::debug!(
            target: "html_to_markdown::convert",
            "html5ever repair would lose text; proceeding with original structure"
        );
        return Ok(ParsedPage::first_parse(dom, input));
    }
    let for_omitted_end_tag = omitted_end_tag && !loses_text && repair_limit.is_none();
    log_the_second_parse(for_narrower_choice, asked.discarded_end_tag, for_omitted_end_tag);
    let dom_ctx = build_dom_context(&second, second.parser(), page.len());
    Ok(ParsedPage {
        source: page,
        dom: second,
        dom_ctx,
        len: page.len(),
        repair_limit,
    })
}

/// Log why the conversion reads the second parse.
fn log_the_second_parse(for_narrower_choice: bool, discarded_end_tag: bool, for_omitted_end_tag: bool) {
    if for_narrower_choice {
        tracing::debug!(
            target: "html_to_markdown::convert",
            "a narrower choice of hidden_content takes the html5ever repair; re-parsed with html5ever repair"
        );
    } else if discarded_end_tag {
        tracing::debug!(
            target: "html_to_markdown::convert",
            "end tag of an open element discarded by the first parse; re-parsed with html5ever repair"
        );
    } else if for_omitted_end_tag {
        // ~keep An omitted end tag is HTML that the standard permits, so this route is logged
        // ~keep at debug, like the choice of a tier. A misnest is an authoring error and warns.
        // ~keep A page that reached a limit is here only as a misnest.
        tracing::debug!(
            target: "html_to_markdown::convert",
            "element with no end tag; re-parsed with html5ever repair"
        );
    } else {
        tracing::warn!(
            target: "html_to_markdown::convert",
            "misnested HTML elements detected; re-parsed with html5ever repair"
        );
    }
}

/// What in the first parse of a page asks for the second parse, through the HTML tree builder.
#[derive(Clone, Copy)]
struct Asked {
    /// An element with content is open at the end of the page, or the first parse discarded
    /// the end tag of an open element.
    omitted_end_tag: bool,
    /// The first parse discarded the end tag of an open element.
    discarded_end_tag: bool,
    /// An element is where the HTML tree builder does not leave it.
    misnest: bool,
}

impl Asked {
    fn of(dom: &tl::VDom, parser: &tl::Parser<'_>, input: &str, options: &ConversionOptions) -> Self {
        let open_at_the_end = has_omitted_end_tag(dom, parser);
        let reasons = tree_repair_reasons(dom, parser);
        let misnest = reasons.misnest;
        // ~keep Retained forms intentionally remain in the surrounding plain-text flow (#814).
        let form_paragraph_close = reasons.form_paragraph_close
            && options.preprocessing.enabled
            && options.preprocessing.remove_forms
            && options.preprocessing.preset != crate::options::PreprocessingPreset::Minimal
            && !options
                .preserve_tags
                .iter()
                .any(|name| name.eq_ignore_ascii_case("form"));
        // ~keep Both rules ask where the tree builder ends an element, so both have the text rule.
        let discarded_end_tag = !open_at_the_end && !misnest && has_discarded_end_tag(dom, parser, input);
        Self {
            omitted_end_tag: open_at_the_end || reasons.paragraph_close || form_paragraph_close || discarded_end_tag,
            discarded_end_tag,
            misnest,
        }
    }

    const fn any(self) -> bool {
        self.omitted_end_tag || self.misnest
    }
}

/// Whether `html` goes to the HTML tree builder under a choice of `hidden_content` that is
/// narrower than the choice of the caller. `page` is the page of the caller's choice.
///
/// ~keep The tree builder moves content between the head and the body, and the walk writes the
/// ~keep two differently: an `<img>` in a `<head>` is written only after the tree builder moved
/// ~keep it to the body. A narrower choice keeps tags that a wider choice removes, and such a
/// ~keep tag can be all that asks for the tree builder: in `<head><img><template></head><p>`
/// ~keep the `<template>` has no end tag. So a wider choice takes the tree builder wherever a
/// ~keep narrower one does, and writes what the narrower one writes. A narrower page that is
/// ~keep equal to the wider page asks for nothing new and is not parsed.
///
/// ~keep The inert-body pass ran on `html` under the choice of the caller and left as written
/// ~keep each `<template>` and `<noscript>` that the choice keeps. The narrower choice empties
/// ~keep those that it does not keep, so the pass runs again under the narrower choice.
fn narrower_choice_asks(
    html: &str,
    page: &str,
    options: &ConversionOptions,
    hidden_content: HiddenContent,
) -> Result<bool> {
    let narrower = match hidden_content {
        HiddenContent::Drop => return Ok(false),
        HiddenContent::Reachable => HiddenContent::Drop,
        HiddenContent::All => HiddenContent::Reachable,
    };
    let (narrower_html, _) = normalize_inert_bodies_with_preservation(html, false, narrower);
    let narrower_page = preprocess_initial_html(&narrower_html, options, narrower)?;
    if narrower_page != page && asks_for_the_tree_builder(&narrower_page, options) {
        return Ok(true);
    }
    narrower_choice_asks(html, &narrower_page, options, narrower)
}

/// Whether the second parse of a choice that keeps hidden content loses a title that the first
/// parse writes, on a page that `drop` does not send to the tree builder. `as_written` is the
/// page before the passes of this conversion.
///
/// ~keep The walk writes a `<title>` of a `<head>` that holds a paragraph as text, and the tree
/// ~keep builder puts that title in the head, where it is the title of the document. Kept content
/// ~keep can be all that asks for the tree builder: in `<head><title>t</title><p>a</p></head>`
/// ~keep `<template><div>b</template>` the `<div>` has no end tag. `drop` then writes the title
/// ~keep from its first parse, so a wider choice keeps its first parse too. Where `drop` takes
/// ~keep the tree builder, each choice takes it and no choice writes the title.
fn loses_a_title_of_a_wider_choice(
    first: &tl::VDom<'_>,
    second: &tl::VDom<'_>,
    as_written: Option<&str>,
    options: &ConversionOptions,
    hidden_content: HiddenContent,
) -> Result<bool> {
    let Some(html) = as_written else {
        return Ok(false);
    };
    if hidden_content == HiddenContent::Drop || written_title_len(second) >= written_title_len(first) {
        return Ok(false);
    }
    let (emptied, _) = normalize_inert_bodies_with_preservation(html, false, HiddenContent::Drop);
    let page_of_drop = preprocess_initial_html(&emptied, options, HiddenContent::Drop)?;
    Ok(!asks_for_the_tree_builder(&page_of_drop, options))
}

/// Whether the conversion of `page`, a page before its first parse, runs the HTML tree builder.
fn asks_for_the_tree_builder(page: &str, options: &ConversionOptions) -> bool {
    has_custom_element_tags(page)
        || parse_html(page).is_ok_and(|dom| {
            let parser = dom.parser();
            Asked::of(&dom, parser, page, options).any()
        })
}

/// Finish the tree that the converter reads. Returns the kept scripts of the page, with the
/// node of each script that had an owner mark.
///
/// ~keep No parse comes after this function, so the ids of the nodes are final here. The owner
/// ~keep marks leave the tree here, before the metadata, a visitor or a writer of HTML reads it.
pub(super) fn finish_dom_parse(
    dom: &mut tl::VDom<'_>,
    dom_ctx: &mut DomContext,
    inert_bodies: &std::collections::HashMap<String, String>,
    input_len: usize,
    kept_scripts: KeptScripts,
) -> Result<KeptScripts> {
    if !inert_bodies.is_empty() {
        // ~keep The restore runs first: it puts the bytes of a repaired script back in the tree
        // ~keep and takes the owner mark of that script out. No reader asks for its node ids:
        // ~keep nothing decodes the text of a script, so a restored body reads as the tree has it.
        crate::converter::utility::preprocessing::restore_inert_bodies(dom, inert_bodies)?;
        *dom_ctx = build_dom_context(dom, dom.parser(), input_len);
    }
    trace_parse_complete(dom, input_len);
    #[cfg(feature = "metadata")]
    let kept_scripts = kept_scripts.with_owner_marks_taken(dom)?;
    Ok(kept_scripts)
}

#[cfg(test)]
mod tests {
    use super::{FORCE_INVALID_LENGTH, PARSE_CALLS};
    use crate::converter::utility::caching::DOM_CONTEXT_BUILDS;
    use crate::{ConversionError, ConversionOptions, TierStrategy, convert};

    #[test]
    fn should_parse_and_build_dom_context_once_for_well_formed_tier2_input() {
        let options = ConversionOptions {
            tier_strategy: TierStrategy::Tier2,
            ..ConversionOptions::default()
        };
        PARSE_CALLS.with(|calls| calls.set(0));
        DOM_CONTEXT_BUILDS.with(|builds| builds.set(0));

        let result = convert("<p>Hello <strong>world</strong></p>", options).expect("convert HTML");

        assert_eq!(result.content.as_deref(), Some("Hello **world**\n"));
        PARSE_CALLS.with(|calls| assert_eq!(calls.get(), 1));
        DOM_CONTEXT_BUILDS.with(|builds| assert_eq!(builds.get(), 1));
    }

    #[test]
    fn should_build_only_the_selected_context_after_paragraph_repair() {
        // ~keep These raised-depth fixtures need a local stack independent of the libtest worker.
        std::thread::Builder::new()
            .stack_size(16 * 1024 * 1024)
            .spawn(|| {
                let cases = [0, 100, 500].into_iter().flat_map(|depth| {
                    [500, 2000]
                        .into_iter()
                        .flat_map(move |n| ["fully_closed", "legacy_open", "omitted"].map(|shape| (depth, n, shape)))
                });
                let mut rows = 0;
                for (depth, n, shape) in cases {
                    let paragraph = if shape == "omitted" { "<p>x " } else { "<p>x </p>" };
                    let closes = if shape == "fully_closed" {
                        "</div>".repeat(depth)
                    } else {
                        String::new()
                    };
                    let html = format!("{}{}{closes}", "<div>".repeat(depth), paragraph.repeat(n));
                    let options = ConversionOptions {
                        max_depth: Some(1024),
                        tier_strategy: TierStrategy::Tier2,
                        extract_metadata: false,
                        ..Default::default()
                    };
                    PARSE_CALLS.with(|calls| calls.set(0));
                    DOM_CONTEXT_BUILDS.with(|calls| calls.set(0));
                    let result = convert(&html, options).expect("convert repaired paragraphs");
                    assert_eq!(
                        result.content.as_deref(),
                        Some(format!("{}x\n", "x\n\n".repeat(n - 1)).as_str())
                    );
                    assert!(result.warnings.is_empty());
                    let repairs = shape == "omitted" || (shape == "legacy_open" && depth != 0);
                    assert_eq!(PARSE_CALLS.with(std::cell::Cell::get), if repairs { 2 } else { 1 });
                    assert_eq!(
                        DOM_CONTEXT_BUILDS.with(std::cell::Cell::get),
                        1,
                        "{depth}, {n}, {shape}"
                    );
                    rows += 1;
                }
                assert_eq!(rows, 18);
            })
            .expect("spawn deep paragraph repair fixtures")
            .join()
            .expect("deep paragraph repair fixtures complete");
    }

    #[test]
    fn should_build_one_context_for_repair_and_fallback_decisions() {
        // ~keep Preserve deep decision coverage without depending on the default libtest stack.
        std::thread::Builder::new()
            .stack_size(16 * 1024 * 1024)
            .spawn(|| {
                let cases = [
                    (
                        "<DIV><P>one</DIV>two</P>rest</DIV>tail".to_string(),
                        "one\n\ntwo\n\nresttail\n",
                        2,
                        0,
                    ),
                    (
                        "<table>a<tr><td>b</td></tr></table>".to_string(),
                        "a\n\n| b |\n| --- |\n",
                        2,
                        0,
                    ),
                    ("<HTML><BODY><p>a</p><p>b</p>".to_string(), "a\n\nb\n", 1, 0),
                    ("<frameset><frame></frameset><p>a<p>b".to_string(), "a\n\nb\n", 2, 0),
                    (
                        format!("<p>kept</p>{}deep", "<div>".repeat(600)),
                        "kept\n\ndeep\n",
                        1,
                        1,
                    ),
                    (format!("{}x", "<table><td>".repeat(300)), "", 2, 1),
                ];
                for (html, content, parses, warnings) in cases {
                    let options = ConversionOptions {
                        max_depth: Some(1024),
                        tier_strategy: TierStrategy::Tier2,
                        extract_metadata: false,
                        ..Default::default()
                    };
                    PARSE_CALLS.with(|calls| calls.set(0));
                    DOM_CONTEXT_BUILDS.with(|calls| calls.set(0));
                    let result = convert(&html, options).expect("convert selected tree");
                    assert_eq!(result.content.as_deref(), Some(content));
                    assert_eq!(result.warnings.len(), warnings);
                    assert_eq!(PARSE_CALLS.with(std::cell::Cell::get), parses);
                    assert_eq!(DOM_CONTEXT_BUILDS.with(std::cell::Cell::get), 1);
                }
            })
            .expect("spawn deep selected-tree fixtures")
            .join()
            .expect("deep selected-tree fixtures complete");
    }

    #[test]
    fn should_follow_the_last_root_and_child_for_omitted_end_tag_repair() {
        for html in [
            "<p>one</p><div>two",
            "<html><head><title>T</title></head><body><p>one</p><div>two",
        ] {
            PARSE_CALLS.with(|calls| calls.set(0));
            DOM_CONTEXT_BUILDS.with(|calls| calls.set(0));
            let result = convert(
                html,
                ConversionOptions {
                    tier_strategy: TierStrategy::Tier2,
                    extract_metadata: false,
                    ..Default::default()
                },
            )
            .expect("convert omitted final sibling");
            assert_eq!(result.content.as_deref(), Some("one\n\ntwo\n"));
            assert_eq!(PARSE_CALLS.with(std::cell::Cell::get), 2);
            assert_eq!(DOM_CONTEXT_BUILDS.with(std::cell::Cell::get), 1);
        }
    }

    fn parse_calls_for(html: &str) -> (usize, Option<String>) {
        let options = ConversionOptions {
            tier_strategy: TierStrategy::Tier2,
            ..ConversionOptions::default()
        };
        PARSE_CALLS.with(|calls| calls.set(0));
        let result = convert(html, options).expect("convert HTML");
        (PARSE_CALLS.with(std::cell::Cell::get), result.content)
    }

    #[test]
    fn should_parse_the_page_of_a_narrower_choice_only_when_it_is_another_page() {
        // ~keep A wider choice asks the page of each narrower choice whether it takes the tree
        // ~keep builder. A page equal to the wider page is not parsed, and no narrower page is
        // ~keep parsed when the page of the choice asks for the second parse itself.
        let choices = [
            crate::HiddenContent::Drop,
            crate::HiddenContent::Reachable,
            crate::HiddenContent::All,
        ];
        for (html, expected) in [
            ("<p>one</p>", [1, 1, 1]),
            ("<p>one</p><div hidden>two</div>", [1, 2, 2]),
            ("<p>one</p><template><p>two</p></template>", [1, 1, 2]),
            (
                "<p>one</p><div hidden>two</div><template><p>three</p></template>",
                [1, 2, 3],
            ),
            ("<div><p>one</div><template><p>two</p></template>tail", [2, 2, 2]),
        ] {
            let calls = choices.map(|hidden_content| {
                let options = ConversionOptions {
                    tier_strategy: TierStrategy::Tier2,
                    hidden_content,
                    ..ConversionOptions::default()
                };
                PARSE_CALLS.with(|calls| calls.set(0));
                convert(html, options).expect("convert HTML");
                PARSE_CALLS.with(std::cell::Cell::get)
            });
            assert_eq!(calls, expected, "{html}");
        }
    }

    #[test]
    fn should_parse_twice_when_an_element_with_content_has_no_end_tag() {
        let (calls, content) = parse_calls_for("<div><p>one</div>tail");

        assert_eq!(content.as_deref(), Some("one\n\ntail\n"));
        assert_eq!(calls, 2);
    }

    #[test]
    fn should_repair_a_form_nested_in_a_form_without_an_omitted_end_tag() {
        let mut options = ConversionOptions {
            tier_strategy: TierStrategy::Tier2,
            ..ConversionOptions::default()
        };
        options.preprocessing.remove_forms = false;
        PARSE_CALLS.with(|calls| calls.set(0));
        let result = convert("<form>a<form>b</form>c</form>d", options).expect("retained nested form");

        assert_eq!(result.content.as_deref(), Some("ab\n\ncd\n"));
        PARSE_CALLS.with(|calls| assert_eq!(calls.get(), 2));
    }

    #[test]
    fn should_parse_once_after_source_removal_of_closed_nested_forms() {
        let (calls, content) = parse_calls_for("<form>a<form>b</form>c</form>d");

        assert_eq!(content.as_deref(), Some("cd\n"));
        assert_eq!(calls, 1);
    }

    #[test]
    fn should_not_repair_form_shaped_text_or_forms_inside_a_template() {
        for html in [
            "<form>a</form><form>b</form><p>tail</p>",
            "<form title='<form>'>a</form><p>tail</p>",
            "<form><!-- <form>b</form> -->a</form><p>tail</p>",
            "<form><script>const text = '<form><form>';</script>a</form><p>tail</p>",
            "<form><style>a::after { content: '<form><form>'; }</style>a</form><p>tail</p>",
            "<form><template><form>b</form></template>a</form><p>tail</p>",
            "<template><form>a<form>b</form>c</form></template><p>tail</p>",
            "<form><noscript><form>a<form>b</form>c</form></noscript></form><p>tail</p>",
        ] {
            let (calls, content) = parse_calls_for(html);

            assert_eq!(calls, 1, "{html:?}");
            assert_eq!(content.as_deref(), Some("tail\n"), "{html:?}");
        }
    }

    #[test]
    fn should_parse_once_when_only_html_and_body_have_no_end_tag() {
        for html in ["<html><body><p>one</p><p>two</p>", "<HTML><BODY><p>one</p><p>two</p>"] {
            let (calls, content) = parse_calls_for(html);

            assert_eq!(content.as_deref(), Some("one\n\ntwo\n"), "{html:?}");
            assert_eq!(calls, 1, "{html:?}");
        }
    }

    #[test]
    fn should_keep_the_first_parse_when_the_second_parse_nests_past_its_limit() {
        let html = format!("<p>kept</p>{}deep", "<div>".repeat(600));
        // ~keep This tests repair fallback with a deliberately low traversal budget, independent
        // ~keep of the default conversion depth (#924).
        PARSE_CALLS.with(|calls| calls.set(0));
        let result = convert(
            &html,
            ConversionOptions {
                tier_strategy: TierStrategy::Tier2,
                max_depth: Some(64),
                ..Default::default()
            },
        )
        .expect("convert unrepaired HTML");

        assert_eq!(result.content.as_deref(), Some("kept\n"));
        assert_eq!(PARSE_CALLS.with(std::cell::Cell::get), 1);
    }

    #[test]
    fn should_parse_twice_when_a_misnest_nests_past_the_repair_depth_limit() {
        // ~keep A cell with no row is a misnest and has no end tag. The first parse hides it,
        // ~keep so the page takes the tree up to the depth limit (issue #808) and the rest of
        // ~keep the input as written, in a second parse.
        let html = format!("{}x", "<table><td>".repeat(300));
        let (calls, content) = parse_calls_for(&html);

        // ~keep The page is past the default depth of the walk, so the test reads the parse
        // ~keep count. The words of such a page are a test of `parser_repair_safeguards.rs`,
        // ~keep which raises the depth of the walk.
        assert!(content.is_some());
        assert_eq!(calls, 2);
    }

    #[test]
    fn should_parse_twice_when_the_first_parse_discarded_the_end_tag_of_an_open_element() {
        // ~keep The list pass writes the end tag of an `li` and of a `dd` before the first
        // ~keep parse, so in a list no element is open at the end tag of the list: one parse.
        let mut failures = Vec::new();
        let cases = [
            ("div", "p", 2),
            ("select", "option", 2),
            ("ul", "li", 1),
            ("dl", "dd", 1),
        ];
        let words = ["one", "two", "rest", "tail"];
        for (outer, inner, expected) in cases {
            let html = format!("<{outer}><{inner}>one</{outer}>two</{inner}>rest</{outer}>tail");
            let (calls, content) = parse_calls_for(&html);
            let content = content.unwrap_or_default();
            let has_every_word = words.into_iter().all(|word| content.contains(word));
            if calls != expected || !has_every_word {
                failures.push(format!("{html:?}: {calls} parse(s), not {expected}: {content:?}"));
            }
        }
        assert!(failures.is_empty(), "{failures:#?}");
        let (calls, content) = parse_calls_for("<div><p>one</div>two</p>rest</div>tail");
        assert_eq!(content.as_deref(), Some("one\n\ntwo\n\nresttail\n"));
        assert_eq!(calls, 2);
    }

    #[test]
    fn should_parse_once_when_a_discarded_end_tag_names_no_open_element() {
        for html in [
            "<p>a</b>b</p>",
            "<div title='</div>'><p>x</p></div>",
            "<div><p>x<!-- </div> --></p></div>",
        ] {
            let (calls, content) = parse_calls_for(html);

            assert_eq!(calls, 1, "{html:?}");
            assert!(content.is_some(), "{html:?}");
        }
    }

    #[test]
    fn should_parse_once_when_the_open_element_has_no_content() {
        for html in ["<p>one</p><br>", "<p>one</p><span>", "<html><body><p>one</p><hr>"] {
            let (calls, content) = parse_calls_for(html);

            assert_eq!(calls, 1, "{html:?}");
            assert!(content.is_some_and(|content| content.starts_with("one\n")), "{html:?}");
        }
    }

    #[test]
    fn should_parse_once_when_an_attribute_value_holds_an_end_tag() {
        let (calls, content) = parse_calls_for("<p>one</p><div title='</div>'></div>");

        assert_eq!(content.as_deref(), Some("one\n"));
        assert_eq!(calls, 1);
    }

    #[test]
    fn should_convert_the_first_parse_when_the_repaired_page_holds_less_text() {
        // ~keep `tl` leaves a `<frame>` open, so the first page looks like one with no end tag.
        // ~keep The second call is the parse of the repaired page, which is measured and left.
        for (html, expected) in [
            (
                "<frameset><frame></frameset><div><p>one</p></div><p>tail</p>",
                "one\n\ntail\n",
            ),
            ("<FRAMESET></FRAMESET><div><p>one</div>tail", "onetail\n"),
            ("<noframes><div></noframes><div><p>one</p></div>tail", "one\n\ntail\n"),
        ] {
            let (calls, content) = parse_calls_for(html);

            assert_eq!(content.as_deref(), Some(expected), "{html:?}");
            assert_eq!(calls, 2, "{html:?}");
        }
    }

    #[test]
    fn should_log_at_debug_that_a_repair_that_loses_text_is_not_used() {
        assert_eq!(
            repair_events("<frameset><frame></frameset><div><p>one</p></div><p>tail</p>"),
            [(
                tracing::Level::DEBUG,
                "html5ever repair would lose text; proceeding with original structure".to_string()
            )]
        );
    }

    type Events = std::sync::Arc<std::sync::Mutex<Vec<(tracing::Level, String)>>>;

    struct EventLog(Events);

    struct Message<'a>(&'a mut String);

    impl tracing::field::Visit for Message<'_> {
        fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
            if field.name() == "message" {
                *self.0 = format!("{value:?}");
            }
        }
    }

    impl tracing::Subscriber for EventLog {
        fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool {
            true
        }
        fn new_span(&self, _attributes: &tracing::span::Attributes<'_>) -> tracing::span::Id {
            tracing::span::Id::from_u64(1)
        }
        fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {}
        fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {}
        fn event(&self, event: &tracing::Event<'_>) {
            let mut message = String::new();
            event.record(&mut Message(&mut message));
            self.0
                .lock()
                .expect("event log")
                .push((*event.metadata().level(), message));
        }
        fn enter(&self, _span: &tracing::span::Id) {}
        fn exit(&self, _span: &tracing::span::Id) {}
    }

    fn repair_events(html: &str) -> Vec<(tracing::Level, String)> {
        let events = Events::default();
        tracing::subscriber::with_default(EventLog(Events::clone(&events)), || {
            // ~keep A callsite keeps the interest of the thread that reaches it first, and a
            // ~keep test on another thread reaches these with no subscriber. So the first
            // ~keep conversion only reaches them, and the interest is then asked again.
            parse_calls_for(html);
            tracing::callsite::rebuild_interest_cache();
            events.lock().expect("event log").clear();
            parse_calls_for(html);
        });
        let events = events.lock().expect("event log");
        events
            .iter()
            .filter(|(_, message)| message.contains("html5ever repair"))
            .cloned()
            .collect()
    }

    #[test]
    fn should_log_the_second_parse_at_debug_for_an_omitted_end_tag_and_warn_for_a_misnest() {
        assert_eq!(
            repair_events("<div><p>one</div>tail"),
            [(
                tracing::Level::DEBUG,
                "element with no end tag; re-parsed with html5ever repair".to_string()
            )]
        );
        assert_eq!(
            repair_events("<b><p>one</p></b>"),
            [(
                tracing::Level::WARN,
                "misnested HTML elements detected; re-parsed with html5ever repair".to_string()
            )]
        );
    }

    #[test]
    fn should_warn_of_a_misnest_when_it_nests_past_the_repair_depth_limit() {
        // ~keep No cell has an end tag, and the tree builder nests past its depth limit. The
        // ~keep repair that the page then takes is the one for a misnest.
        let html = format!("{}x", "<table><td>".repeat(300));

        assert_eq!(
            repair_events(&html),
            [(
                tracing::Level::WARN,
                "misnested HTML elements detected; re-parsed with html5ever repair".to_string()
            )]
        );
    }

    #[test]
    fn should_fail_once_when_input_exceeds_parser_capacity() {
        let options = ConversionOptions {
            tier_strategy: TierStrategy::Tier2,
            ..ConversionOptions::default()
        };
        PARSE_CALLS.with(|calls| calls.set(0));
        FORCE_INVALID_LENGTH.with(|forced| forced.set(true));

        let result = convert("<p>oversized</p>", options);

        FORCE_INVALID_LENGTH.with(|forced| forced.set(false));
        assert!(matches!(
            result,
            Err(ConversionError::ParseError(message)) if message == "Failed to parse HTML"
        ));
        PARSE_CALLS.with(|calls| assert_eq!(calls.get(), 1));
    }
}