pathland-markdown 0.2.3

Pathland's shared inline Markdown parser: produces AttributedString style runs + links
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
//! Shared inline Markdown parser for Pathland.
//!
//! Parses a small inline subset into a
//! [`pathland_core::AttributedString`]:
//!
//! - `**bold**` / `__bold__` → `FONT_WEIGHT` 700
//! - `*italic*` / `_italic_` → `FONT_STYLE` Italic
//! - `` `code` `` → `FONT_DESIGN` Monospaced
//! - `~~strikethrough~~` → `STRIKETHROUGH` 1
//! - `[label](url)` → link run (label text is parsed recursively)
//! - `\` escapes the next character
//!
//! Intraword underscores stay literal (`snake_case_name`), matching CommonMark
//! emphasis rules.
//!
//! The parser is `no_std` + `alloc` and is shared by every DSL: the Rust DSL
//! calls [`parse`] directly; foreign hosts (Java/JNA) call the C ABI exported
//! by the `pathland-markdown-capi` cdylib. Block-level Markdown, images, and
//! reference links are out of scope for v1.

#![no_std]

extern crate alloc;

#[cfg(test)]
extern crate std;

use alloc::string::String;
use alloc::vec::Vec;
use pathland_core::{AttributedString, LinkRun, StyleRun};

/// Parse inline Markdown into an [`AttributedString`].
///
/// Returns `None` only if the produced ranges fail the model's validation
/// (which should not happen for well-formed UTF-8 input; the parser never
/// splits code points).
#[must_use]
pub fn parse(input: &str) -> Option<AttributedString> {
    let mut text = String::new();
    let mut runs = Vec::new();
    let mut links = Vec::new();
    parse_into(input, &mut text, &mut runs, &mut links);
    AttributedString::new(text, runs, links).ok()
}

fn parse_into(input: &str, text: &mut String, runs: &mut Vec<StyleRun>, links: &mut Vec<LinkRun>) {
    let bytes = input.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => {
                let next = next_char(input, i + 1);
                match next {
                    Some((ch, end)) => {
                        text.push(ch);
                        i = end;
                    }
                    None => {
                        text.push('\\');
                        i += 1;
                    }
                }
            }
            b'*' if bytes.get(i + 1) == Some(&b'*') => {
                if let Some(end) = find_delimiter(input, i + 2, "**") {
                    let start = text.len();
                    parse_into(&input[i + 2..end], text, runs, links);
                    runs.push(StyleRun::new(byte_len(start), byte_len(text.len())).bold());
                    i = end + 2;
                } else {
                    text.push('*');
                    i += 1;
                }
            }
            b'*' => {
                if let Some(end) = find_delimiter(input, i + 1, "*") {
                    let start = text.len();
                    parse_into(&input[i + 1..end], text, runs, links);
                    runs.push(StyleRun::new(byte_len(start), byte_len(text.len())).italic());
                    i = end + 1;
                } else {
                    text.push('*');
                    i += 1;
                }
            }
            b'_' if bytes.get(i + 1) == Some(&b'_') && underscore_can_open(input, i) => {
                if let Some(end) = find_delimiter(input, i + 2, "__") {
                    let start = text.len();
                    parse_into(&input[i + 2..end], text, runs, links);
                    runs.push(StyleRun::new(byte_len(start), byte_len(text.len())).bold());
                    i = end + 2;
                } else {
                    text.push('_');
                    i += 1;
                }
            }
            b'_' if underscore_can_open(input, i) => {
                if let Some(end) = find_delimiter(input, i + 1, "_") {
                    let start = text.len();
                    parse_into(&input[i + 1..end], text, runs, links);
                    runs.push(StyleRun::new(byte_len(start), byte_len(text.len())).italic());
                    i = end + 1;
                } else {
                    text.push('_');
                    i += 1;
                }
            }
            b'~' if bytes.get(i + 1) == Some(&b'~') => {
                if let Some(end) = find_delimiter(input, i + 2, "~~") {
                    let start = text.len();
                    parse_into(&input[i + 2..end], text, runs, links);
                    runs.push(StyleRun::new(byte_len(start), byte_len(text.len())).strikethrough());
                    i = end + 2;
                } else {
                    text.push('~');
                    i += 1;
                }
            }
            b'`' => {
                if let Some(end) = find_delimiter(input, i + 1, "`") {
                    let start = text.len();
                    text.push_str(&input[i + 1..end]);
                    runs.push(StyleRun::new(byte_len(start), byte_len(text.len())).monospaced());
                    i = end + 1;
                } else {
                    text.push('`');
                    i += 1;
                }
            }
            b'[' => {
                if let Some((label_end, url, after)) = parse_link(input, i) {
                    let start = text.len();
                    parse_into(&input[i + 1..label_end], text, runs, links);
                    links.push(LinkRun::new(byte_len(start), byte_len(text.len()), url));
                    i = after;
                } else {
                    text.push('[');
                    i += 1;
                }
            }
            _ => {
                let (ch, end) = next_char(input, i).expect("valid utf-8 boundary");
                text.push(ch);
                i = end;
            }
        }
    }
}

