ironmark 1.12.3

Fast Markdown to HTML parser written in Rust with WebAssembly bindings
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
use crate::ParseOptions;
use crate::ast::{Block, ListKind, TableAlignment};
use crate::html::{
    collapse_and_escape_into, encode_url_escaped_into, escape_html_into, gfm_tag_is_filtered,
};
use crate::inline::{InlineBuffers, LinkRefMap, parse_inline_pass};

#[inline(always)]
fn emit_checkbox(out: &mut String, checked: Option<bool>) {
    match checked {
        Some(true) => out.push_str("<input type=\"checkbox\" checked=\"\" disabled=\"\" /> "),
        Some(false) => out.push_str("<input type=\"checkbox\" disabled=\"\" /> "),
        None => {}
    }
}

enum Work<'a> {
    Block(&'a Block),
    TightListItem(&'a Block),
    TightBlock(&'a Block),
    CloseTag(&'static str),
}

pub(crate) fn render_block(
    block: &Block,
    refs: &LinkRefMap,
    out: &mut String,
    opts: &ParseOptions,
    bufs: &mut InlineBuffers,
) {
    if let Block::Document { children } = block
        && let [child] = children.as_slice()
    {
        render_single_child_doc(child, refs, out, opts, bufs);
        return;
    }

    let mut stack: Vec<Work<'_>> = Vec::with_capacity(32);
    stack.push(Work::Block(block));

    while let Some(work) = stack.pop() {
        match work {
            Work::CloseTag(tag) => out.push_str(tag),
            Work::TightListItem(block) => {
                render_tight_list_item(block, refs, out, opts, bufs, &mut stack);
            }
            Work::TightBlock(block) => {
                if let Block::Paragraph { raw } = block {
                    push_inline_or_plain(out, raw, refs, opts, bufs);
                } else {
                    render_one(block, refs, out, opts, bufs, &mut stack);
                }
            }
            Work::Block(block) => {
                render_one(block, refs, out, opts, bufs, &mut stack);
            }
        }
    }
}

#[inline]
fn render_single_child_doc(
    child: &Block,
    refs: &LinkRefMap,
    out: &mut String,
    opts: &ParseOptions,
    bufs: &mut InlineBuffers,
) {
    match child {
        Block::Paragraph { raw } => {
            out.push_str("<p>");
            parse_inline_pass(out, raw, refs, opts, bufs);
            out.push_str("</p>\n");
        }
        _ => {
            let mut stack = Vec::with_capacity(8);
            stack.push(Work::Block(child));
            while let Some(work) = stack.pop() {
                match work {
                    Work::CloseTag(tag) => out.push_str(tag),
                    Work::TightListItem(block) => {
                        render_tight_list_item(block, refs, out, opts, bufs, &mut stack);
                    }
                    Work::TightBlock(block) => {
                        if let Block::Paragraph { raw } = block {
                            push_inline_or_plain(out, raw, refs, opts, bufs);
                        } else {
                            render_one(block, refs, out, opts, bufs, &mut stack);
                        }
                    }
                    Work::Block(block) => render_one(block, refs, out, opts, bufs, &mut stack),
                }
            }
        }
    }
}

fn list_close_tag(kind: &ListKind) -> &'static str {
    match kind {
        ListKind::Bullet(_) => "</ul>\n",
        ListKind::Ordered(_) => "</ol>\n",
    }
}

#[inline(always)]
fn emit_list_open(out: &mut String, kind: &ListKind, start: u32) {
    match kind {
        ListKind::Bullet(_) => out.push_str("<ul>\n"),
        ListKind::Ordered(_) => {
            if start == 1 {
                out.push_str("<ol>\n");
            } else {
                use std::fmt::Write;
                out.push_str("<ol start=\"");
                let _ = write!(out, "{}", start);
                out.push_str("\">\n");
            }
        }
    }
}

#[inline]
fn render_one<'a>(
    block: &'a Block,
    refs: &LinkRefMap,
    out: &mut String,
    opts: &ParseOptions,
    bufs: &mut InlineBuffers,
    stack: &mut Vec<Work<'a>>,
) {
    match block {
        Block::Document { children } => {
            for child in children.iter().rev() {
                stack.push(Work::Block(child));
            }
        }
        Block::ThematicBreak => out.push_str("<hr />\n"),
        Block::Heading { level, raw } => {
            static TAGS: [&str; 7] = ["", "h1", "h2", "h3", "h4", "h5", "h6"];
            let l = *level as usize;
            let tag = TAGS[l];
            out.push('<');
            out.push_str(tag);
            let mut slug = std::mem::take(&mut bufs.scratch);
            let use_slug = opts.enable_heading_ids || opts.enable_heading_anchors;
            if use_slug {
                heading_slug_into(&mut slug, raw);
                if !slug.is_empty() {
                    out.push_str(" id=\"");
                    escape_html_into(out, &slug);
                    out.push('"');
                }
            }
            out.push('>');
            parse_inline_pass(out, raw, refs, opts, bufs);
            if opts.enable_heading_anchors && !slug.is_empty() {
                out.push_str(" <a class=\"anchor\" href=\"#");
                encode_url_escaped_into(out, &slug);
                out.push_str("\">¶</a>");
            }
            out.push_str("</");
            out.push_str(tag);
            out.push_str(">\n");
            bufs.scratch = slug;
        }
        Block::Paragraph { raw } => {
            out.push_str("<p>");
            parse_inline_pass(out, raw, refs, opts, bufs);
            out.push_str("</p>\n");
        }
        Block::CodeBlock { info, literal } => {
            if info.is_empty() {
                out.push_str("<pre><code>");
            } else {
                let lang = match memchr::memchr3(b' ', b'\t', b'\n', info.as_bytes()) {
                    Some(0) => "",
                    // SAFETY: `pos` is returned by memchr and is within `info`.
                    Some(pos) => unsafe { info.get_unchecked(..pos) },
                    None => info,
                };
                if lang.is_empty() {
                    out.push_str("<pre><code>");
                } else {
                    out.push_str("<pre><code class=\"language-");
                    escape_html_into(out, lang);
                    out.push_str("\">");
                }
            }
            escape_html_into(out, literal);
            out.push_str("</code></pre>\n");
        }
        Block::HtmlBlock { literal } => {
            let escape_it = opts.disable_raw_html
                || opts.no_html_blocks
                || (opts.tag_filter && gfm_tag_is_filtered(literal));
            if escape_it {
                escape_html_into(out, literal);
            } else {
                out.push_str(literal);
            }
            if !literal.ends_with('\n') {
                out.push('\n');
            }
        }
        Block::BlockQuote { children } => {
            out.push_str("<blockquote>\n");
            stack.push(Work::CloseTag("</blockquote>\n"));
            for child in children.iter().rev() {
                stack.push(Work::Block(child));
            }
        }
        Block::List {
            kind,
            start,
            tight,
            children,
        } => {
            if *tight && children.len() == 1 {
                render_nested_tight_list(
                    kind,
                    *start,
                    children,
                    InlineCtx { refs, opts },
                    out,
                    bufs,
                    stack,
                );
                return;
            }
            emit_list_open(out, kind, *start);
            stack.push(Work::CloseTag(list_close_tag(kind)));
            if *tight {
                for item in children.iter().rev() {
                    stack.push(Work::TightListItem(item));
                }
            } else {
                for item in children.iter().rev() {
                    stack.push(Work::Block(item));
                }
            }
        }
        Block::ListItem { children, checked } => {
            out.push_str("<li>");
            emit_checkbox(out, *checked);
            if !children.is_empty() {
                out.push('\n');
                stack.push(Work::CloseTag("</li>\n"));
                for child in children.iter().rev() {
                    stack.push(Work::Block(child));
                }
            } else {
                out.push_str("</li>\n");
            }
        }
        Block::Table(td) => {
            let alignments = &td.alignments;
            let header = &td.header;
            let num_cols = td.num_cols;
            let all_none = alignments.iter().all(|a| *a == TableAlignment::None);
            out.push_str("<table>\n<thead>\n<tr>\n");
            for (i, cell) in header.iter().enumerate() {
                let align = if all_none {
                    TableAlignment::None
                } else {
                    alignments.get(i).copied().unwrap_or(TableAlignment::None)
                };
                render_table_cell(out, cell.as_str(), "th", align, refs, opts, bufs);
            }
            out.push_str("</tr>\n</thead>\n");
            let num_rows = td.rows.len().checked_div(num_cols).unwrap_or(0);
            if num_rows > 0 {
                out.push_str("<tbody>\n");
                if all_none {
                    for row in td.rows.chunks_exact(num_cols) {
                        out.push_str("<tr>\n");
                        for cell in row {
                            out.push_str("<td>");
                            push_inline_or_plain(out, cell.as_str(), refs, opts, bufs);
                            out.push_str("</td>\n");
                        }
                        out.push_str("</tr>\n");
                    }
                } else {
                    for row in td.rows.chunks_exact(num_cols) {
                        out.push_str("<tr>\n");
                        for (c, cell) in row.iter().enumerate() {
                            let align = alignments.get(c).copied().unwrap_or(TableAlignment::None);
                            render_table_cell(out, cell.as_str(), "td", align, refs, opts, bufs);
                        }
                        out.push_str("</tr>\n");
                    }
                }
                out.push_str("</tbody>\n");
            }
            out.push_str("</table>\n");
        }
    }
}

/// Returns `true` if `s` needs no inline parsing or HTML escaping.
/// Uses the pre-built scan_table (same table as `parse_inline_pass`) so we
/// do a single O(n) pass instead of multiple memchr SIMD scans.
#[inline(always)]
fn is_trivially_plain(s: &str, scan_table: &[u8; 256]) -> bool {
    s.as_bytes()
        .iter()
        .all(|&b| scan_table[b as usize] == 0 && b >= b' ')
}

/// For trivially plain text, push directly; otherwise run the full inline pass.
#[inline(always)]
fn push_inline_or_plain(
    out: &mut String,
    raw: &str,
    refs: &LinkRefMap,
    opts: &ParseOptions,
    bufs: &mut InlineBuffers,
) {
    if is_trivially_plain(raw, &bufs.scan_table) {
        if opts.collapse_whitespace {
            collapse_and_escape_into(out, raw);
        } else {
            out.push_str(raw);
        }
    } else {
        parse_inline_pass(out, raw, refs, opts, bufs);
    }
}

#[derive(Copy, Clone)]
struct InlineCtx<'a> {
    refs: &'a LinkRefMap,
    opts: &'a ParseOptions,
}

