Skip to main content

tabnas_markdown/
inline.rs

1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3//! Phase 2 of the CommonMark parse (spec 0.31.2, Appendix A, "Phase 2:
4//! inline structure"). Port of `ts/src/inline.ts` (canonical) and
5//! `go/inline.go`; keep the three in step. The block phase left the raw
6//! text of every paragraph and heading in `string_content`; this module
7//! turns that text into inline children and clears it.
8//!
9//! The shape is the spec's own algorithm: one left-to-right scan over the
10//! subject that appends nodes as it goes, plus two auxiliary stacks that
11//! are resolved out of band, because neither construct can be decided at
12//! the point where its opener is seen:
13//!
14//! - the delimiter stack (section 6.4) holds `*` / `_` (and, under GFM,
15//!   `~`) runs, and is resolved by `process_emphasis`;
16//! - the bracket stack (section 6.3) holds `[` and `![`, and is resolved
17//!   by `parse_close_bracket` when a `]` turns up.
18//!
19//! Everything else (code spans, autolinks, raw HTML, entities, escapes,
20//! breaks) is decided locally at the scan position. That is what produces
21//! the precedence section 6.3 requires: a code span, autolink or raw HTML
22//! tag is consumed whole during the scan, so it binds more tightly than
23//! emphasis and more tightly than the brackets of a link label. Conversely
24//! brackets bind more tightly than emphasis, because bracket matching
25//! happens during the scan while emphasis matching happens afterwards over
26//! the delimiter stack.
27//!
28//! What differs from the TypeScript, and why (the same list as the Go port):
29//!
30//! - The subject is scanned by BYTE offset. Every character the scan
31//!   branches on is ASCII, and no UTF-8 continuation byte can collide with
32//!   an ASCII value, so byte scanning is exact. Wherever a whole
33//!   *character* is needed (emphasis flanking above all) the character is
34//!   decoded before being handed to the Unicode classifiers.
35//! - The sticky (`y`) regexes become `^`-anchored patterns matched against
36//!   `subject[pos..]`.
37//! - `parse_link_label` and the small whitespace regexes are hand-coded
38//!   loops. The label pattern's `{0,1000}` repeat of an alternation would
39//!   expand to a thousand copies under a linear-time engine, and the rest
40//!   are cheaper as loops.
41//! - The delimiter stack is a slab of entries linked by index rather than
42//!   by pointer, and the bracket stack is a vector; both are what the
43//!   arena tree asks for.
44
45use std::collections::HashMap;
46use std::sync::OnceLock;
47
48use regex::Regex;
49
50use crate::common::{
51    decode_entity, is_escapable, is_unicode_punctuation, is_unicode_whitespace, js_trim,
52    normalize_reference, unescape_string, ENTITY_PATTERN, ESCAPABLE_ASCII,
53};
54use crate::node::{MdNode, NodeId, NodeType, Tree};
55use crate::options::{Options, RefDef, RefMap};
56
57// --- Section 6.6 raw HTML: the tag grammar, spelled out because it is
58// stricter than `<[^>]*>` in every part. Attribute names are
59// XML-restricted-to-ASCII; unquoted attribute values exclude quotes, `=`,
60// `<`, `>`, backtick and all control characters; comments, PIs,
61// declarations and CDATA each have their own terminator. `INLINE_SPACE*`
62// stands in for "spaces, tabs, and up to one line ending": a paragraph can
63// never contain a blank line, so a single run can only ever span one line
64// ending anyway.
65
66/// JavaScript's `\s`, spelled out: the `regex` crate's `\s` is a different
67/// set, so using it here would reject tags the TypeScript accepts.
68const INLINE_SPACE: &str = "[ \\t\\n\\x0B\\x0C\\r\
69\\x{00a0}\\x{1680}\\x{2000}-\\x{200a}\\x{2028}\\x{2029}\\x{202f}\\x{205f}\\x{feff}\\x{3000}]";
70
71const INLINE_TAG_NAME: &str = "[A-Za-z][A-Za-z0-9-]*";
72const INLINE_ATTRIBUTE_NAME: &str = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
73const INLINE_UNQUOTED_VALUE: &str = "[^\"'=<>`\\x00-\\x20]+";
74const INLINE_SINGLE_QUOTED_VALUE: &str = "'[^']*'";
75const INLINE_DOUBLE_QUOTED_VALUE: &str = "\"[^\"]*\"";
76
77/// Section 6.6: `<!-->` and `<!--->` are comments in their own right;
78/// otherwise the body simply may not contain `-->`, which the lazy
79/// quantifier enforces.
80const INLINE_HTML_COMMENT: &str = r"<!-->|<!--->|<!--[\s\S]*?-->";
81const INLINE_PROCESSING_INSTRUCTION: &str = r"[<][?][\s\S]*?[?][>]";
82const INLINE_DECLARATION: &str = "<![A-Za-z][^>]*>";
83/// The TypeScript compiles the whole tag pattern with the `i` flag, which
84/// here only ever matters for the literal `CDATA`; every other letter in
85/// the grammar is already spelled in both cases. Written out rather than
86/// left to `(?i)`, because the `regex` crate folds case over all of
87/// Unicode: `(?i)[A-Za-z]` also matches U+017F LATIN SMALL LETTER LONG S
88/// and U+212A KELVIN SIGN, where JavaScript's non-unicode `i` does not.
89const INLINE_CDATA: &str = r"<!\[[cC][dD][aA][tT][aA]\[[\s\S]*?\]\]>";
90
91/// JavaScript's `.` without the `s` flag: it excludes `\n`, `\r`, U+2028
92/// and U+2029.
93const INLINE_JS_DOT: &str = r"[^\n\r\x{2028}\x{2029}]";
94
95fn re_html_tag() -> &'static Regex {
96    static RE: OnceLock<Regex> = OnceLock::new();
97    RE.get_or_init(|| {
98        let attribute_value = format!(
99            "(?:{INLINE_UNQUOTED_VALUE}|{INLINE_SINGLE_QUOTED_VALUE}|{INLINE_DOUBLE_QUOTED_VALUE})"
100        );
101        let attribute_value_spec = format!("(?:{INLINE_SPACE}*={INLINE_SPACE}*{attribute_value})");
102        let attribute = format!("(?:{INLINE_SPACE}+{INLINE_ATTRIBUTE_NAME}{attribute_value_spec}?)");
103        let open_tag = format!("<{INLINE_TAG_NAME}{attribute}*{INLINE_SPACE}*/?>");
104        let close_tag = format!("</{INLINE_TAG_NAME}{INLINE_SPACE}*>");
105        Regex::new(&format!(
106            "^(?:{open_tag}|{close_tag}|{INLINE_HTML_COMMENT}|{INLINE_PROCESSING_INSTRUCTION}|{INLINE_DECLARATION}|{INLINE_CDATA})"
107        ))
108        .expect("the raw HTML pattern compiles")
109    })
110}
111
112fn re_entity_here() -> &'static Regex {
113    static RE: OnceLock<Regex> = OnceLock::new();
114    RE.get_or_init(|| {
115        Regex::new(&format!("^(?:{ENTITY_PATTERN})")).expect("a literal pattern compiles")
116    })
117}
118
119/// Section 6.3 link destination, pointy-bracket form: no line endings, no
120/// unescaped `<` or `>`.
121fn re_link_destination_braces() -> &'static Regex {
122    static RE: OnceLock<Regex> = OnceLock::new();
123    RE.get_or_init(|| {
124        Regex::new(&format!(r"^<(?:[^<>\n\\\x00]|\\{INLINE_JS_DOT})*>"))
125            .expect("a literal pattern compiles")
126    })
127}
128
129/// Section 6.3 link title in `"`, `'` or `(...)` delimiters. The escape
130/// alternative comes first so that `\"` inside a double-quoted title is
131/// consumed as an escape rather than closing the title.
132fn re_link_title() -> &'static Regex {
133    static RE: OnceLock<Regex> = OnceLock::new();
134    RE.get_or_init(|| {
135        let escaped = format!(r"\\[{}]", regex::escape(ESCAPABLE_ASCII));
136        Regex::new(&format!(
137            "^(?:\"(?:{escaped}|[^\"\\x00])*\"|'(?:{escaped}|[^'\\x00])*'|\\((?:{escaped}|[^()\\x00])*\\))"
138        ))
139        .expect("a literal pattern compiles")
140    })
141}
142
143/// Section 6.5 autolinks. Scheme: an ASCII letter then 1 to 31 more of
144/// letter / digit / `+` / `.` / `-`, i.e. 2 to 32 characters in total.
145fn re_autolink() -> &'static Regex {
146    static RE: OnceLock<Regex> = OnceLock::new();
147    RE.get_or_init(|| {
148        Regex::new(r"^<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*>")
149            .expect("a literal pattern compiles")
150    })
151}
152
153fn re_email_autolink() -> &'static Regex {
154    static RE: OnceLock<Regex> = OnceLock::new();
155    RE.get_or_init(|| {
156        Regex::new(
157            "^<([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+\
158@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\
159(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>",
160        )
161        .expect("a literal pattern compiles")
162    })
163}
164
165/// Maximum `(` nesting inside a bare link destination. The spec describes
166/// balanced parentheses without stating a bound; cmark uses 32, and the
167/// bound is what keeps an unbalanced run from being quadratic (see
168/// `scan_link_destination`).
169const MAX_LINK_PAREN_NESTING: usize = 32;
170
171/// The most inline containers (emphasis, strong emphasis, strikethrough,
172/// links and images) that may nest inside one block. A delimiter pair,
173/// link or image whose content already holds that many nested containers
174/// stays literal text.
175///
176/// The reason is the same as `block::MAX_CONTAINER_NESTING` (see there
177/// for the measurements): each wrapper is two levels of the projected
178/// `tabnas::Value`, whose destructor and `to_json` recurse per level, and
179/// `****x****` nests one `strong` per two stars a side. The canonical
180/// TypeScript has no such limit; `DIVERGENCE.md` records it, and
181/// `tests/robust_test.rs` pins the boundary.
182pub const MAX_INLINE_NESTING: usize = 50;
183
184/// The code span search memo, cmark's `backticks[]`: the start of the
185/// last backtick run of each length that a scan has passed, and whether
186/// a scan has reached the end of the subject. Once one has, every run
187/// after that scan's start is on record, so an opener whose length has
188/// no run ahead of it is refused without rescanning. Without it, a
189/// subject holding unmatched runs of distinct lengths rescanned its whole
190/// tail once per run.
191///
192/// An entry only ever moves forward. A scan that succeeds part way stops
193/// before the last run of its length, and letting it overwrite the
194/// position a full scan recorded would hide a later closer from the next
195/// opener.
196#[derive(Debug, Clone, Default)]
197pub struct BacktickMemo {
198    last_run: HashMap<usize, usize>,
199    scanned_to_end: bool,
200}
201
202fn text_node(tree: &mut Tree, literal: &str) -> NodeId {
203    let mut node = MdNode::new(NodeType::Text);
204    node.literal = literal.to_string();
205    tree.add(node)
206}
207
208/// Whether a byte can start an inline construct, i.e. whether it
209/// terminates a run of ordinary text. The TypeScript spells this as the
210/// negated classes of `reMain` / `reMainGfm`; `~` is only special under
211/// GFM.
212fn is_inline_special_byte(c: u8, gfm: bool) -> bool {
213    match c {
214        b'\n' | b'`' | b'[' | b']' | b'\\' | b'!' | b'<' | b'&' | b'*' | b'_' => true,
215        b'~' => gfm,
216        _ => false,
217    }
218}
219
220/// The TypeScript's `reWhitespaceChar`, `/[ \t\n\v\f\r]/`.
221fn is_inline_whitespace_byte(c: u8) -> bool {
222    matches!(c, b' ' | b'\t' | b'\n' | b'\x0B' | b'\x0C' | b'\r')
223}
224
225/// Drop `n` bytes from the end of a delimiter run's literal. The literal is
226/// a run of ASCII `*`, `_` or `~`, so bytes and characters agree.
227fn trim_delim_tail(s: &mut String, n: usize) {
228    let keep = s.len().saturating_sub(n);
229    s.truncate(keep);
230}
231
232/// One `*`, `_` or `~` run on the delimiter stack (section 6.4).
233#[derive(Debug, Clone)]
234struct Delimiter {
235    /// The delimiter character.
236    cc: u8,
237    /// Delimiters still unused; drops as pairs are consumed.
238    numdelims: usize,
239    /// Run length as originally scanned, what the rule of three is computed
240    /// on.
241    origdelims: usize,
242    node: NodeId,
243    previous: Option<usize>,
244    next: Option<usize>,
245    can_open: bool,
246    can_close: bool,
247}
248
249/// One `[` or `![` on the bracket stack (section 6.3).
250#[derive(Debug, Clone)]
251struct Bracket {
252    node: NodeId,
253    /// Top of the delimiter stack when this bracket opened: the emphasis
254    /// floor.
255    previous_delimiter: Option<usize>,
256    /// Offset of the `[` in the subject.
257    index: usize,
258    image: bool,
259    /// Cleared on earlier openers once a link is built: no links in links.
260    active: bool,
261    /// Another bracket opened after this one, so its text contains a `[`.
262    bracket_after: bool,
263}
264
265/// What `scan_delimiter_run` reports about a run.
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub struct DelimScan {
268    pub numdelims: usize,
269    pub can_open: bool,
270    pub can_close: bool,
271}
272
273// --- pure recognizers -------------------------------------------------------
274//
275// Recognition split from node building: each function inspects `subject`
276// at `pos` and reports what it found, moving nothing and touching no tree.
277// The scanner methods below delegate to them, and they are public so any
278// other driver over the same syntax shares this exact recognition logic
279// instead of reimplementing it.
280
281/// Apply a `^`-anchored regex at `pos`; the match text, or `None`.
282fn regex_at<'s>(re: &Regex, subject: &'s str, pos: usize) -> Option<&'s str> {
283    re.find(&subject[pos..])
284        .map(|m| &subject[pos + m.start()..pos + m.end()])
285}
286
287/// The whole character ending at `end`, so an astral character is
288/// classified as one character by the flanking rules rather than as a
289/// stray byte. Start of subject counts as a line ending (section 6.4).
290pub fn code_point_before(subject: &str, end: usize) -> char {
291    if end == 0 {
292        return '\n';
293    }
294    subject[..end].chars().next_back().unwrap_or('\n')
295}
296
297/// The whole character at `i`; end of subject counts as a line ending.
298pub fn code_point_at(subject: &str, i: usize) -> char {
299    if i >= subject.len() {
300        return '\n';
301    }
302    subject[i..].chars().next().unwrap_or('\n')
303}
304
305/// The end of the run of spaces starting at `pos`.
306pub fn skip_initial_spaces(subject: &str, mut pos: usize) -> usize {
307    let bytes = subject.as_bytes();
308    while pos < bytes.len() && bytes[pos] == b' ' {
309        pos += 1;
310    }
311    pos
312}
313
314/// The end of "spaces, and at most one line ending" starting at `pos`
315/// (section 6.3).
316pub fn match_spnl(subject: &str, pos: usize) -> usize {
317    let mut pos = skip_initial_spaces(subject, pos);
318    if pos < subject.len() && subject.as_bytes()[pos] == b'\n' {
319        pos = skip_initial_spaces(subject, pos + 1);
320    }
321    pos
322}
323
324/// A code span (section 6.3), or an unmatched opener, which is literal
325/// text.
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub enum CodeSpanScan {
328    Closed { end: usize, literal: String },
329    Open { end: usize, ticks: String },
330}
331
332/// The code span starting at `pos`: a backtick string to the next backtick
333/// string of *exactly* the same length. `None` when no backtick run starts
334/// at `pos`.
335///
336/// Hand-coded rather than the TypeScript's sticky and global regexes, so
337/// that no regex is built from an input-derived run length.
338pub fn scan_code_span(subject: &str, pos: usize) -> Option<CodeSpanScan> {
339    scan_code_span_memo(subject, pos, &mut BacktickMemo::default())
340}
341
342/// [`scan_code_span`] with the search memo the inline parser keeps per
343/// block, so that a subject full of unmatched runs is scanned once.
344pub fn scan_code_span_memo(
345    subject: &str,
346    pos: usize,
347    memo: &mut BacktickMemo,
348) -> Option<CodeSpanScan> {
349    let s = subject.as_bytes();
350    let mut i = pos;
351    while i < s.len() && s[i] == b'`' {
352        i += 1;
353    }
354    if i == pos {
355        return None;
356    }
357    let tick_len = i - pos;
358    let after_open_ticks = i;
359
360    // A full scan has been past here: a closer exists only if a run of
361    // this length was recorded after the opener.
362    if memo.scanned_to_end && memo.last_run.get(&tick_len).is_none_or(|&last| last <= pos) {
363        return Some(CodeSpanScan::Open {
364            end: after_open_ticks,
365            ticks: subject[pos..after_open_ticks].to_string(),
366        });
367    }
368
369    while i < s.len() {
370        if s[i] != b'`' {
371            i += 1;
372            continue;
373        }
374        let run_start = i;
375        while i < s.len() && s[i] == b'`' {
376            i += 1;
377        }
378        let run_len = i - run_start;
379        memo.last_run
380            .entry(run_len)
381            .and_modify(|last| *last = (*last).max(run_start))
382            .or_insert(run_start);
383        if run_len == tick_len {
384            // Line endings become spaces; then one leading and one trailing
385            // space are stripped together, but only if the content is not
386            // all spaces (which is what lets a code span hold backticks).
387            let contents = subject[after_open_ticks..i - tick_len].replace('\n', " ");
388            let has_non_space = contents.bytes().any(|b| b != b' ');
389            let literal = if contents.len() > 2
390                && contents.starts_with(' ')
391                && contents.ends_with(' ')
392                && has_non_space
393            {
394                contents[1..contents.len() - 1].to_string()
395            } else {
396                contents
397            };
398            return Some(CodeSpanScan::Closed { end: i, literal });
399        }
400    }
401
402    memo.scanned_to_end = true;
403    Some(CodeSpanScan::Open {
404        end: after_open_ticks,
405        ticks: subject[pos..after_open_ticks].to_string(),
406    })
407}
408
409/// How a backslash escape resolves (sections 6.1 and 6.7).
410#[derive(Debug, Clone, PartialEq, Eq)]
411pub enum EscapeKind {
412    Linebreak,
413    Char,
414    Literal,
415}
416
417#[derive(Debug, Clone, PartialEq, Eq)]
418pub struct EscapeScan {
419    pub kind: EscapeKind,
420    pub literal: String,
421    pub end: usize,
422}
423
424/// The backslash escape with `pos` at the backslash. Always succeeds: a
425/// backslash before anything unescapable is a literal backslash. The
426/// linebreak form consumes the following line's leading spaces.
427pub fn scan_escape(subject: &str, pos: usize) -> EscapeScan {
428    let bytes = subject.as_bytes();
429    let next = pos + 1;
430    if next < bytes.len() && bytes[next] == b'\n' {
431        return EscapeScan {
432            kind: EscapeKind::Linebreak,
433            literal: String::new(),
434            end: skip_initial_spaces(subject, next + 1),
435        };
436    }
437    if next < bytes.len() && is_escapable(bytes[next]) {
438        return EscapeScan {
439            kind: EscapeKind::Char,
440            literal: subject[next..next + 1].to_string(),
441            end: next + 1,
442        };
443    }
444    EscapeScan {
445        kind: EscapeKind::Literal,
446        literal: "\\".to_string(),
447        end: next,
448    }
449}
450
451/// An email or URI autolink in angle brackets (section 6.5).
452#[derive(Debug, Clone, PartialEq, Eq)]
453pub struct AngleAutolinkScan {
454    pub dest: String,
455    pub label: String,
456    pub end: usize,
457}
458
459pub fn scan_angle_autolink(subject: &str, pos: usize) -> Option<AngleAutolinkScan> {
460    if let Some(m) = regex_at(re_email_autolink(), subject, pos) {
461        let dest = &m[1..m.len() - 1];
462        return Some(AngleAutolinkScan {
463            dest: format!("mailto:{dest}"),
464            label: dest.to_string(),
465            end: pos + m.len(),
466        });
467    }
468    if let Some(m) = regex_at(re_autolink(), subject, pos) {
469        let dest = &m[1..m.len() - 1];
470        return Some(AngleAutolinkScan {
471            dest: dest.to_string(),
472            label: dest.to_string(),
473            end: pos + m.len(),
474        });
475    }
476    None
477}
478
479/// A raw HTML tag (section 6.6) at `pos`: open, close, comment, PI,
480/// declaration or CDATA. Returns the raw text and the end offset.
481pub fn scan_html_tag(subject: &str, pos: usize) -> Option<(String, usize)> {
482    regex_at(re_html_tag(), subject, pos).map(|m| (m.to_string(), pos + m.len()))
483}
484
485/// An entity or numeric character reference (section 6.2), decoded.
486/// Returns the decoded text and the end offset.
487pub fn scan_entity(subject: &str, pos: usize) -> Option<(String, usize)> {
488    regex_at(re_entity_here(), subject, pos).map(|m| (decode_entity(m), pos + m.len()))
489}
490
491/// Classify the run of `cc` starting at `pos` without consuming it
492/// (section 6.4): a run is left-flanking iff it is not followed by Unicode
493/// whitespace and either not followed by Unicode punctuation or else
494/// preceded by whitespace or punctuation; right-flanking is the mirror
495/// image. `_` additionally may not open inside a word (rules 2, 4, 6, 8),
496/// which is what keeps `snake_case_words` intact; `*` has no such
497/// restriction.
498///
499/// The two neighbouring characters are decoded as characters, not read as
500/// bytes: classify `é` or `。` by its first UTF-8 byte and most of section
501/// 6.4 silently breaks on non-ASCII input.
502pub fn scan_delimiter_run(subject: &str, pos: usize, cc: u8) -> Option<DelimScan> {
503    let bytes = subject.as_bytes();
504    let mut numdelims = 0;
505    let mut p = pos;
506    while p < bytes.len() && bytes[p] == cc {
507        numdelims += 1;
508        p += 1;
509    }
510    if numdelims == 0 {
511        return None;
512    }
513
514    let char_before = code_point_before(subject, pos);
515    let char_after = code_point_at(subject, p);
516
517    let after_is_whitespace = is_unicode_whitespace(char_after);
518    let after_is_punctuation = is_unicode_punctuation(char_after);
519    let before_is_whitespace = is_unicode_whitespace(char_before);
520    let before_is_punctuation = is_unicode_punctuation(char_before);
521
522    let left_flanking = !after_is_whitespace
523        && (!after_is_punctuation || before_is_whitespace || before_is_punctuation);
524    let right_flanking = !before_is_whitespace
525        && (!before_is_punctuation || after_is_whitespace || after_is_punctuation);
526
527    let (can_open, can_close) = if cc == b'_' {
528        (
529            left_flanking && (!right_flanking || before_is_punctuation),
530            right_flanking && (!left_flanking || after_is_punctuation),
531        )
532    } else {
533        (left_flanking, right_flanking)
534    };
535
536    Some(DelimScan {
537        numdelims,
538        can_open,
539        can_close,
540    })
541}
542
543/// How a line ending resolves (sections 6.7 and 6.8), given the literal of
544/// the text node immediately before it (`None` when that node is absent or
545/// not text). Two or more trailing spaces make a hard break; `trim` says
546/// the trailing spaces must be dropped from that node either way. Returns
547/// `(hard, trim)`.
548pub fn classify_break(prev_text_literal: Option<&str>) -> (bool, bool) {
549    let Some(prev) = prev_text_literal else {
550        return (false, false);
551    };
552    let bytes = prev.as_bytes();
553    if bytes.last() != Some(&b' ') {
554        return (false, false);
555    }
556    (bytes.len() > 1 && bytes[bytes.len() - 2] == b' ', true)
557}
558
559/// A link title at `pos` (section 6.3), without its delimiters, unescaped.
560/// Returns the title and the end offset.
561pub fn scan_link_title(subject: &str, pos: usize) -> Option<(String, usize)> {
562    regex_at(re_link_title(), subject, pos)
563        .map(|m| (unescape_string(&m[1..m.len() - 1]), pos + m.len()))
564}
565
566/// A link destination at `pos` (section 6.3): either `<...>`, or a bare run
567/// with balanced unescaped parentheses and no ASCII control characters or
568/// spaces. Returns the destination and the end offset.
569///
570/// The destination is backslash-unescaped and entity-decoded, but **not**
571/// percent-encoded: `[l](/ä)` yields `/ä`, not `/%C3%A4`. Encoding is a
572/// rendering concern and `html.rs` applies `normalize_uri` when it writes
573/// the attribute; the public AST promises the decoded form.
574pub fn scan_link_destination(subject: &str, pos: usize) -> Option<(String, usize)> {
575    if let Some(braced) = regex_at(re_link_destination_braces(), subject, pos) {
576        return Some((
577            unescape_string(&braced[1..braced.len() - 1]),
578            pos + braced.len(),
579        ));
580    }
581    let bytes = subject.as_bytes();
582    if pos < bytes.len() && bytes[pos] == b'<' {
583        return None;
584    }
585
586    let mut p = pos;
587    let mut openparens = 0usize;
588
589    while p < bytes.len() {
590        let c = bytes[p];
591        if c == b'\\' && p + 1 < bytes.len() && is_escapable(bytes[p + 1]) {
592            p += 1;
593            if p < bytes.len() {
594                p += 1;
595            }
596        } else if c == b'(' {
597            // Bail rather than scan on once nesting passes the limit.
598            // Without this, input like `[a](b` repeated makes every `]`
599            // scan to end of input looking for parens that never balance,
600            // which is quadratic in the document size. cmark caps nesting
601            // at the same depth, and no spec example nests more than two
602            // deep.
603            if openparens >= MAX_LINK_PAREN_NESTING {
604                return None;
605            }
606            p += 1;
607            openparens += 1;
608        } else if c == b')' {
609            if openparens < 1 {
610                break;
611            }
612            p += 1;
613            openparens -= 1;
614        } else if c <= b' ' || c == 0x7F {
615            // Spaces and ASCII control characters end the bare form.
616            break;
617        } else {
618            p += 1;
619        }
620    }
621
622    // An empty destination is only legal immediately before the closing
623    // paren of an inline link, as in `[link]()`.
624    if p == pos && !(p < bytes.len() && bytes[p] == b')') {
625        return None;
626    }
627    if openparens != 0 {
628        return None;
629    }
630
631    Some((unescape_string(&subject[pos..p]), p))
632}
633
634/// A link label at `pos` (sections 4.7 and 6.3), brackets included.
635/// Returns `(raw_length, length)`: `raw_length` is what was consumed, and
636/// `length` is 0 when the label is too long to be valid (at most 999
637/// characters between the brackets). `None` when no label is here at all.
638///
639/// Hand-coded where the TypeScript uses `/\[(?:[^\\[\]]|\\.){0,1000}\]/sy`.
640/// The scan accepts the same language: every alternative of the repeat
641/// begins on a character that is not `]`, so shortening the greedy run can
642/// only put a non-`]` where the closing bracket must be.
643pub fn scan_link_label(subject: &str, pos: usize) -> Option<(usize, usize)> {
644    let s = subject.as_bytes();
645    if pos >= s.len() || s[pos] != b'[' {
646        return None;
647    }
648
649    let mut i = pos + 1;
650    let mut iters = 0;
651    // Length in UTF-16 code units, which is the unit the TypeScript's
652    // `m.length > 1001` test counts in, hence the 2 for an astral character
653    // below.
654    let mut units = 1;
655
656    loop {
657        if i >= s.len() {
658            return None;
659        }
660        let c = s[i];
661        if c == b']' {
662            i += 1;
663            units += 1;
664            let raw = i - pos;
665            // Section 4.7: at most 999 characters between the brackets.
666            if units > 1001 {
667                return Some((raw, 0));
668            }
669            return Some((raw, raw));
670        }
671        // An unescaped `[` cannot be consumed by the repeat, and is not the
672        // `]` the pattern then demands. Nor can a 1001st repeat run.
673        if c == b'[' || iters == 1000 {
674            return None;
675        }
676        if c == b'\\' {
677            // `\\.`: with the `s` flag, any character at all, line endings
678            // included.
679            i += 1;
680            units += 1;
681            if i >= s.len() {
682                return None;
683            }
684        }
685        let ch = code_point_at(subject, i);
686        i += ch.len_utf8();
687        units += ch.len_utf16();
688        iters += 1;
689    }
690}
691
692/// The `(destination "title")` tail of an inline link.
693#[derive(Debug, Clone, PartialEq, Eq)]
694pub struct LinkTailScan {
695    pub dest: String,
696    pub title: Option<String>,
697    pub end: usize,
698}
699
700/// The inline-link tail with `pos` just after the `]`. `None` unless the
701/// whole tail, through the closing paren, is present.
702pub fn scan_inline_link_tail(subject: &str, pos: usize) -> Option<LinkTailScan> {
703    let bytes = subject.as_bytes();
704    if pos >= bytes.len() || bytes[pos] != b'(' {
705        return None;
706    }
707
708    let mut p = match_spnl(subject, pos + 1);
709    let (dest, d_end) = scan_link_destination(subject, p)?;
710
711    p = match_spnl(subject, d_end);
712    let mut title = None;
713    // A title has to be separated from the destination by whitespace, so
714    // `[a](/url"t")` is not a titled link.
715    if p >= 1 && p - 1 < bytes.len() && is_inline_whitespace_byte(bytes[p - 1]) {
716        if let Some((t, t_end)) = scan_link_title(subject, p) {
717            title = Some(t);
718            p = t_end;
719        }
720    }
721    p = match_spnl(subject, p);
722
723    if p < bytes.len() && bytes[p] == b')' {
724        return Some(LinkTailScan {
725            dest,
726            title,
727            end: p + 1,
728        });
729    }
730    None
731}
732
733/// The inline scanner: the subject, the scan position, and the two
734/// auxiliary stacks.
735pub struct InlineParser {
736    pub subject: String,
737    pub pos: usize,
738    delims: Vec<Delimiter>,
739    /// Top of the delimiter stack, as an index into `delims`.
740    delim_top: Option<usize>,
741    brackets: Vec<Bracket>,
742    pub refmap: RefMap,
743    pub options: Options,
744    /// The nesting height of every inline container made for the current
745    /// block: 1 for one wrapping only leaves, and one more per level.
746    /// Leaves are absent and count 0. `MAX_INLINE_NESTING` is judged from
747    /// it; see `run_height`.
748    nesting: HashMap<NodeId, usize>,
749    /// The code span search memo for the current block's subject.
750    backticks: BacktickMemo,
751}
752
753impl InlineParser {
754    pub fn new(refmap: RefMap, options: Options) -> Self {
755        InlineParser {
756            subject: String::new(),
757            pos: 0,
758            delims: Vec::new(),
759            delim_top: None,
760            brackets: Vec::new(),
761            refmap,
762            options,
763            nesting: HashMap::new(),
764            backticks: BacktickMemo::default(),
765        }
766    }
767
768    /// The tallest nesting height among the siblings from `from` up to
769    /// but not including `until` (or to the end of the run). Stops at
770    /// `MAX_INLINE_NESTING`, the only threshold the callers compare
771    /// against, so the walk never costs more than it decides.
772    fn run_height(&self, tree: &Tree, from: Option<NodeId>, until: Option<NodeId>) -> usize {
773        let mut height = 0;
774        let mut cur = from;
775        while let Some(id) = cur {
776            if cur == until || height >= MAX_INLINE_NESTING {
777                break;
778            }
779            height = height.max(self.nesting.get(&id).copied().unwrap_or(0));
780            cur = tree.get(id).next;
781        }
782        height
783    }
784
785    // --- scanning primitives ---
786
787    /// The byte at `pos`, or `None` at the end of the subject.
788    fn peek(&self) -> Option<u8> {
789        self.subject.as_bytes().get(self.pos).copied()
790    }
791
792    /// Spaces, and at most one line ending, between the parts of a link.
793    fn spnl(&mut self) {
794        self.pos = match_spnl(&self.subject, self.pos);
795    }
796
797    fn skip_spaces(&mut self) {
798        self.pos = skip_initial_spaces(&self.subject, self.pos);
799    }
800
801    /// The TypeScript's `reIndent`, `/ {0,3}/y`.
802    fn skip_indent(&mut self) {
803        let bytes = self.subject.as_bytes();
804        let mut n = 0;
805        while n < 3 && self.pos < bytes.len() && bytes[self.pos] == b' ' {
806            self.pos += 1;
807            n += 1;
808        }
809    }
810
811    /// The TypeScript's `reSpaceAtEndOfLine`, `/ *(?:\n|$)/y`. On failure
812    /// `pos` is left alone, as a failed sticky match would leave it.
813    fn space_at_end_of_line(&mut self) -> bool {
814        let bytes = self.subject.as_bytes();
815        let mut i = self.pos;
816        while i < bytes.len() && bytes[i] == b' ' {
817            i += 1;
818        }
819        if i < bytes.len() {
820            if bytes[i] != b'\n' {
821                return false;
822            }
823            i += 1;
824        }
825        self.pos = i;
826        true
827    }
828
829    // --- section 6.3 code spans ---
830
831    /// A code span runs from a backtick string to the next backtick string
832    /// of *exactly* the same length. Unmatched opening backticks are
833    /// literal text.
834    pub fn parse_backticks(&mut self, tree: &mut Tree, block: NodeId) -> bool {
835        let Some(scan) = scan_code_span_memo(&self.subject, self.pos, &mut self.backticks) else {
836            return false;
837        };
838        match scan {
839            CodeSpanScan::Closed { end, literal } => {
840                self.pos = end;
841                let mut node = MdNode::new(NodeType::Code);
842                node.literal = literal;
843                let id = tree.add(node);
844                tree.append_child(block, id);
845            }
846            CodeSpanScan::Open { end, ticks } => {
847                // No closing run of the same length: the opener is literal
848                // text.
849                self.pos = end;
850                let id = text_node(tree, &ticks);
851                tree.append_child(block, id);
852            }
853        }
854        true
855    }
856
857    // --- section 6.1 backslash escapes, section 6.7 hard line breaks ---
858
859    pub fn parse_backslash(&mut self, tree: &mut Tree, block: NodeId) -> bool {
860        let scan = scan_escape(&self.subject, self.pos);
861        self.pos = scan.end;
862        let id = if scan.kind == EscapeKind::Linebreak {
863            tree.new_node(NodeType::Linebreak)
864        } else {
865            text_node(tree, &scan.literal)
866        };
867        tree.append_child(block, id);
868        true
869    }
870
871    // --- section 6.5 autolinks ---
872
873    pub fn parse_autolink(&mut self, tree: &mut Tree, block: NodeId) -> bool {
874        let Some(scan) = scan_angle_autolink(&self.subject, self.pos) else {
875            return false;
876        };
877        self.pos = scan.end;
878        let id = make_autolink(tree, &scan.dest, &scan.label);
879        tree.append_child(block, id);
880        true
881    }
882
883    // --- section 6.6 raw HTML ---
884
885    pub fn parse_html_tag(&mut self, tree: &mut Tree, block: NodeId) -> bool {
886        let Some((raw, end)) = scan_html_tag(&self.subject, self.pos) else {
887            return false;
888        };
889        self.pos = end;
890        let mut node = MdNode::new(NodeType::HtmlInline);
891        node.literal = raw;
892        let id = tree.add(node);
893        tree.append_child(block, id);
894        true
895    }
896
897    // --- section 6.4 emphasis: delimiter runs and flanking ---
898
899    /// Classify the run of `cc` starting at `pos` without consuming it.
900    pub fn scan_delims(&self, cc: u8) -> Option<DelimScan> {
901        scan_delimiter_run(&self.subject, self.pos, cc)
902    }
903
904    /// Emit a delimiter run as text and push it on the delimiter stack.
905    pub fn handle_delim(&mut self, cc: u8, tree: &mut Tree, block: NodeId) -> bool {
906        let Some(res) = self.scan_delims(cc) else {
907            return false;
908        };
909
910        let numdelims = res.numdelims;
911        let startpos = self.pos;
912        self.pos += numdelims;
913
914        let node = text_node(tree, &self.subject[startpos..self.pos]);
915        tree.append_child(block, node);
916
917        // GFM strikethrough only recognises runs of one or two tildes;
918        // longer runs stay literal.
919        let stackable = if cc == b'~' { numdelims <= 2 } else { true };
920
921        if (res.can_open || res.can_close) && stackable {
922            let index = self.delims.len();
923            self.delims.push(Delimiter {
924                cc,
925                numdelims,
926                origdelims: numdelims,
927                node,
928                previous: self.delim_top,
929                next: None,
930                can_open: res.can_open,
931                can_close: res.can_close,
932            });
933            if let Some(prev) = self.delim_top {
934                self.delims[prev].next = Some(index);
935            }
936            self.delim_top = Some(index);
937        }
938
939        true
940    }
941
942    fn remove_delimiter(&mut self, delim: usize) {
943        let previous = self.delims[delim].previous;
944        let next = self.delims[delim].next;
945        if let Some(prev) = previous {
946            self.delims[prev].next = next;
947        }
948        match next {
949            // Top of stack.
950            None => self.delim_top = previous,
951            Some(n) => self.delims[n].previous = previous,
952        }
953    }
954
955    /// The spec's "process emphasis" procedure. `stack_bottom` is the
956    /// floor: for the whole-block call it is `None`, and for the inlines of
957    /// a link it is the delimiter that was on top when the link's `[`
958    /// opened.
959    pub fn process_emphasis(&mut self, tree: &mut Tree, stack_bottom: Option<usize>) {
960        // openers_bottom, keyed by (delimiter char, whether the closer can
961        // also open, closer run length mod 3). Once a closer of some class
962        // fails to find an opener, no later closer of the same class needs
963        // to look past that point either; this is what keeps the search
964        // linear.
965        let mut openers_bottom: HashMap<(u8, bool, usize), Option<usize>> = HashMap::new();
966
967        // First closer above stack_bottom.
968        let mut closer = self.delim_top;
969        while let Some(c) = closer {
970            if self.delims[c].previous == stack_bottom {
971                break;
972            }
973            closer = self.delims[c].previous;
974        }
975
976        while let Some(c) = closer {
977            if !self.delims[c].can_close {
978                closer = self.delims[c].next;
979                continue;
980            }
981
982            let closercc = self.delims[c].cc;
983            let key = (
984                closercc,
985                self.delims[c].can_open,
986                self.delims[c].origdelims % 3,
987            );
988            let bottom = openers_bottom.get(&key).copied().unwrap_or(stack_bottom);
989
990            let mut opener = self.delims[c].previous;
991            let mut opener_found = false;
992            while let Some(o) = opener {
993                if opener == stack_bottom || opener == bottom {
994                    break;
995                }
996                let od = &self.delims[o];
997                if od.cc == closercc && od.can_open {
998                    if closercc == b'~' {
999                        // GFM strikethrough: opener and closer runs must be
1000                        // the same length, so `~~x~` is not a match.
1001                        if od.numdelims == self.delims[c].numdelims {
1002                            opener_found = true;
1003                            break;
1004                        }
1005                    } else {
1006                        // Section 6.4 rules 9 and 10, the "rule of three":
1007                        // when either side of the pair could both open and
1008                        // close, the two run lengths may not sum to a
1009                        // multiple of 3, unless both are themselves
1010                        // multiples of 3.
1011                        let cd = &self.delims[c];
1012                        let odd_match = (cd.can_open || od.can_close)
1013                            && cd.origdelims % 3 != 0
1014                            && (od.origdelims + cd.origdelims) % 3 == 0;
1015                        if !odd_match {
1016                            opener_found = true;
1017                            break;
1018                        }
1019                    }
1020                }
1021                opener = od.previous;
1022            }
1023
1024            // The nesting limit: a pair whose content already holds
1025            // `MAX_INLINE_NESTING` nested containers stays literal, which
1026            // is the closer finding no opener.
1027            let mut height = 0;
1028            if let Some(o) = opener.filter(|_| opener_found) {
1029                height = self.run_height(
1030                    tree,
1031                    tree.get(self.delims[o].node).next,
1032                    Some(self.delims[c].node),
1033                );
1034                if height >= MAX_INLINE_NESTING {
1035                    opener_found = false;
1036                }
1037            }
1038
1039            let old_closer = c;
1040
1041            match opener {
1042                Some(o) if opener_found => {
1043                    // Two delimiters make strong, one makes emph;
1044                    // strikethrough always consumes the whole (equal-length)
1045                    // run.
1046                    let use_delims = if closercc == b'~' {
1047                        self.delims[c].numdelims
1048                    } else if self.delims[c].numdelims >= 2 && self.delims[o].numdelims >= 2 {
1049                        2
1050                    } else {
1051                        1
1052                    };
1053                    let node_type = if closercc == b'~' {
1054                        NodeType::Del
1055                    } else if use_delims == 1 {
1056                        NodeType::Emph
1057                    } else {
1058                        NodeType::Strong
1059                    };
1060
1061                    let opener_inl = self.delims[o].node;
1062                    let closer_inl = self.delims[c].node;
1063
1064                    self.delims[o].numdelims -= use_delims;
1065                    self.delims[c].numdelims -= use_delims;
1066                    trim_delim_tail(&mut tree.get_mut(opener_inl).literal, use_delims);
1067                    trim_delim_tail(&mut tree.get_mut(closer_inl).literal, use_delims);
1068
1069                    // Everything between the two delimiter text nodes
1070                    // becomes the content of the new node.
1071                    let emph = tree.new_node(node_type);
1072                    let mut tmp = tree.get(opener_inl).next;
1073                    while let Some(t) = tmp {
1074                        if t == closer_inl {
1075                            break;
1076                        }
1077                        let nxt = tree.get(t).next;
1078                        tree.unlink(t);
1079                        tree.append_child(emph, t);
1080                        tmp = nxt;
1081                    }
1082                    tree.insert_after(opener_inl, emph);
1083                    self.nesting.insert(emph, height + 1);
1084
1085                    // Delimiters between the pair can never match anything
1086                    // now.
1087                    if self.delims[o].next != Some(c) {
1088                        self.delims[o].next = Some(c);
1089                        self.delims[c].previous = Some(o);
1090                    }
1091
1092                    if self.delims[o].numdelims == 0 {
1093                        tree.unlink(opener_inl);
1094                        self.remove_delimiter(o);
1095                    }
1096                    if self.delims[c].numdelims == 0 {
1097                        tree.unlink(closer_inl);
1098                        let tempstack = self.delims[c].next;
1099                        self.remove_delimiter(c);
1100                        closer = tempstack;
1101                    }
1102                }
1103                _ => {
1104                    closer = self.delims[c].next;
1105                    openers_bottom.insert(key, self.delims[old_closer].previous);
1106                    if !self.delims[old_closer].can_open {
1107                        // It found no opener and cannot be one: it is inert.
1108                        self.remove_delimiter(old_closer);
1109                    }
1110                }
1111            }
1112        }
1113
1114        // Drop everything above the floor.
1115        while let Some(top) = self.delim_top {
1116            if Some(top) == stack_bottom {
1117                break;
1118            }
1119            self.remove_delimiter(top);
1120        }
1121    }
1122
1123    // --- section 6.3 links and images ---
1124
1125    /// The link title without its delimiters, unescaped; `None` when there
1126    /// is no title here.
1127    pub fn parse_link_title(&mut self) -> Option<String> {
1128        let (title, end) = scan_link_title(&self.subject, self.pos)?;
1129        self.pos = end;
1130        Some(title)
1131    }
1132
1133    /// A destination that is backslash-unescaped and entity-decoded, but
1134    /// **not** percent-encoded; see `scan_link_destination`.
1135    pub fn parse_link_destination(&mut self) -> Option<String> {
1136        let (dest, end) = scan_link_destination(&self.subject, self.pos)?;
1137        self.pos = end;
1138        Some(dest)
1139    }
1140
1141    /// The byte length of the link label at `pos`, brackets included,
1142    /// advancing past it; 0 if there is no label here or it is over the
1143    /// section 4.7 999-character limit.
1144    pub fn parse_link_label(&mut self) -> usize {
1145        let Some((raw_len, length)) = scan_link_label(&self.subject, self.pos) else {
1146            return 0;
1147        };
1148        // The raw match is consumed even when it is too long to be a valid
1149        // label; callers that need the position back reset it themselves.
1150        self.pos += raw_len;
1151        length
1152    }
1153
1154    fn add_bracket(&mut self, node: NodeId, index: usize, image: bool) {
1155        if let Some(top) = self.brackets.last_mut() {
1156            top.bracket_after = true;
1157        }
1158        self.brackets.push(Bracket {
1159            node,
1160            previous_delimiter: self.delim_top,
1161            index,
1162            image,
1163            active: true,
1164            bracket_after: false,
1165        });
1166    }
1167
1168    fn remove_bracket(&mut self) {
1169        self.brackets.pop();
1170    }
1171
1172    pub fn parse_open_bracket(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1173        let startpos = self.pos;
1174        self.pos += 1;
1175        let node = text_node(tree, "[");
1176        tree.append_child(block, node);
1177        self.add_bracket(node, startpos, false);
1178        true
1179    }
1180
1181    /// `!` only matters when it introduces an image.
1182    pub fn parse_bang(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1183        let startpos = self.pos;
1184        self.pos += 1;
1185        if self.peek() == Some(b'[') {
1186            self.pos += 1;
1187            let node = text_node(tree, "![");
1188            tree.append_child(block, node);
1189            self.add_bracket(node, startpos + 1, true);
1190        } else {
1191            let node = text_node(tree, "!");
1192            tree.append_child(block, node);
1193        }
1194        true
1195    }
1196
1197    /// The spec's "look for link or image" procedure. On a `]`, walk back
1198    /// to the newest bracket opener and try, in order: an inline
1199    /// `(dest "title")`, a full `[label]`, a collapsed `[]` or a shortcut
1200    /// reference. Anything that fails backtracks to just after the `]` and
1201    /// leaves a literal `]`.
1202    pub fn parse_close_bracket(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1203        self.pos += 1;
1204        let startpos = self.pos;
1205
1206        let Some(opener) = self.brackets.last().cloned() else {
1207            let node = text_node(tree, "]");
1208            tree.append_child(block, node);
1209            return true;
1210        };
1211        if !opener.active {
1212            // Deactivated by an enclosing link: not an opener any more.
1213            let node = text_node(tree, "]");
1214            tree.append_child(block, node);
1215            self.remove_bracket();
1216            return true;
1217        }
1218
1219        let is_image = opener.image;
1220        let mut dest = String::new();
1221        let mut title: Option<String> = None;
1222        let mut matched = false;
1223
1224        let savepos = self.pos;
1225
1226        // Inline link: `](` destination title `)`.
1227        if let Some(tail) = scan_inline_link_tail(&self.subject, self.pos) {
1228            self.pos = tail.end;
1229            dest = tail.dest;
1230            title = tail.title;
1231            matched = true;
1232        }
1233
1234        if !matched {
1235            // Reference forms. A second label gives the full form; an empty
1236            // or absent one means the link text is itself the label
1237            // (collapsed and shortcut), which is only possible if that text
1238            // holds no bracket.
1239            let mut reflabel: Option<String> = None;
1240            let beforelabel = self.pos;
1241            let n = self.parse_link_label();
1242            if n > 2 {
1243                reflabel = Some(self.subject[beforelabel + 1..beforelabel + n - 1].to_string());
1244            } else if !opener.bracket_after {
1245                let (lo, hi) = (opener.index + 1, startpos - 1);
1246                if lo <= hi && hi <= self.subject.len() {
1247                    reflabel = Some(self.subject[lo..hi].to_string());
1248                }
1249            }
1250            if n == 0 {
1251                self.pos = savepos;
1252            }
1253
1254            if let Some(label) = reflabel {
1255                if let Some(link) = self.refmap.get(&normalize_reference(&label)) {
1256                    dest = link.destination.clone();
1257                    title = link.title.clone();
1258                    matched = true;
1259                }
1260            }
1261        }
1262
1263        if !matched {
1264            self.remove_bracket();
1265            self.pos = startpos;
1266            let node = text_node(tree, "]");
1267            tree.append_child(block, node);
1268            return true;
1269        }
1270
1271        let mut node = MdNode::new(if is_image {
1272            NodeType::Image
1273        } else {
1274            NodeType::Link
1275        });
1276        node.destination = dest;
1277        // An empty title is the same as no title at all: `[a](/url "")`
1278        // renders a bare `<a href="/url">`.
1279        node.title = title.filter(|t| !t.is_empty());
1280        let node = tree.add(node);
1281
1282        let mut tmp = tree.get(opener.node).next;
1283        while let Some(t) = tmp {
1284            let nxt = tree.get(t).next;
1285            tree.unlink(t);
1286            tree.append_child(node, t);
1287            tmp = nxt;
1288        }
1289        tree.append_child(block, node);
1290
1291        // Emphasis inside the link text resolves now, and only down to the
1292        // delimiter that was current when the `[` opened.
1293        self.process_emphasis(tree, opener.previous_delimiter);
1294
1295        // The nesting limit, judged once the content's own nesting is
1296        // settled: a link or image whose text already holds
1297        // `MAX_INLINE_NESTING` nested containers stays literal. Its
1298        // children go back where they were, the `[` stays the text it
1299        // still is, and the `]` becomes text, as for any other failed
1300        // match; the tail after `]` is rescanned as text too.
1301        let height = self.run_height(tree, tree.get(node).first_child, None);
1302        if height >= MAX_INLINE_NESTING {
1303            tree.unlink(node);
1304            let mut child = tree.get(node).first_child;
1305            while let Some(c) = child {
1306                let nxt = tree.get(c).next;
1307                tree.unlink(c);
1308                tree.append_child(block, c);
1309                child = nxt;
1310            }
1311            self.remove_bracket();
1312            self.pos = startpos;
1313            let text = text_node(tree, "]");
1314            tree.append_child(block, text);
1315            return true;
1316        }
1317        self.nesting.insert(node, height + 1);
1318
1319        self.remove_bracket();
1320        tree.unlink(opener.node);
1321
1322        // Links may not contain links (section 6.3): every earlier link
1323        // opener is spent. Image openers survive, since images may nest in
1324        // links.
1325        if !is_image {
1326            for b in self.brackets.iter_mut() {
1327                if !b.image {
1328                    b.active = false;
1329                }
1330            }
1331        }
1332
1333        true
1334    }
1335
1336    // --- section 6.2 entities, sections 6.8 and 6.9 breaks and plain text ---
1337
1338    pub fn parse_entity(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1339        let Some((literal, end)) = scan_entity(&self.subject, self.pos) else {
1340            return false;
1341        };
1342        self.pos = end;
1343        let node = text_node(tree, &literal);
1344        tree.append_child(block, node);
1345        true
1346    }
1347
1348    /// A chunk of ordinary text: everything up to the next character that
1349    /// could start an inline construct. A byte scan is exact, because the
1350    /// terminators are all ASCII.
1351    pub fn parse_string(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1352        let bytes = self.subject.as_bytes();
1353        let startpos = self.pos;
1354        let gfm = self.options.gfm;
1355        while self.pos < bytes.len() && !is_inline_special_byte(bytes[self.pos], gfm) {
1356            self.pos += 1;
1357        }
1358        if self.pos == startpos {
1359            return false;
1360        }
1361        let node = text_node(tree, &self.subject[startpos..self.pos]);
1362        tree.append_child(block, node);
1363        true
1364    }
1365
1366    /// Sections 6.7 and 6.8: two or more spaces before the line ending make
1367    /// a hard break, anything else a soft one. Trailing spaces are dropped
1368    /// either way, as is the indentation of the next line.
1369    pub fn parse_newline(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1370        self.pos += 1;
1371        let lastc = tree.get(block).last_child;
1372        let prev_text = lastc.and_then(|id| {
1373            let node = tree.get(id);
1374            (node.node_type == NodeType::Text).then_some(node.literal.as_str())
1375        });
1376        let (hard, trim) = classify_break(prev_text);
1377        if trim {
1378            if let Some(id) = lastc {
1379                let literal = &mut tree.get_mut(id).literal;
1380                let trimmed = literal.trim_end_matches(' ').len();
1381                literal.truncate(trimmed);
1382            }
1383            let brk = tree.new_node(if hard {
1384                NodeType::Linebreak
1385            } else {
1386                NodeType::Softbreak
1387            });
1388            tree.append_child(block, brk);
1389        } else {
1390            let brk = tree.new_node(NodeType::Softbreak);
1391            tree.append_child(block, brk);
1392        }
1393        self.skip_spaces();
1394        true
1395    }
1396
1397    /// One inline construct at `pos`; false only at the end of the subject.
1398    pub fn parse_inline(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1399        let Some(c) = self.peek() else {
1400            return false;
1401        };
1402
1403        let res = match c {
1404            b'\n' => self.parse_newline(tree, block),
1405            b'\\' => self.parse_backslash(tree, block),
1406            b'`' => self.parse_backticks(tree, block),
1407            b'*' | b'_' => self.handle_delim(c, tree, block),
1408            // Only GFM gives `~` a meaning; otherwise it is ordinary text
1409            // (and the non-GFM text scan swallows whole runs of it).
1410            b'~' => {
1411                if self.options.gfm {
1412                    self.handle_delim(c, tree, block)
1413                } else {
1414                    self.parse_string(tree, block)
1415                }
1416            }
1417            b'[' => self.parse_open_bracket(tree, block),
1418            b'!' => self.parse_bang(tree, block),
1419            b']' => self.parse_close_bracket(tree, block),
1420            b'<' => self.parse_autolink(tree, block) || self.parse_html_tag(tree, block),
1421            b'&' => self.parse_entity(tree, block),
1422            _ => self.parse_string(tree, block),
1423        };
1424
1425        if !res {
1426            self.parse_literal_char(tree, block);
1427        }
1428
1429        true
1430    }
1431
1432    /// A character nothing claimed: consume it as literal text. Only `<`
1433    /// and `&` reach here from the dispatch, so the byte at `pos` is a
1434    /// whole character; the engine driver's literal fallback may reach it
1435    /// with any character, so the whole character is taken either way.
1436    pub fn parse_literal_char(&mut self, tree: &mut Tree, block: NodeId) -> bool {
1437        if self.pos >= self.subject.len() {
1438            return false;
1439        }
1440        let startpos = self.pos;
1441        self.pos += code_point_at(&self.subject, self.pos).len_utf8();
1442        let node = text_node(tree, &self.subject[startpos..self.pos]);
1443        tree.append_child(block, node);
1444        true
1445    }
1446
1447    /// Reset for one block's raw content; false when the trimmed subject
1448    /// is empty. Trimming is what stops trailing spaces at the end of a
1449    /// block from making a hard break, and drops the leading indentation
1450    /// of the first line. The trim must remove exactly what
1451    /// `String.prototype.trim` removes, which is `js_trim`.
1452    pub fn begin_block(&mut self, tree: &Tree, block: NodeId) -> bool {
1453        self.subject = js_trim(&tree.get(block).string_content).to_string();
1454        self.pos = 0;
1455        self.delims.clear();
1456        self.delim_top = None;
1457        self.brackets.clear();
1458        self.nesting.clear();
1459        self.backticks = BacktickMemo::default();
1460        !self.subject.is_empty()
1461    }
1462
1463    /// The tail of a block's inline parse: clear the raw content, resolve
1464    /// emphasis over the whole delimiter stack.
1465    pub fn finish_block(&mut self, tree: &mut Tree, block: NodeId) {
1466        tree.get_mut(block).string_content.clear();
1467        self.process_emphasis(tree, None);
1468    }
1469
1470    /// Parse one paragraph's or heading's raw content into inline children.
1471    pub fn parse(&mut self, tree: &mut Tree, block: NodeId) {
1472        self.begin_block(tree, block);
1473        while self.parse_inline(tree, block) {}
1474        self.finish_block(tree, block);
1475    }
1476
1477    /// Section 4.7: consume one link reference definition at the start
1478    /// of `s`, adding it to `refmap`. Returns the number of BYTES consumed.
1479    /// The block phase goes through [`parse_references`], which takes
1480    /// every leading definition of a paragraph over one copy of it.
1481    pub fn parse_reference(&mut self, s: &str, refmap: &mut RefMap) -> usize {
1482        self.subject = s.to_string();
1483        self.pos = 0;
1484        self.parse_reference_here(refmap)
1485    }
1486
1487    /// [`parse_reference`] at the current position of the current
1488    /// subject: on success the position is past the definition, on
1489    /// failure it is back where it was and the result is 0.
1490    fn parse_reference_here(&mut self, refmap: &mut RefMap) -> usize {
1491        let startpos = self.pos;
1492
1493        // Section 4.7 allows up to three spaces of indentation before the
1494        // label. The block phase normally strips a paragraph line's
1495        // indentation before it gets here, so this usually consumes
1496        // nothing.
1497        self.skip_indent();
1498
1499        let label_start = self.pos;
1500        let match_chars = self.parse_link_label();
1501        if match_chars == 0 {
1502            return 0;
1503        }
1504        let rawlabel = self.subject[label_start + 1..label_start + match_chars - 1].to_string();
1505
1506        if self.peek() == Some(b':') {
1507            self.pos += 1;
1508        } else {
1509            self.pos = startpos;
1510            return 0;
1511        }
1512
1513        self.spnl();
1514
1515        let Some(dest) = self.parse_link_destination() else {
1516            self.pos = startpos;
1517            return 0;
1518        };
1519
1520        let beforetitle = self.pos;
1521        self.spnl();
1522        let mut title = None;
1523        if self.pos != beforetitle {
1524            title = self.parse_link_title();
1525        }
1526        if title.is_none() {
1527            self.pos = beforetitle;
1528        }
1529
1530        // Nothing but spaces may follow on the definition's last line.
1531        let mut at_line_end = true;
1532        if !self.space_at_end_of_line() {
1533            if title.is_none() {
1534                at_line_end = false;
1535            } else {
1536                // What looked like a title is something else; the definition
1537                // may still be valid without it.
1538                title = None;
1539                self.pos = beforetitle;
1540                at_line_end = self.space_at_end_of_line();
1541            }
1542        }
1543        if !at_line_end {
1544            self.pos = startpos;
1545            return 0;
1546        }
1547
1548        let normlabel = normalize_reference(&rawlabel);
1549        if normlabel.is_empty() {
1550            // A label must hold at least one non-whitespace character.
1551            self.pos = startpos;
1552            return 0;
1553        }
1554
1555        // First definition wins.
1556        refmap.entry(normlabel).or_insert(RefDef {
1557            destination: dest,
1558            title,
1559        });
1560
1561        self.pos - startpos
1562    }
1563}
1564
1565/// Autolink text is literal: no backslash escapes, no entity references.
1566/// The destination is not percent-encoded here; see
1567/// `scan_link_destination`.
1568fn make_autolink(tree: &mut Tree, destination: &str, label: &str) -> NodeId {
1569    let mut node = MdNode::new(NodeType::Link);
1570    node.destination = destination.to_string();
1571    node.title = None;
1572    let id = tree.add(node);
1573    let text = text_node(tree, label);
1574    tree.append_child(id, text);
1575    id
1576}
1577
1578// --- GFM extended autolinks (autolink literals) -----------------------------
1579//
1580// GFM recognises `www.x.com`, `https://x.com` and `a@x.com` without the
1581// `<...>` CommonMark requires. This runs as a post-pass over the finished
1582// inline tree rather than as another branch of the scan above, which is
1583// how cmark-gfm does it and is the only shape that keeps 652/652 safe: the
1584// scanner that decides code spans, raw HTML, emphasis and links is not
1585// touched at all, and an autolink can therefore never win against a
1586// construct CommonMark says comes first.
1587//
1588// The pass rewrites text nodes into text / link / text runs. It does not
1589// descend into link (links may not contain links) or image (its children
1590// are the alt text), and code / html_inline are leaves it never looks
1591// inside.
1592//
1593// Everything here scans by BYTE, like the rest of this file. Every
1594// character the pass branches on is ASCII, and no byte of a multi-byte
1595// UTF-8 sequence can collide with one, so a non-ASCII character is exactly
1596// as unmatchable here as its UTF-16 code unit is in the TypeScript: it ends
1597// a domain run, it is not a valid autolink start, and it is not trailing
1598// punctuation. Slices therefore never cut a character in half: every
1599// boundary this pass produces sits at an ASCII character.
1600
1601/// RFC 1035's limit on a fully-qualified domain name. See
1602/// `scan_domain_end`.
1603const MAX_AUTOLINK_DOMAIN: usize = 253;
1604
1605/// RFC 5321's limit on the local part of an address, before the `@`.
1606const MAX_EMAIL_LOCAL: usize = 64;
1607
1608/// The three schemes the extension recognises without angle brackets.
1609const AUTOLINK_SCHEMES: [&str; 3] = ["https://", "http://", "ftp://"];
1610
1611fn is_ascii_alnum(c: u8) -> bool {
1612    c.is_ascii_alphanumeric()
1613}
1614
1615fn is_autolink_space(c: u8) -> bool {
1616    matches!(c, b' ' | b'\t' | b'\n' | b'\x0B' | b'\x0C' | b'\r')
1617}
1618
1619/// A domain segment holds alphanumerics, `_` and `-`; `.` separates them.
1620fn is_domain_char(c: u8) -> bool {
1621    is_ascii_alnum(c) || c == b'_' || c == b'-' || c == b'.'
1622}
1623
1624/// Before the `@`: alphanumerics and `.`, `-`, `_`, `+`.
1625fn is_email_local_char(c: u8) -> bool {
1626    is_ascii_alnum(c) || c == b'.' || c == b'-' || c == b'_' || c == b'+'
1627}
1628
1629/// "All such recognized autolinks can only come at the beginning of a line,
1630/// after whitespace, or any of the delimiting characters `*`, `_`, `~`,
1631/// `(`."
1632///
1633/// Offset 0 has no preceding character in `s` at all, so the caller
1634/// answers for it through `at_start`; see `starts_after_delimiter`.
1635fn is_autolink_start(s: &[u8], i: usize, at_start: bool) -> bool {
1636    if i == 0 {
1637        return at_start;
1638    }
1639    let c = s[i - 1];
1640    is_autolink_space(c) || c == b'*' || c == b'_' || c == b'~' || c == b'('
1641}
1642
1643/// Whether offset 0 of a text node may begin an autolink, given the sibling
1644/// in front of it.
1645///
1646/// The rule above is about the source character immediately before the
1647/// match, and by the time this pass runs the tree no longer carries source
1648/// offsets, but the previous sibling's *type* names that character
1649/// exactly:
1650///
1651/// - `emph` and `strong` end on the `*` or `_` that closed them, and `del`
1652///   on its second `~`. All three are delimiters the rule allows, so
1653///   `*a*www.b.com` links.
1654/// - `code` ends on a backtick, `link` and `image` on `)`, `]` or `>`, and
1655///   `html_inline` on `>`. None are delimiters, so `` `x`www.a.com ``,
1656///   `[l](/u)www.a.com` and `<b>www.a.com` do not link.
1657/// - a `softbreak` or `linebreak` puts offset 0 at the beginning of a line,
1658///   and so does having no previous sibling: that is the first inline of
1659///   the block, or of the emphasis span this pass descended into.
1660///
1661/// A `text` node never appears here: `linkify_children` merges every run
1662/// of adjacent text siblings before handing the first of them over.
1663fn starts_after_delimiter(tree: &Tree, prev: Option<NodeId>) -> bool {
1664    match prev {
1665        None => true,
1666        Some(id) => matches!(
1667            tree.get(id).node_type,
1668            NodeType::Softbreak
1669                | NodeType::Linebreak
1670                | NodeType::Emph
1671                | NodeType::Strong
1672                | NodeType::Del
1673        ),
1674    }
1675}
1676
1677/// ASCII case-insensitive comparison against an already-lowercase literal.
1678fn matches_ignore_case(s: &[u8], at: usize, lower: &str) -> bool {
1679    let lower = lower.as_bytes();
1680    if at + lower.len() > s.len() {
1681        return false;
1682    }
1683    lower
1684        .iter()
1685        .enumerate()
1686        .all(|(k, &l)| s[at + k].to_ascii_lowercase() == l)
1687}
1688
1689/// The end of the run of domain characters at `from`, capped at
1690/// `MAX_AUTOLINK_DOMAIN`.
1691///
1692/// The cap is what keeps this pass linear. `_` both continues a domain and
1693/// introduces a valid autolink start, so without a bound an input like
1694/// `"_www.a_b.c".repeat(n)` gives every underscore a candidate whose domain
1695/// run reaches the end of the text: quadratic. Anything past the cap is
1696/// still scanned, just as the path rather than as the domain, and no real
1697/// domain comes near it.
1698fn scan_domain_end(s: &[u8], from: usize) -> usize {
1699    let max = s.len().min(from + MAX_AUTOLINK_DOMAIN);
1700    let mut i = from;
1701    while i < max && is_domain_char(s[i]) {
1702        i += 1;
1703    }
1704    i
1705}
1706
1707/// A valid domain: at least one period, and no underscore in either of the
1708/// last two segments. `from..to` must already be a run of domain
1709/// characters.
1710fn is_valid_domain(s: &[u8], from: usize, to: usize) -> bool {
1711    if to <= from {
1712        return false;
1713    }
1714    let mut periods = 0;
1715    let mut underscores_in_last = 0;
1716    let mut underscores_in_prev = 0;
1717    for &c in &s[from..to] {
1718        if c == b'_' {
1719            underscores_in_last += 1;
1720        } else if c == b'.' {
1721            underscores_in_prev = underscores_in_last;
1722            underscores_in_last = 0;
1723            periods += 1;
1724        }
1725    }
1726    periods > 0 && underscores_in_last == 0 && underscores_in_prev == 0
1727}
1728
1729/// "Extended autolink path validation": pull the end of the match back off
1730/// trailing characters that read as sentence punctuation rather than as
1731/// part of a URL. One loop rather than three passes, because dropping a
1732/// `)` can expose a `.` and vice versa.
1733///
1734/// - `?` `!` `.` `,` `:` `*` `_` `~` are dropped wherever they trail;
1735/// - a trailing `)` is dropped only while the match holds more `)` than
1736///   `(`, so `(www.a.com/x_(y))` keeps its inner pair and loses the outer
1737///   one;
1738/// - a trailing `;` preceded by something shaped like an entity reference
1739///   takes the whole `&...;` with it.
1740///
1741/// The parenthesis counts are taken once and then maintained, not
1742/// recomputed per drop: a deeply parenthesised URL is otherwise quadratic
1743/// in its own length.
1744fn trim_autolink_end(s: &[u8], start: usize, mut end: usize) -> usize {
1745    let mut opening: Option<usize> = None;
1746    let mut closing = 0usize;
1747
1748    while start < end {
1749        let c = s[end - 1];
1750
1751        match c {
1752            b'?' | b'!' | b'.' | b',' | b':' | b'*' | b'_' | b'~' => {
1753                end -= 1;
1754                continue;
1755            }
1756
1757            b')' => {
1758                if opening.is_none() {
1759                    let mut o = 0;
1760                    closing = 0;
1761                    for &d in &s[start..end] {
1762                        if d == b'(' {
1763                            o += 1;
1764                        } else if d == b')' {
1765                            closing += 1;
1766                        }
1767                    }
1768                    opening = Some(o);
1769                }
1770                if closing <= opening.unwrap_or(0) {
1771                    return end;
1772                }
1773                closing -= 1;
1774                end -= 1;
1775                continue;
1776            }
1777
1778            b';' => {
1779                // `&` followed by one or more alphanumerics, then this `;`.
1780                let mut j = end as isize - 2;
1781                while j > start as isize && is_ascii_alnum(s[j as usize]) {
1782                    j -= 1;
1783                }
1784                if j < end as isize - 2 && j >= 0 && s[j as usize] == b'&' {
1785                    end = j as usize;
1786                    continue;
1787                }
1788                return end;
1789            }
1790
1791            _ => return end,
1792        }
1793    }
1794
1795    end
1796}
1797
1798/// One recognised autolink literal: `s[start..end]` linking to `href`.
1799struct AutolinkMatch {
1800    start: usize,
1801    end: usize,
1802    href: String,
1803}
1804
1805/// `www.`, `http://`, `https://` and `ftp://` all start with one of these.
1806fn could_start_url(c: u8) -> bool {
1807    matches!(c, b'w' | b'W' | b'h' | b'H' | b'f' | b'F')
1808}
1809
1810fn has_period(s: &[u8], from: usize, to: usize) -> bool {
1811    s[from..to].contains(&b'.')
1812}
1813
1814/// Every autolink literal in one text run, left to right and
1815/// non-overlapping. Returns an empty vector when there is nothing to do,
1816/// which is the overwhelmingly common case.
1817fn scan_autolinks(text: &str, at_start: bool) -> Vec<AutolinkMatch> {
1818    let s = text.as_bytes();
1819    let length = s.len();
1820    let mut out = Vec::new();
1821
1822    // The maximal run of non-space, non-`<` characters containing the
1823    // current position: "zero or more non-space non-`<` characters may
1824    // follow" the domain. Cached because candidates are tried left to
1825    // right, so each run is scanned once however many candidates start
1826    // inside it.
1827    let mut run_start = usize::MAX;
1828    let mut run_end = 0usize;
1829
1830    let mut i = 0;
1831    let mut last_end = 0;
1832
1833    while i < length {
1834        let c = s[i];
1835
1836        // --- email: found by its `@`, then rewound to the start of the
1837        // local part
1838        if c == b'@' {
1839            // The rewind is bounded to keep this pass linear, and RFC 5321
1840            // bounds a local part in the same place anyway, so the cap
1841            // costs no real address.
1842            let capped = i as isize - MAX_EMAIL_LOCAL as isize;
1843            let floor = (last_end as isize).max(capped);
1844            let mut k = i as isize;
1845            while k > floor && is_email_local_char(s[k as usize - 1]) {
1846                k -= 1;
1847            }
1848
1849            // Stopping *on* the cap is not the same as finding a boundary.
1850            // If the character just outside it still belongs to the local
1851            // part, the local part is longer than the cap allows and there
1852            // is no address here at all: accepting the match would link the
1853            // 64-character tail of a longer run and leave the rest as text,
1854            // inventing an address the source never wrote. `k` can only
1855            // reach `capped` when the cap, rather than `last_end`, is what
1856            // ended the loop; and `k` of 0 is the start of the string,
1857            // where there is no character outside the cap to disqualify
1858            // anything.
1859            if k == capped && k > 0 && is_email_local_char(s[k as usize - 1]) {
1860                i += 1;
1861                continue;
1862            }
1863
1864            let k = k as usize;
1865            if k < i && is_autolink_start(s, k, at_start) {
1866                // After the `@`: alphanumerics, `.`, `-`, `_`; at least one
1867                // period; a trailing `.` is not part of the address, and a
1868                // trailing `-` or `_` invalidates the whole thing.
1869                let mut end = i + 1;
1870                while end < length && is_domain_char(s[end]) {
1871                    end += 1;
1872                }
1873                while end > i + 1 && s[end - 1] == b'.' {
1874                    end -= 1;
1875                }
1876
1877                let last = if end > i + 1 { s[end - 1] } else { 0 };
1878                if end > i + 1 && last != b'-' && last != b'_' && has_period(s, i + 1, end) {
1879                    out.push(AutolinkMatch {
1880                        start: k,
1881                        end,
1882                        href: format!("mailto:{}", &text[k..end]),
1883                    });
1884                    last_end = end;
1885                    i = end;
1886                    continue;
1887                }
1888            }
1889            i += 1;
1890            continue;
1891        }
1892
1893        // --- www / scheme: both need a valid start and a valid domain
1894        if !could_start_url(c) || !is_autolink_start(s, i, at_start) {
1895            i += 1;
1896            continue;
1897        }
1898
1899        let mut domain_start: Option<usize> = None;
1900        let mut prefix = "";
1901        if matches_ignore_case(s, i, "www.") {
1902            // The domain of a `www.` autolink includes the `www.` itself, so
1903            // the required period is already there and `www.foo_bar.com` is
1904            // rejected on the same footing as `http://foo_bar.com`.
1905            domain_start = Some(i);
1906            prefix = "http://";
1907        } else {
1908            for scheme in AUTOLINK_SCHEMES {
1909                if matches_ignore_case(s, i, scheme) {
1910                    domain_start = Some(i + scheme.len());
1911                    break;
1912                }
1913            }
1914        }
1915        let Some(domain_start) = domain_start else {
1916            i += 1;
1917            continue;
1918        };
1919
1920        let domain_end = scan_domain_end(s, domain_start);
1921        // Checked before the run scan below, so a candidate that cannot
1922        // possibly match costs only its own domain run.
1923        if !is_valid_domain(s, domain_start, domain_end) {
1924            i += 1;
1925            continue;
1926        }
1927
1928        if i >= run_end || i < run_start {
1929            run_start = i;
1930            run_end = i;
1931            while run_end < length {
1932                let d = s[run_end];
1933                if is_autolink_space(d) || d == b'<' {
1934                    break;
1935                }
1936                run_end += 1;
1937            }
1938        }
1939
1940        let end = trim_autolink_end(s, i, run_end);
1941        // Trailing punctuation can eat back into the domain
1942        // (`www.commonmark.org.` loses its last period), so the domain is
1943        // validated again over what actually survived.
1944        let survived = domain_end.min(end);
1945        if end <= domain_start || !is_valid_domain(s, domain_start, survived) {
1946            i += 1;
1947            continue;
1948        }
1949
1950        out.push(AutolinkMatch {
1951            start: i,
1952            end,
1953            href: format!("{prefix}{}", &text[i..end]),
1954        });
1955        last_end = end;
1956        i = end;
1957    }
1958
1959    out
1960}
1961
1962/// Replace one text node with the text / link / text run its literal
1963/// implies.
1964fn linkify_text_node(tree: &mut Tree, node: NodeId) {
1965    let at_start = starts_after_delimiter(tree, tree.get(node).prev);
1966    let s = tree.get(node).literal.clone();
1967    let matches = scan_autolinks(&s, at_start);
1968    if matches.is_empty() {
1969        return;
1970    }
1971
1972    let mut at = 0;
1973    for m in matches {
1974        if at < m.start {
1975            let text = text_node(tree, &s[at..m.start]);
1976            tree.insert_before(node, text);
1977        }
1978        // Not percent-encoded here, for the same reason as
1979        // `scan_link_destination`: encoding belongs to the renderer, and
1980        // the AST promises the decoded form.
1981        let link = make_autolink(tree, &m.href, &s[m.start..m.end]);
1982        tree.insert_before(node, link);
1983        at = m.end;
1984    }
1985    if at < s.len() {
1986        let text = text_node(tree, &s[at..]);
1987        tree.insert_before(node, text);
1988    }
1989
1990    tree.unlink(node);
1991}
1992
1993/// Autolink the text children of one container, and add the child
1994/// containers still to visit to `pending`.
1995fn linkify_children(tree: &mut Tree, parent: NodeId, pending: &mut Vec<NodeId>) {
1996    let mut child = tree.get(parent).first_child;
1997
1998    while let Some(c) = child {
1999        if tree.get(c).node_type == NodeType::Text {
2000            // Consolidate the run of adjacent text nodes first. The scan
2001            // above emits a node per delimiter run and per character it
2002            // could not claim, so `a.b-c_d@a.b` arrives as three siblings
2003            // and the address is only visible once they are one string.
2004            // Merging changes nothing downstream: the renderer writes text
2005            // literals back to back, and the AST projection already
2006            // coalesces adjacent runs.
2007            let mut sibling = tree.get(c).next;
2008            if sibling.is_some_and(|s| tree.get(s).node_type == NodeType::Text) {
2009                let mut merged = tree.get(c).literal.clone();
2010                while let Some(s) = sibling {
2011                    if tree.get(s).node_type != NodeType::Text {
2012                        break;
2013                    }
2014                    merged.push_str(&tree.get(s).literal);
2015                    let next = tree.get(s).next;
2016                    tree.unlink(s);
2017                    sibling = next;
2018                }
2019                tree.get_mut(c).literal = merged;
2020            }
2021
2022            let after = tree.get(c).next;
2023            linkify_text_node(tree, c);
2024            child = after;
2025            continue;
2026        }
2027
2028        // No links inside links (section 6.3), and an image's children are
2029        // its alt text.
2030        let node = tree.get(c);
2031        if node.node_type != NodeType::Link
2032            && node.node_type != NodeType::Image
2033            && node.is_container()
2034        {
2035            pending.push(c);
2036        }
2037        child = node.next;
2038    }
2039}
2040
2041/// Recognise GFM autolink literals throughout one finished block's inlines.
2042///
2043/// Iterative rather than recursive: emphasis nests as deeply as the input
2044/// says.
2045pub fn linkify_autolinks(tree: &mut Tree, block: NodeId) {
2046    let mut pending = vec![block];
2047    while let Some(node) = pending.pop() {
2048        linkify_children(tree, node, &mut pending);
2049    }
2050}
2051
2052/// Blocks whose raw content the block phase left for this phase to parse.
2053/// GFM table cells hold inlines and nothing else ("block-level elements
2054/// cannot be inserted in a table"), so a cell is parsed exactly as a
2055/// paragraph is, autolink post-pass included.
2056pub fn is_inline_content_block(t: NodeType) -> bool {
2057    matches!(
2058        t,
2059        NodeType::Paragraph | NodeType::Heading | NodeType::TableCell
2060    )
2061}
2062
2063/// The inline content blocks of `tree`, in the order the walk exits them:
2064/// the one iteration both inline drivers share (the hand scanner and the
2065/// engine path), so which blocks get inline parsing is decided exactly
2066/// once. Inline parsing only adds children beneath these blocks, so the
2067/// list taken before the phase runs is the walk the phase would make.
2068pub fn inline_content_blocks(tree: &Tree) -> Vec<NodeId> {
2069    let mut out = Vec::new();
2070    let mut walker = tree.walker(tree.root());
2071    while let Some(event) = walker.next(tree) {
2072        if !event.entering && is_inline_content_block(tree.get(event.node).node_type) {
2073            out.push(event.node);
2074        }
2075    }
2076    out
2077}
2078
2079/// Walk the finished block tree, handing every inline content block
2080/// (paragraphs, headings, table cells) to `f` and running the GFM
2081/// autolink-literal post-pass after it, so when linkify runs is decided
2082/// exactly once for both drivers.
2083pub fn for_each_inline_block(
2084    tree: &mut Tree,
2085    options: &Options,
2086    mut f: impl FnMut(&mut Tree, NodeId),
2087) {
2088    for block in inline_content_blocks(tree) {
2089        f(tree, block);
2090        if options.gfm {
2091            linkify_autolinks(tree, block);
2092        }
2093    }
2094}
2095
2096/// Phase 2 entry point: walk the block tree and parse the string content of
2097/// every paragraph, heading and table cell into inline children.
2098pub fn parse_inlines(tree: &mut Tree, refmap: RefMap, options: Options) {
2099    let mut parser = InlineParser::new(refmap, options);
2100    for_each_inline_block(tree, &options, |tree, block| parser.parse(tree, block));
2101}
2102
2103/// Consume link reference definitions from the front of a paragraph's raw
2104/// content, adding them to `refmap`. Returns the number of BYTES consumed,
2105/// or 0 if `s` does not start with a definition.
2106///
2107/// Reference definitions are parsed during the block phase, before any
2108/// inline parser for the document exists, so a scratch parser is built per
2109/// call; nothing here depends on the parse options.
2110pub fn parse_reference(s: &str, refmap: &mut RefMap) -> usize {
2111    let mut parser = InlineParser::new(RefMap::new(), Options::COMMONMARK);
2112    parser.parse_reference(s, refmap)
2113}
2114
2115/// Section 4.7 over a whole paragraph: every link reference definition
2116/// at the start of `s`, in order, each added to `refmap`. Returns the
2117/// number of BYTES they take up together.
2118///
2119/// One parser over one copy of `s`, advancing through it. Copying the
2120/// remaining tail once per definition, as the per-definition entry
2121/// point does, made a paragraph of n short definitions cost O(n^2).
2122pub fn parse_references(s: &str, refmap: &mut RefMap) -> usize {
2123    let mut parser = InlineParser::new(RefMap::new(), Options::COMMONMARK);
2124    parser.subject = s.to_string();
2125    parser.pos = 0;
2126    while parser.pos < s.len() && s.as_bytes()[parser.pos] == b'[' {
2127        if parser.parse_reference_here(refmap) == 0 {
2128            break;
2129        }
2130    }
2131    parser.pos
2132}