Skip to main content

flm_core/stdlib/backends/html/
escape.rs

1//! The escaping of document text for HTML: the three functions that rewrite
2//! the characters a browser would otherwise read as markup, one for text
3//! between tags and two for attribute values.
4//!
5//! **Escaping** means writing a character as a *character reference* — the
6//! spelling `&name;` or `&#number;` that HTML reads back as that one character
7//! — so that the character reaches the reader as itself instead of being taken
8//! for syntax. HTML needs it in two places, and they are not the same place:
9//! the text between tags, where `<` would start a tag, and the value of an
10//! attribute, where the quotation mark closing the value ends it.
11//!
12//! The three escaping functions here are the whole of the HTML backend's
13//! escaping. [`escape_text_into`] is what
14//! [`HtmlSink::text`](super::HtmlSink::text) writes through,
15//! [`escape_attr_into`] what
16//! [`TagBuilder::attr`](super::TagBuilder::attr) writes through, and
17//! [`escape_attr_single_quoted_into`] what
18//! [`TagBuilder::attr_json`](super::TagBuilder::attr_json) writes through; an
19//! emitter calls the sink and never these functions, which are public so that
20//! a test or a host can check exactly what the sink does. All three are total:
21//! every string has a result, nothing is refused, and none of them ever reads
22//! output back ([the sink](super::sink) explains why that matters).
23//!
24//! # What is escaped, and what is not
25//!
26//! In **text**, three characters become references — `&`, `<` and `>` — and
27//! eight space characters are written as numeric references (below).
28//! Nothing else is rewritten: the output is UTF-8 and every other character,
29//! accented or not, is written as itself. A quotation mark needs no escaping
30//! between tags, and is written as itself.
31//!
32//! In an **attribute value written inside double quotation marks**, four
33//! characters become references — `&`, `<`, `>` and `"` — always, regardless
34//! of what the value holds and where it came from. This is how almost every
35//! attribute of this backend is written, so escaping the quotation mark keeps a
36//! value from ending its attribute early. `&`, `<` and `>` are escaped there as
37//! well, so that the value is valid regardless of what it holds, and because
38//! this library never reads written output back to find out whether a value
39//! was escaped already.
40//!
41//! In an **attribute value written inside single quotation marks**, two
42//! characters become references — `&` and `'` — and nothing else is rewritten:
43//! a double quotation mark, a `<` and a `>` are written as themselves, which HTML
44//! allows inside a quoted attribute value. This is how an attribute whose
45//! value is JSON is written, so that the raw page shows the JSON as
46//! JSON — `data-flm-source-span='["book/ch1.flm",0,8]'` — instead of a line of
47//! `&quot;`. It escapes as unconditionally as the other two: text a document
48//! wrote cannot leave the attribute through it.
49//!
50//! A further function, `json_string_into`, is not one of the three: it is not
51//! HTML escaping and is not public, being used by this backend's emitter
52//! alone. It writes a string the way JSON writes one, for the only attribute
53//! whose *value* is a JSON value rather than a plain word: the attribute
54//! `data-flm-source-span`, which records where an element's node is located
55//! in its source. The two escapings then apply one after the other: the value
56//! is built as JSON, and the sink escapes that value for HTML with
57//! [`escape_attr_single_quoted_into`], so a browser returns the JSON
58//! intact.
59//!
60//! Escaping is the same inside `<pre>` and `<code>` as everywhere else. Those
61//! elements change how a browser lays text out, not how it reads markup: a `<`
62//! inside them still starts a tag.
63//!
64//! # The eight spaces
65//!
66//! Eight Unicode space characters are written as *numeric* character
67//! references ([`SPACE_REFERENCES`]) — the spelling `&#x` followed by the
68//! character's number in hexadecimal — because a space character that is not
69//! the ordinary one cannot be told from an ordinary space by looking at the
70//! output: a reviewer comparing two pages, or reading a diff, would see
71//! nothing.
72//!
73//! The spelling is numeric rather than a name such as `&nbsp;` because a
74//! numeric reference is read the same way wherever the output is embedded,
75//! XML included, while those names are defined by HTML alone and an XML parser
76//! refuses every one of them. A numeric reference shows in a comparison of two
77//! outputs as clearly as a named one, and that is the purpose of the
78//! rewriting.
79
80/// The eight space characters written as numeric character references, each
81/// with the reference written for it: the no-break space, the hair space,
82/// the thin space, the punctuation space, the en space, the em space, the
83/// figure space and the narrow no-break space.
84///
85/// The table is public so that a test or a host can refer to the same eight
86/// characters without repeating them. It is used by [`escape_text_into`]
87/// alone: an attribute value is not rewritten this way, since a reader does
88/// not compare the spaces inside one.
89pub const SPACE_REFERENCES: [(char, &str); 8] = [
90    ('\u{00A0}', "&#xA0;"),
91    ('\u{200A}', "&#x200A;"),
92    ('\u{2009}', "&#x2009;"),
93    ('\u{2008}', "&#x2008;"),
94    ('\u{2002}', "&#x2002;"),
95    ('\u{2003}', "&#x2003;"),
96    ('\u{2007}', "&#x2007;"),
97    ('\u{202F}', "&#x202F;"),
98];
99
100/// Returns the numeric character reference of one of the eight spaces
101/// ([`SPACE_REFERENCES`]), or `None` for every other character.
102fn space_reference(ch: char) -> Option<&'static str> {
103    SPACE_REFERENCES.iter().find(|(space, _)| *space == ch).map(|(_, reference)| *reference)
104}
105
106/// Appends `text` to `out` escaped as document text: `&`, `<` and `>` as their
107/// character references, the eight spaces of [`SPACE_REFERENCES`] as their
108/// numeric references, every other character as itself.
109///
110/// This is what [`HtmlSink::text`](super::HtmlSink::text) writes through; see
111/// [the module documentation](self) for what is escaped where and why.
112///
113/// # Examples
114///
115/// ```
116/// use flm_core::stdlib::backends::html::escape::escape_text_into;
117///
118/// let mut out = String::new();
119/// escape_text_into(&mut out, "a < b & \"c\"");
120/// assert_eq!(out, "a &lt; b &amp; \"c\"");
121///
122/// // A string that already holds a character reference is escaped again: the
123/// // text a document wrote is text, never markup.
124/// let mut out = String::new();
125/// escape_text_into(&mut out, "&amp;");
126/// assert_eq!(out, "&amp;amp;");
127///
128/// // A no-break space, which nobody could see in the output otherwise.
129/// let mut out = String::new();
130/// escape_text_into(&mut out, "10\u{00A0}km");
131/// assert_eq!(out, "10&#xA0;km");
132/// ```
133pub fn escape_text_into(out: &mut String, text: &str) {
134    for ch in text.chars() {
135        match ch {
136            '&' => out.push_str("&amp;"),
137            '<' => out.push_str("&lt;"),
138            '>' => out.push_str("&gt;"),
139            _ if ch.is_ascii() => out.push(ch),
140            _ => match space_reference(ch) {
141                Some(reference) => out.push_str(reference),
142                None => out.push(ch),
143            },
144        }
145    }
146}
147
148/// Appends `value` to `out` escaped as the value of an attribute written
149/// inside double quotation marks: `&`, `<`, `>` and `"` as their character
150/// references, every other character as itself — the eight spaces included,
151/// since an attribute value is not read by a person the way text is.
152///
153/// This is what [`TagBuilder::attr`](super::TagBuilder::attr) writes through;
154/// see [the module documentation](self) for why the escaping is unconditional.
155///
156/// # Examples
157///
158/// ```
159/// use flm_core::stdlib::backends::html::escape::escape_attr_into;
160///
161/// let mut out = String::new();
162/// escape_attr_into(&mut out, "a \"quoted\" <value>");
163/// assert_eq!(out, "a &quot;quoted&quot; &lt;value&gt;");
164///
165/// // An address keeps every character it needs; only the four are rewritten.
166/// let mut out = String::new();
167/// escape_attr_into(&mut out, "https://example.org/p?a=1&b=2");
168/// assert_eq!(out, "https://example.org/p?a=1&amp;b=2");
169/// ```
170pub fn escape_attr_into(out: &mut String, value: &str) {
171    for ch in value.chars() {
172        match ch {
173            '&' => out.push_str("&amp;"),
174            '<' => out.push_str("&lt;"),
175            '>' => out.push_str("&gt;"),
176            '"' => out.push_str("&quot;"),
177            _ => out.push(ch),
178        }
179    }
180}
181
182/// Appends `value` to `out` escaped as the value of an attribute written
183/// inside single quotation marks: `&` as `&amp;` and `'` as `&#39;`, every
184/// other character as itself — a double quotation mark, a `<` and a `>`
185/// included, which HTML allows inside a quoted attribute value.
186///
187/// This is what [`TagBuilder::attr_json`](super::TagBuilder::attr_json) writes
188/// through, and it is meant for an attribute whose value is a JSON value: a
189/// JSON value is full of double quotation marks, and writing it between single
190/// quotation marks leaves them as themselves, so the raw page shows the value
191/// as JSON. See [the module documentation](self) for what is escaped where.
192///
193/// Escaping the two characters keeps a value from ending its attribute early.
194/// The escaping is unconditional: regardless of what the value holds and where
195/// it came from, the result cannot leave the attribute.
196///
197/// # Examples
198///
199/// ```
200/// use flm_core::stdlib::backends::html::escape::escape_attr_single_quoted_into;
201///
202/// let mut out = String::new();
203/// escape_attr_single_quoted_into(&mut out, "[\"book/ch1.flm\",0,8]");
204/// assert_eq!(out, "[\"book/ch1.flm\",0,8]");
205///
206/// // The two characters that are rewritten, and only those.
207/// let mut out = String::new();
208/// escape_attr_single_quoted_into(&mut out, "it's <a & b>");
209/// assert_eq!(out, "it&#39;s <a &amp; b>");
210/// ```
211pub fn escape_attr_single_quoted_into(out: &mut String, value: &str) {
212    for ch in value.chars() {
213        match ch {
214            '&' => out.push_str("&amp;"),
215            '\'' => out.push_str("&#39;"),
216            _ => out.push(ch),
217        }
218    }
219}
220
221/// Appends `value` to `out` as JSON spells a string: the quotation marks
222/// around it, a backslash before every quotation mark and every backslash
223/// inside it, and every control character (below `U+0020`) as the short escape
224/// JSON gives it or as `\u00XX`.
225///
226/// Every other character is written as itself, which is valid JSON: a JSON
227/// document is Unicode text, and this library's output is UTF-8.
228///
229/// This is not HTML escaping and does not replace it. The result is JSON text;
230/// written as an attribute value it goes through
231/// [`escape_attr_single_quoted_into`] afterwards, which leaves its quotation
232/// marks as themselves and writes the value between single quotation marks.
233/// See the module documentation.
234///
235/// It is not public: the only attribute whose value is JSON is written by this
236/// backend's emitter, and nothing outside the backend has a use for it.
237pub(super) fn json_string_into(out: &mut String, value: &str) {
238    out.push('"');
239    for ch in value.chars() {
240        match ch {
241            '"' => out.push_str("\\\""),
242            '\\' => out.push_str("\\\\"),
243            '\u{8}' => out.push_str("\\b"),
244            '\u{c}' => out.push_str("\\f"),
245            '\n' => out.push_str("\\n"),
246            '\r' => out.push_str("\\r"),
247            '\t' => out.push_str("\\t"),
248            _ if (ch as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", ch as u32)),
249            _ => out.push(ch),
250        }
251    }
252    out.push('"');
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    fn text(input: &str) -> String {
260        let mut out = String::new();
261        escape_text_into(&mut out, input);
262        out
263    }
264
265    fn attr(input: &str) -> String {
266        let mut out = String::new();
267        escape_attr_into(&mut out, input);
268        out
269    }
270
271    #[test]
272    fn text_escapes_three_characters_and_leaves_the_quotation_marks() {
273        assert_eq!(text("a & b < c > d \"e\" 'f'"), "a &amp; b &lt; c &gt; d \"e\" 'f'");
274    }
275
276    #[test]
277    fn an_attribute_value_escapes_four_characters_always() {
278        assert_eq!(attr("a & b < c > d \"e\" 'f'"), "a &amp; b &lt; c &gt; d &quot;e&quot; 'f'");
279    }
280
281    #[test]
282    fn the_eight_spaces_are_written_as_their_numeric_references_in_text_only() {
283        let spaces: String = SPACE_REFERENCES.iter().map(|(ch, _)| *ch).collect();
284        let expected: String = SPACE_REFERENCES.iter().map(|(_, r)| *r).collect();
285        assert_eq!(text(&spaces), expected);
286        assert_eq!(attr(&spaces), spaces);
287        // The ordinary space is not one of them.
288        assert_eq!(text(" "), " ");
289    }
290
291    fn attr_single(input: &str) -> String {
292        let mut out = String::new();
293        escape_attr_single_quoted_into(&mut out, input);
294        out
295    }
296
297    #[test]
298    fn a_single_quoted_attribute_value_escapes_two_characters_and_no_others() {
299        assert_eq!(
300            attr_single("a & b < c > d \"e\" 'f'"),
301            "a &amp; b < c > d \"e\" &#39;f&#39;"
302        );
303    }
304
305    #[test]
306    fn a_json_array_is_written_as_json_between_single_quotation_marks() {
307        let mut value = String::from("[");
308        json_string_into(&mut value, "book/ch1.flm");
309        value.push_str(",0,8]");
310        assert_eq!(attr_single(&value), "[\"book/ch1.flm\",0,8]");
311    }
312
313    #[test]
314    fn nothing_else_is_rewritten_and_the_output_is_utf8() {
315        let probe = "Café — naïve “quotes” ½ ≤ α 😅";
316        assert_eq!(text(probe), probe);
317        assert_eq!(attr(probe), probe);
318        assert_eq!(attr_single(probe), probe);
319    }
320
321    #[test]
322    fn both_functions_append_to_what_the_buffer_already_holds() {
323        let mut out = String::from("<p>");
324        escape_text_into(&mut out, "a<b");
325        assert_eq!(out, "<p>a&lt;b");
326    }
327
328    fn json(input: &str) -> String {
329        let mut out = String::new();
330        json_string_into(&mut out, input);
331        out
332    }
333
334    #[test]
335    fn a_json_string_carries_its_quotation_marks() {
336        assert_eq!(json(""), "\"\"");
337        assert_eq!(json("book/ch1.flm"), "\"book/ch1.flm\"");
338    }
339
340    #[test]
341    fn a_name_holding_a_quotation_mark_a_backslash_and_a_control_character_survives() {
342        assert_eq!(json("a\"b\\c\td\u{1}e"), "\"a\\\"b\\\\c\\td\\u0001e\"");
343    }
344
345    #[test]
346    fn a_quotation_mark_and_a_backslash_are_written_with_a_backslash_before_them() {
347        assert_eq!(json("a\"b"), "\"a\\\"b\"");
348        assert_eq!(json("a\\b"), "\"a\\\\b\"");
349        assert_eq!(json("\\\""), "\"\\\\\\\"\"");
350    }
351
352    #[test]
353    fn a_control_character_is_written_as_an_escape() {
354        assert_eq!(json("\u{8}\u{c}\n\r\t"), "\"\\b\\f\\n\\r\\t\"");
355        assert_eq!(json("\u{0}\u{1}\u{1f}"), "\"\\u0000\\u0001\\u001f\"");
356    }
357
358    #[test]
359    fn every_other_character_stands_as_itself() {
360        let probe = "Café — naïve ½ α 😅 '";
361        assert_eq!(json(probe), format!("\"{probe}\""));
362        // `U+007F` is not a control character JSON asks to be escaped.
363        assert_eq!(json("\u{7f}"), "\"\u{7f}\"");
364    }
365
366    #[test]
367    fn a_json_string_appends_to_what_the_buffer_already_holds() {
368        let mut out = String::from("[");
369        json_string_into(&mut out, "a");
370        assert_eq!(out, "[\"a\"");
371    }
372}