#[inline(never)]
fn render_nested_tight_list<'a>(
    kind: &ListKind,
    start: u32,
    children: &'a [Block],
    inline: InlineCtx<'_>,
    out: &mut String,
    bufs: &mut InlineBuffers,
    stack: &mut Vec<Work<'a>>,
) {
    const MAX_DEPTH: usize = 64;
    let mut close_tags: [&'static str; MAX_DEPTH] = [""; MAX_DEPTH];
    let mut depth: usize = 0;

    let mut cur_kind = kind;
    let mut cur_start = start;
    let mut cur_children: &'a [Block] = children;

    loop {
        let Block::ListItem {
            children: item_children,
            checked,
        } = &cur_children[0]
        else {
            emit_list_open(out, cur_kind, cur_start);
            stack.push(Work::CloseTag(list_close_tag(cur_kind)));
            stack.push(Work::Block(&cur_children[0]));
            break;
        };

        match cur_kind {
            ListKind::Bullet(_) => out.push_str("<ul>\n<li>"),
            ListKind::Ordered(_) => {
                emit_list_open(out, cur_kind, cur_start);
                out.push_str("<li>");
            }
        }
        emit_checkbox(out, *checked);

        if item_children.len() == 2
            && depth < MAX_DEPTH
            && let (
                Block::Paragraph { raw },
                Block::List {
                    kind: inner_kind,
                    start: inner_start,
                    tight: true,
                    children: inner_children,
                },
            ) = (&item_children[0], &item_children[1])
            && inner_children.len() == 1
        {
            push_inline_or_plain(out, raw, inline.refs, inline.opts, bufs);
            out.push('\n');
            close_tags[depth] = list_close_tag(cur_kind);
            depth += 1;
            cur_kind = inner_kind;
            cur_start = *inner_start;
            cur_children = inner_children;
            continue;
        }

        if item_children.len() == 1
            && let Block::Paragraph { raw } = &item_children[0]
        {
            push_inline_or_plain(out, raw, inline.refs, inline.opts, bufs);
            // Reserve for unwind: "</li>\n" (6) + close tag (~6) per level
            let total_close_bytes = (depth + 1) * 12;
            out.reserve(total_close_bytes);
            debug_assert!(
                total_close_bytes >= 12,
                "close bytes must cover at least one level"
            );
            // SAFETY: reserved enough capacity, all bytes are ASCII.
            // Each nesting level writes at most "</li>\n" (6) + "</ul>\n"/"</ol>\n" (6) = 12 bytes.
            unsafe {
                let buf = out.as_mut_vec();
                debug_assert!(buf.capacity() - buf.len() >= total_close_bytes);
                let mut ptr = buf.as_mut_ptr().add(buf.len());

                macro_rules! write_bytes {
                    ($s:expr) => {
                        std::ptr::copy_nonoverlapping($s.as_ptr(), ptr, $s.len());
                        ptr = ptr.add($s.len());
                    };
                }

                write_bytes!(b"</li>\n");
                write_bytes!(list_close_tag(cur_kind).as_bytes());
                let mut i = depth;
                while i > 0 {
                    i -= 1;
                    write_bytes!(b"</li>\n");
                    write_bytes!(close_tags[i].as_bytes());
                }
                buf.set_len(ptr.offset_from(buf.as_ptr()) as usize);
            }
            return;
        }

        {
            let mut i = 0;
            while i < depth {
                stack.push(Work::CloseTag(close_tags[i]));
                stack.push(Work::CloseTag("</li>\n"));
                i += 1;
            }
        }
        stack.push(Work::CloseTag(list_close_tag(cur_kind)));
        stack.push(Work::CloseTag("</li>\n"));

        let mut prev_was_para = false;
        for (idx, child) in item_children.iter().enumerate() {
            match child {
                Block::Paragraph { raw } => {
                    push_inline_or_plain(out, raw, inline.refs, inline.opts, bufs);
                    prev_was_para = true;
                }
                _ => {
                    if prev_was_para || idx == 0 {
                        out.push('\n');
                    }
                    for remaining in item_children[idx..].iter().rev() {
                        stack.push(Work::TightBlock(remaining));
                    }
                    return;
                }
            }
        }
        return;
    }

    out.reserve(depth * 12);
    let mut i = depth;
    while i > 0 {
        i -= 1;
        out.push_str("</li>\n");
        out.push_str(close_tags[i]);
    }
}

#[inline]
fn render_tight_list_item<'a>(
    block: &'a Block,
    refs: &LinkRefMap,
    out: &mut String,
    opts: &ParseOptions,
    bufs: &mut InlineBuffers,
    stack: &mut Vec<Work<'a>>,
) {
    let Block::ListItem { children, checked } = block else {
        render_one(block, refs, out, opts, bufs, stack);
        return;
    };

    out.push_str("<li>");
    emit_checkbox(out, *checked);

    if children.len() == 1
        && let Block::Paragraph { raw } = &children[0]
    {
        push_inline_or_plain(out, raw, refs, opts, bufs);
        out.push_str("</li>\n");
        return;
    }

    stack.push(Work::CloseTag("</li>\n"));
    let mut prev_was_para = false;
    for (idx, child) in children.iter().enumerate() {
        match child {
            Block::Paragraph { raw } => {
                push_inline_or_plain(out, raw, refs, opts, bufs);
                prev_was_para = true;
            }
            _ => {
                if prev_was_para || idx == 0 {
                    out.push('\n');
                }
                for remaining in children[idx..].iter().rev() {
                    stack.push(Work::TightBlock(remaining));
                }
                return;
            }
        }
    }
}