fn byte_len(value: usize) -> u32 {
    u32::try_from(value).unwrap_or(u32::MAX)
}

/// Underscore emphasis is not allowed intraword (`snake_case` stays literal).
fn underscore_can_open(input: &str, at: usize) -> bool {
    input[..at]
        .chars()
        .next_back()
        .is_none_or(|c| !c.is_alphanumeric())
}

fn underscore_can_close(input: &str, after_run: usize) -> bool {
    input[after_run..]
        .chars()
        .next()
        .is_none_or(|c| !c.is_alphanumeric())
}

/// Find the next closing delimiter at or after `from`, returning its byte
/// offset. Escaped characters are skipped.
///
/// Asterisk runs are split so nesting works: for a run of three (`***`) the
/// outer `**` close uses the last two stars and the inner `*` close uses the
/// first. A lone `*` never closes on a `**` run (that is nested bold).
fn find_delimiter(input: &str, from: usize, needle: &str) -> Option<usize> {
    let bytes = input.as_bytes();
    let mut i = from;
    while i < bytes.len() {
        if bytes[i] == b'\\' {
            i += 2;
            continue;
        }
        match needle {
            "**" => {
                if bytes[i] == b'*' {
                    let mut end = i;
                    while end < bytes.len() && bytes[end] == b'*' {
                        end += 1;
                    }
                    if end - i >= 2 {
                        return Some(end - 2);
                    }
                }
            }
            "*" => {
                if bytes[i] == b'*' {
                    let mut end = i;
                    while end < bytes.len() && bytes[end] == b'*' {
                        end += 1;
                    }
                    if end - i == 1 {
                        return Some(i);
                    }
                    i = end;
                    continue;
                }
            }
            "__" => {
                if bytes[i] == b'_' {
                    let mut end = i;
                    while end < bytes.len() && bytes[end] == b'_' {
                        end += 1;
                    }
                    if end - i >= 2 && underscore_can_close(input, end) {
                        return Some(end - 2);
                    }
                }
            }
            "_" => {
                if bytes[i] == b'_' {
                    let mut end = i;
                    while end < bytes.len() && bytes[end] == b'_' {
                        end += 1;
                    }
                    if end - i == 1 && underscore_can_close(input, end) {
                        return Some(i);
                    }
                    i = end;
                    continue;
                }
            }
            "~~" => {
                if bytes[i] == b'~' {
                    let mut end = i;
                    while end < bytes.len() && bytes[end] == b'~' {
                        end += 1;
                    }
                    if end - i >= 2 {
                        return Some(end - 2);
                    }
                }
            }
            _ => {
                if input[i..].starts_with(needle) {
                    return Some(i);
                }
            }
        }
        i = next_char(input, i)?.1;
    }
    None
}

/// Parse `[label](url)` at `open`. Returns `(label_end, url, after_close)`.
fn parse_link(input: &str, open: usize) -> Option<(usize, &str, usize)> {
    let bytes = input.as_bytes();
    let mut i = open + 1;
    while i < bytes.len() {
        if bytes[i] == b'\\' {
            i += 2;
            continue;
        }
        if bytes[i] == b']' && bytes.get(i + 1) == Some(&b'(') {
            let label_end = i;
            let url_start = i + 2;
            let mut j = url_start;
            while j < bytes.len() {
                if bytes[j] == b'\\' {
                    j += 2;
                    continue;
                }
                if bytes[j] == b')' {
                    return Some((label_end, &input[url_start..j], j + 1));
                }
                j = next_char(input, j)?.1;
            }
            return None;
        }
        i = next_char(input, i)?.1;
    }
    None
}

