Skip to main content

tabnas_markdown/
common.rs

1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3//! Shared lexical helpers. Port of `ts/src/common.ts` and `go/common.go`:
4//! the character classes the spec names, backslash and entity unescaping
5//! (sections 6.1 and 6.2), link-label normalisation (section 4.7), and the
6//! URL and XML escaping the HTML renderer needs.
7//!
8//! These are the pieces where "close enough" silently costs conformance
9//! examples, so each one names the spec rule it implements.
10//!
11//! Two things differ from the TypeScript, both because Rust has a better
12//! tool for the job:
13//!
14//! - Unicode punctuation is asked of the `regex` crate's Unicode tables
15//!   (`\p{P}` and `\p{S}`), which is the same property escape the
16//!   TypeScript uses, rather than an enumerated code-point table.
17//! - Case folding for label matching uses `str::to_lowercase` and
18//!   `str::to_uppercase`, which implement the FULL Unicode mappings (so
19//!   `ß` uppercases to `SS`, and CommonMark example 540 holds) exactly as
20//!   JavaScript's do. The Go port needs a hand-built table for this.
21
22use std::sync::OnceLock;
23
24use regex::Regex;
25
26use crate::entities;
27
28/// The full ASCII punctuation set of section 2.1: everything that may
29/// follow a backslash.
30pub const ESCAPABLE_ASCII: &str = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
31
32/// Section 6.2: a valid entity is always semicolon-terminated. Both cases
33/// are spelled out, so no `(?i)` flag is needed; the TypeScript applies `i`
34/// to a lowercase pattern.
35pub const ENTITY_PATTERN: &str =
36    r"&(?:#[xX][a-fA-F0-9]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{1,31});";
37
38fn re_entity_or_escaped_char() -> &'static Regex {
39    static RE: OnceLock<Regex> = OnceLock::new();
40    RE.get_or_init(|| {
41        Regex::new(&format!(
42            r"\\[{}]|{}",
43            regex::escape(ESCAPABLE_ASCII),
44            ENTITY_PATTERN
45        ))
46        .expect("the unescape pattern is a literal and compiles")
47    })
48}
49
50fn re_entity_whole() -> &'static Regex {
51    static RE: OnceLock<Regex> = OnceLock::new();
52    RE.get_or_init(|| {
53        Regex::new(&format!("^(?:{ENTITY_PATTERN})$"))
54            .expect("the entity pattern is a literal and compiles")
55    })
56}
57
58fn re_whitespace_run() -> &'static Regex {
59    static RE: OnceLock<Regex> = OnceLock::new();
60    RE.get_or_init(|| Regex::new(r"[ \t\r\n]+").expect("a literal pattern compiles"))
61}
62
63/// Section 2.1 Unicode punctuation, which 0.31.2 widened from the P*
64/// categories alone to P* union S*; that is why `$ + < = > ^ ` | ~ £ €`
65/// count. Expressed with Unicode property escapes rather than an
66/// enumerated table: the table form silently rots against each Unicode
67/// revision, and a P-only table is exactly the near-miss that costs
68/// emphasis-flanking examples.
69fn re_unicode_punctuation() -> &'static Regex {
70    static RE: OnceLock<Regex> = OnceLock::new();
71    RE.get_or_init(|| Regex::new(r"^[\p{P}\p{S}]$").expect("a literal pattern compiles"))
72}
73
74/// Whether `b` is ASCII punctuation, i.e. may follow a backslash (section
75/// 6.1).
76pub fn is_escapable(b: u8) -> bool {
77    ESCAPABLE_ASCII.as_bytes().contains(&b)
78}
79
80/// Section 2.3 Unicode whitespace. Deliberately not `char::is_whitespace`:
81/// that set differs from the spec's at the edges, and emphasis flanking
82/// (section 6.4) is decided on exactly this set.
83pub fn is_unicode_whitespace(c: char) -> bool {
84    matches!(c, '\t' | '\n' | '\u{c}' | '\r' | ' ')
85        || matches!(
86            c,
87            '\u{00A0}'
88                | '\u{1680}'
89                | '\u{2028}'
90                | '\u{2029}'
91                | '\u{202F}'
92                | '\u{205F}'
93                | '\u{3000}'
94        )
95        || ('\u{2000}'..='\u{200A}').contains(&c)
96}
97
98/// Section 2.1 Unicode punctuation: P* union S*. Used only by the emphasis
99/// flanking rules.
100pub fn is_unicode_punctuation(c: char) -> bool {
101    if c.is_ascii() {
102        // Every ASCII character in P or S is in the section 2.1 ASCII set,
103        // and vice versa.
104        return is_escapable(c as u8);
105    }
106    let mut buf = [0u8; 4];
107    re_unicode_punctuation().is_match(c.encode_utf8(&mut buf))
108}
109
110/// Section 6.2. Named references resolve from the HTML5 table; numeric
111/// ones from the code point, with U+0000, surrogates and anything out of
112/// range folded to U+FFFD as the spec requires. Anything that is not a
113/// valid reference comes back unchanged.
114pub fn decode_entity(text: &str) -> String {
115    if !re_entity_whole().is_match(text) {
116        return text.to_string();
117    }
118
119    let body = &text[1..text.len() - 1];
120
121    if let Some(numeric) = body.strip_prefix('#') {
122        let (digits, radix) = match numeric.strip_prefix(['x', 'X']) {
123            Some(hex) => (hex, 16),
124            None => (numeric, 10),
125        };
126        let cp = u32::from_str_radix(digits, radix).ok();
127        return match cp {
128            Some(cp) if cp != 0 && cp <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&cp) => {
129                char::from_u32(cp)
130                    .map(|c| c.to_string())
131                    .unwrap_or_else(|| "\u{FFFD}".to_string())
132            }
133            _ => "\u{FFFD}".to_string(),
134        };
135    }
136
137    match entities::lookup(body) {
138        Some(replacement) => replacement.to_string(),
139        None => text.to_string(),
140    }
141}
142
143/// Sections 6.1 and 6.2: resolve backslash escapes and entity references
144/// together.
145pub fn unescape_string(s: &str) -> String {
146    if !s.contains(['\\', '&']) {
147        return s.to_string();
148    }
149    re_entity_or_escaped_char()
150        .replace_all(s, |captures: &regex::Captures<'_>| {
151            let m = &captures[0];
152            if let Some(escaped) = m.strip_prefix('\\') {
153                escaped.to_string()
154            } else {
155                decode_entity(m)
156            }
157        })
158        .into_owned()
159}
160
161/// JavaScript whitespace: the ECMAScript WhiteSpace and LineTerminator
162/// productions, which are both what `\s` matches and what
163/// `String.prototype.trim()` removes. That is the spec's section 2.3
164/// Unicode whitespace plus the vertical tab and U+FEFF.
165///
166/// Deliberately distinct from [`is_unicode_whitespace`], which is section
167/// 2.3 exactly and answers a different question (emphasis flanking). And
168/// deliberately used in place of `str::trim` wherever the canonical
169/// runtime uses a JavaScript trim or `\s`: `char::is_whitespace` trims
170/// U+0085, which JavaScript keeps, and keeps U+FEFF, which JavaScript
171/// trims. Four separate places turn on exactly this set (the fence info
172/// string, the trailing-space test that decides a hard line break, the
173/// code fence's language/meta split, and section 4.7 label matching), so
174/// it is defined once.
175pub fn is_js_space(c: char) -> bool {
176    c == '\u{b}' || c == '\u{FEFF}' || is_unicode_whitespace(c)
177}
178
179/// Exactly what `String.prototype.trim()` removes.
180pub fn js_trim(s: &str) -> &str {
181    s.trim_matches(is_js_space)
182}
183
184/// The byte index of the first JavaScript-whitespace character in `s`,
185/// with its UTF-8 width, or `None` when there is none. It is the Rust
186/// spelling of `s.search(/\s/)`, except that the index is a byte offset
187/// and the width comes back too: JavaScript can advance past the match
188/// with `+ 1` because every character in the class is BMP, where Rust
189/// must step a whole character.
190pub fn js_space_index(s: &str) -> Option<(usize, usize)> {
191    s.char_indices()
192        .find(|(_, c)| is_js_space(*c))
193        .map(|(index, c)| (index, c.len_utf8()))
194}
195
196/// Section 4.7 label matching: case-insensitive under Unicode case folding,
197/// with internal whitespace collapsed.
198///
199/// Lowercase then uppercase is the approximation of full case folding the
200/// reference implementation uses; it makes ẞ/ß and Σ/ς agree. Rust's
201/// `to_lowercase` and `to_uppercase` are the full mappings, the same ones
202/// JavaScript's `toLowerCase` and `toUpperCase` apply.
203pub fn normalize_reference(raw_label: &str) -> String {
204    let trimmed = js_trim(raw_label);
205    let collapsed = re_whitespace_run().replace_all(trimmed, " ");
206    if collapsed.is_ascii() {
207        // For ASCII, lowercasing then uppercasing is just uppercasing.
208        return collapsed.to_ascii_uppercase();
209    }
210    collapsed.to_lowercase().to_uppercase()
211}
212
213/// HTML output escaping, applied to text and, identically, to attribute
214/// values.
215pub fn escape_xml(s: &str) -> String {
216    if !s.contains(['&', '<', '>', '"']) {
217        return s.to_string();
218    }
219    let mut out = String::with_capacity(s.len() + 8);
220    for c in s.chars() {
221        match c {
222            '&' => out.push_str("&amp;"),
223            '<' => out.push_str("&lt;"),
224            '>' => out.push_str("&gt;"),
225            '"' => out.push_str("&quot;"),
226            c => out.push(c),
227        }
228    }
229    out
230}
231
232/// The set left unencoded by [`normalize_uri`], matching the reference
233/// renderer so hrefs come out byte-identical to the spec's expected HTML.
234const URL_SAFE: &str = ";/?:@&=+$,-_.!~*'()#";
235
236fn is_url_safe(b: u8) -> bool {
237    b.is_ascii_alphanumeric() || URL_SAFE.as_bytes().contains(&b)
238}
239
240const UPPER_HEX: &[u8; 16] = b"0123456789ABCDEF";
241
242fn push_percent(out: &mut String, b: u8) {
243    out.push('%');
244    out.push(UPPER_HEX[(b >> 4) as usize] as char);
245    out.push(UPPER_HEX[(b & 0x0F) as usize] as char);
246}
247
248/// Percent-encode a destination for output, preserving sequences that are
249/// already valid `%XX` triplets so a pre-encoded URL is not double-encoded.
250/// A multi-byte character is encoded as its UTF-8 bytes, which is what the
251/// canonical `encodeURIComponent` produces for it.
252pub fn normalize_uri(uri: &str) -> String {
253    let bytes = uri.as_bytes();
254    let mut out = String::with_capacity(uri.len());
255    let mut i = 0;
256    while i < bytes.len() {
257        let c = bytes[i];
258        if c == b'%'
259            && i + 2 < bytes.len()
260            && bytes[i + 1].is_ascii_hexdigit()
261            && bytes[i + 2].is_ascii_hexdigit()
262        {
263            out.push_str(&uri[i..i + 3]);
264            i += 3;
265            continue;
266        }
267        if c.is_ascii() {
268            if is_url_safe(c) {
269                out.push(c as char);
270            } else {
271                push_percent(&mut out, c);
272            }
273            i += 1;
274            continue;
275        }
276        // Multi-byte: percent-encode every UTF-8 byte of the character.
277        push_percent(&mut out, c);
278        i += 1;
279    }
280    out
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn entities_decode_per_section_6_2() {
289        assert_eq!(decode_entity("&amp;"), "&");
290        assert_eq!(decode_entity("&#65;"), "A");
291        assert_eq!(decode_entity("&#x41;"), "A");
292        assert_eq!(decode_entity("&#0;"), "\u{FFFD}");
293        assert_eq!(decode_entity("&#xD800;"), "\u{FFFD}");
294        assert_eq!(decode_entity("&#1114112;"), "\u{FFFD}");
295        assert_eq!(decode_entity("&nosuch;"), "&nosuch;");
296        assert_eq!(decode_entity("&ampa;"), "&ampa;");
297        assert_eq!(decode_entity("&amp"), "&amp");
298        assert_eq!(decode_entity("&nGt;"), "\u{226B}\u{20D2}");
299    }
300
301    #[test]
302    fn unescape_resolves_both_forms_together() {
303        assert_eq!(unescape_string(r"\*a\* &amp; b"), "*a* & b");
304        assert_eq!(unescape_string("plain"), "plain");
305        assert_eq!(unescape_string(r"\a"), r"\a");
306    }
307
308    #[test]
309    fn label_normalisation_uses_full_case_mapping() {
310        assert_eq!(normalize_reference("  Foo   Bar "), "FOO BAR");
311        assert_eq!(normalize_reference("ẞ"), normalize_reference("SS"));
312        assert_eq!(normalize_reference("Σ"), normalize_reference("ς"));
313    }
314
315    #[test]
316    fn punctuation_is_p_union_s() {
317        for c in [
318            '$', '+', '<', '=', '>', '^', '`', '|', '~', '£', '€', '«', '。',
319        ] {
320            assert!(is_unicode_punctuation(c), "{c:?}");
321        }
322        for c in ['a', '1', ' ', 'é', '\u{200B}'] {
323            assert!(!is_unicode_punctuation(c), "{c:?}");
324        }
325    }
326
327    #[test]
328    fn uri_normalisation_matches_the_reference_renderer() {
329        assert_eq!(normalize_uri("/ä"), "/%C3%A4");
330        assert_eq!(normalize_uri("/a%20b"), "/a%20b");
331        assert_eq!(normalize_uri("/a b"), "/a%20b");
332        assert_eq!(
333            normalize_uri("http://x.y/?q=1&r=(2)"),
334            "http://x.y/?q=1&r=(2)"
335        );
336    }
337
338    #[test]
339    fn xml_escaping() {
340        assert_eq!(escape_xml("a<b>&\"c"), "a&lt;b&gt;&amp;&quot;c");
341    }
342}