#[inline]
fn render_table_cell(
    out: &mut String,
    content: &str,
    tag: &str,
    align: TableAlignment,
    refs: &LinkRefMap,
    opts: &ParseOptions,
    bufs: &mut InlineBuffers,
) {
    let (open, close) = match (tag, align) {
        ("th", TableAlignment::None) => ("<th>", "</th>\n"),
        ("td", TableAlignment::None) => ("<td>", "</td>\n"),
        ("th", TableAlignment::Left) => ("<th style=\"text-align: left\">", "</th>\n"),
        ("th", TableAlignment::Right) => ("<th style=\"text-align: right\">", "</th>\n"),
        ("th", TableAlignment::Center) => ("<th style=\"text-align: center\">", "</th>\n"),
        ("td", TableAlignment::Left) => ("<td style=\"text-align: left\">", "</td>\n"),
        ("td", TableAlignment::Right) => ("<td style=\"text-align: right\">", "</td>\n"),
        ("td", TableAlignment::Center) => ("<td style=\"text-align: center\">", "</td>\n"),
        _ => {
            out.push('<');
            out.push_str(tag);
            match align {
                TableAlignment::Left => out.push_str(" style=\"text-align: left\""),
                TableAlignment::Right => out.push_str(" style=\"text-align: right\""),
                TableAlignment::Center => out.push_str(" style=\"text-align: center\""),
                TableAlignment::None => {}
            }
            out.push('>');
            push_inline_or_plain(out, content, refs, opts, bufs);
            out.push_str("</");
            out.push_str(tag);
            out.push_str(">\n");
            return;
        }
    };
    out.push_str(open);
    push_inline_or_plain(out, content, refs, opts, bufs);
    out.push_str(close);
}