fn next_char(input: &str, at: usize) -> Option<(char, usize)> {
    let ch = input[at..].chars().next()?;
    Some((ch, at + ch.len_utf8()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use pathland_core::{property_id, value_type};

    fn decoded(markdown: &str) -> AttributedString {
        parse(markdown).expect("parser output is valid")
    }

    #[test]
    fn plain_text_has_no_runs() {
        let value = decoded("hello");
        assert_eq!(value.text(), "hello");
        assert!(value.runs().is_empty());
        assert!(value.links().is_empty());
    }

    #[test]
    fn maps_each_inline_marker() {
        let value = decoded("**b** *i* `c` ~~s~~");
        assert_eq!(value.text(), "b i c s");
        assert_eq!(value.runs().len(), 4);
        assert_eq!(value.runs()[0].start, 0);
        assert_eq!(value.runs()[0].end, 1);
        assert!(value.runs()[0]
            .attributes
            .iter()
            .any(|a| { a.property == property_id::FONT_WEIGHT && a.value == 700.0f32.to_bits() }));
        assert!(value.runs()[1]
            .attributes
            .iter()
            .any(|a| { a.property == property_id::FONT_STYLE && a.value == 1.0f32.to_bits() }));
        assert!(value.runs()[2]
            .attributes
            .iter()
            .any(|a| { a.property == property_id::FONT_DESIGN && a.value == 3.0f32.to_bits() }));
        assert!(value.runs()[3].attributes.iter().any(|a| {
            a.property == property_id::STRIKETHROUGH && a.value_type == value_type::U8
        }));
    }

    #[test]
    fn nests_formats() {
        let value = decoded("**bold *and italic***");
        assert_eq!(value.text(), "bold and italic");
        assert_eq!(value.runs().len(), 2);
        assert_eq!(value.runs()[0].start, 5);
        assert_eq!(value.runs()[0].end, 15);
        assert_eq!(value.runs()[1].start, 0);
        assert_eq!(value.runs()[1].end, 15);
    }

    #[test]
    fn links_carry_label_runs_and_url() {
        let value = decoded("[**hi**](https://example.com)");
        assert_eq!(value.text(), "hi");
        assert_eq!(value.links().len(), 1);
        assert_eq!(value.links()[0].url, "https://example.com");
        assert_eq!(value.links()[0].start, 0);
        assert_eq!(value.links()[0].end, 2);
        assert_eq!(value.runs().len(), 1);
    }

    #[test]
    fn code_spans_do_not_parse_inner_markup() {
        let value = decoded("`**not bold**`");
        assert_eq!(value.text(), "**not bold**");
        assert_eq!(value.runs().len(), 1);
        assert_eq!(
            value.runs()[0].attributes[0].property,
            property_id::FONT_DESIGN
        );
    }

    #[test]
    fn underscore_emphasis_matches_asterisk_forms() {
        let value = decoded("_italic_ and __bold__");
        assert_eq!(value.text(), "italic and bold");
        assert_eq!(value.runs().len(), 2);
        assert!(value.runs()[0]
            .attributes
            .iter()
            .any(|a| a.property == property_id::FONT_STYLE));
        assert!(value.runs()[1]
            .attributes
            .iter()
            .any(|a| a.property == property_id::FONT_WEIGHT));
    }

    #[test]
    fn intraword_underscores_stay_literal() {
        let value = decoded("snake_case_name");
        assert_eq!(value.text(), "snake_case_name");
        assert!(value.runs().is_empty());
    }

    #[test]
    fn escaped_underscores_are_literal() {
        let value = decoded(r"\_not italic\_");
        assert_eq!(value.text(), "_not italic_");
        assert!(value.runs().is_empty());
    }

    #[test]
    fn escapes_are_literal() {
        let value = decoded(r"\*not italic\*");
        assert_eq!(value.text(), "*not italic*");
        assert!(value.runs().is_empty());
    }

    #[test]
    fn unmatched_markers_stay_literal() {
        let value = decoded("a * b ** c");
        assert_eq!(value.text(), "a * b ** c");
        assert!(value.runs().is_empty());
    }

    #[test]
    fn utf8_offsets_are_bytes() {
        let value = decoded("é**ü**");
        assert_eq!(value.text(), "éü");
        assert_eq!(value.runs()[0].start, 2);
        assert_eq!(value.runs()[0].end, 4);
    }
}