/// Generate a URL-safe slug from heading raw markdown text.
/// Strips markdown syntax, lowercases, replaces spaces/hyphens/dots with `-`.
/// Uses inline buffer for short slugs to avoid heap allocation.
pub(crate) fn heading_slug_into(slug: &mut String, raw: &str) {
    let bytes = raw.as_bytes();
    let len = bytes.len();
    slug.clear();

    // Fast path: check if heading is already slug-safe (common for simple headings).
    // A slug-safe heading has only ASCII alphanumerics and dashes (no leading/trailing dash).
    if len <= 64 {
        let mut is_safe = true;
        let mut has_content = false;
        for (idx, &b) in bytes.iter().enumerate() {
            if b.is_ascii_alphanumeric() {
                has_content = true;
            } else if b == b'-' {
                // Dash is ok if not leading/trailing and has content
                if idx == 0 || idx == len - 1 || !has_content {
                    is_safe = false;
                    break;
                }
            } else {
                is_safe = false;
                break;
            }
        }
        if is_safe && has_content {
            // Still need to lowercase
            let mut all_lower = true;
            for &b in bytes {
                if b.is_ascii_uppercase() {
                    all_lower = false;
                    break;
                }
            }
            if all_lower {
                slug.push_str(raw);
                return;
            }
            slug.push_str(raw);
            // SAFETY: lowercasing ASCII preserves UTF-8 validity
            unsafe {
                slug.as_mut_vec()
                    .iter_mut()
                    .for_each(|b| *b = b.to_ascii_lowercase())
            };
            return;
        }
    }

    // Slow path: process character by character
    slug.reserve(len.saturating_sub(slug.capacity()));
    let mut i = 0;
    let mut prev_dash = true; // start true to avoid leading dash

    while i < len {
        let b = bytes[i];
        match b {
            b'*' | b'_' | b'~' | b'=' | b'+' | b'`' => {
                i += 1;
            }
            b'<' => {
                if let Some(close) = memchr::memchr(b'>', &bytes[i..]) {
                    i += close + 1;
                } else {
                    i += 1;
                }
            }
            b'\\' => {
                i += 1;
            }
            b'[' | b']' | b'!' | b'(' | b')' => {
                i += 1;
            }
            // Spaces, hyphens, dots → single dash separator
            b' ' | b'\t' | b'-' | b'.' => {
                if !prev_dash && !slug.is_empty() {
                    slug.push('-');
                    prev_dash = true;
                }
                i += 1;
            }
            // ASCII alphanumeric → lowercase
            b if b.is_ascii_alphanumeric() => {
                slug.push(b.to_ascii_lowercase() as char);
                prev_dash = false;
                i += 1;
            }
            // Multi-byte UTF-8
            b if b >= 0x80 => {
                let char_len = crate::utf8_char_len(b);
                // SAFETY: We've verified b >= 0x80 indicating a multi-byte sequence.
                // The input `raw` is valid UTF-8, so the char boundary at `i` is valid.
                let c = unsafe { raw.get_unchecked(i..) }
                    .chars()
                    .next()
                    .unwrap_or(' ');
                if c.is_alphanumeric() {
                    for lc in c.to_lowercase() {
                        slug.push(lc);
                    }
                    prev_dash = false;
                } else {
                    // Non-alphanumeric Unicode → dash separator
                    if !prev_dash && !slug.is_empty() {
                        slug.push('-');
                        prev_dash = true;
                    }
                }
                i += char_len;
            }
            // Other ASCII punctuation → skip
            _ => {
                i += 1;
            }
        }
    }

    // Trim trailing dash
    while slug.ends_with('-') {
        slug.pop();
    }
}

pub fn benchmark_heading_slug(raw: &str) -> String {
    let mut slug = String::with_capacity(raw.len());
    heading_slug_into(&mut slug, raw);
    slug
}