summaryrefslogtreecommitdiff
path: root/src/parse/postprocess.rs
blob: ad4a9057dfa9fdfe786fcb0f1fae7acab90d1587 (plain) (blame)
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
//! Post-processing of strings and raw blocks.

use super::is_newline_char;
use crate::syntax::{Ident, Raw};

/// Resolves all escape sequences in a string.
pub fn unescape_string(string: &str) -> String {
    let mut iter = string.chars().peekable();
    let mut out = String::with_capacity(string.len());

    while let Some(c) = iter.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }

        match iter.next() {
            Some('\\') => out.push('\\'),
            Some('"') => out.push('"'),

            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some('u') if iter.peek() == Some(&'{') => {
                iter.next();

                // TODO: Feedback if closing brace is missing.
                let mut sequence = String::new();
                let terminated = loop {
                    match iter.peek() {
                        Some('}') => {
                            iter.next();
                            break true;
                        }
                        Some(&c) if c.is_ascii_hexdigit() => {
                            iter.next();
                            sequence.push(c);
                        }
                        _ => break false,
                    }
                };

                if let Some(c) = hex_to_char(&sequence) {
                    out.push(c);
                } else {
                    // TODO: Feedback that escape sequence is wrong.
                    out.push_str("\\u{");
                    out.push_str(&sequence);
                    if terminated {
                        out.push('}');
                    }
                }
            }

            other => {
                out.push('\\');
                out.extend(other);
            }
        }
    }

    out
}

/// Resolves the language tag and trims the raw text.
///
/// Returns:
/// - The language tag
/// - The raw lines
/// - Whether at least one newline was present in the untrimmed text.
pub fn process_raw(raw: &str) -> Raw {
    let (lang, inner) = split_after_lang_tag(raw);
    let (lines, had_newline) = trim_and_split_raw(inner);
    Raw { lang, lines, inline: !had_newline }
}

/// Parse the lang tag and return it alongside the remaining inner raw text.
fn split_after_lang_tag(raw: &str) -> (Option<Ident>, &str) {
    let mut lang = String::new();

    let mut inner = raw;
    let mut iter = raw.chars();

    while let Some(c) = iter.next() {
        if c == '`' || c.is_whitespace() || is_newline_char(c) {
            break;
        }

        inner = iter.as_str();
        lang.push(c);
    }

    (Ident::new(lang), inner)
}

/// Trims raw text and splits it into lines.
///
/// Returns whether at least one newline was contained in `raw`.
fn trim_and_split_raw(raw: &str) -> (Vec<String>, bool) {
    // Trims one whitespace at end and start.
    let raw = raw.strip_prefix(' ').unwrap_or(raw);
    let raw = raw.strip_suffix(' ').unwrap_or(raw);

    let mut lines = split_lines(raw);
    let had_newline = lines.len() > 1;
    let is_whitespace = |line: &String| line.chars().all(char::is_whitespace);

    // Trims a sequence of whitespace followed by a newline at the start.
    if lines.first().map(is_whitespace).unwrap_or(false) {
        lines.remove(0);
    }

    // Trims a newline followed by a sequence of whitespace at the end.
    if lines.last().map(is_whitespace).unwrap_or(false) {
        lines.pop();
    }

    (lines, had_newline)
}

/// Splits a string into a vector of lines (respecting Unicode & Windows line breaks).
pub fn split_lines(text: &str) -> Vec<String> {
    let mut iter = text.chars().peekable();
    let mut line = String::new();
    let mut lines = Vec::new();

    while let Some(c) = iter.next() {
        if is_newline_char(c) {
            if c == '\r' && iter.peek() == Some(&'\n') {
                iter.next();
            }

            lines.push(std::mem::take(&mut line));
        } else {
            line.push(c);
        }
    }

    lines.push(line);
    lines
}

/// Converts a hexademical sequence (without braces or "\u") into a character.
pub fn hex_to_char(sequence: &str) -> Option<char> {
    u32::from_str_radix(sequence, 16).ok().and_then(std::char::from_u32)
}

#[cfg(test)]
#[rustfmt::skip]
mod tests {
    use super::*;

    #[test]
    fn test_unescape_strings() {
        fn test(string: &str, expected: &str) {
            assert_eq!(unescape_string(string), expected.to_string());
        }

        test(r#"hello world"#,  "hello world");
        test(r#"hello\nworld"#, "hello\nworld");
        test(r#"a\"bc"#,        "a\"bc");
        test(r#"a\u{2603}bc"#,  "a☃bc");
        test(r#"a\u{26c3bg"#,   "a𦰻g");
        test(r#"av\u{6797"#,    "av林");
        test(r#"a\\"#,          "a\\");
        test(r#"a\\\nbc"#,      "a\\\nbc");
        test(r#"a\tbc"#,        "a\tbc");
        test(r"🌎",             "🌎");
        test(r"🌎\",            r"🌎\");
        test(r"\🌎",            r"\🌎");
    }

    #[test]
    fn test_split_after_lang_tag() {
        fn test(raw: &str, lang: Option<&str>, inner: &str) {
            let (found_lang, found_inner) = split_after_lang_tag(raw);
            assert_eq!(found_lang.as_ref().map(|id| id.as_str()), lang);
            assert_eq!(found_inner, inner);
        }

        test("typst it!",   Some("typst"), " it!");
        test("typst\n it!", Some("typst"), "\n it!");
        test("typst\n it!", Some("typst"), "\n it!");
        test("abc`",        Some("abc"),   "`");
        test(" hi",         None,          " hi");
        test("`",           None,          "`");
    }

    #[test]
    fn test_trim_raw() {
        fn test(raw: &str, expected: Vec<&str>) {
            assert_eq!(trim_and_split_raw(raw).0, expected);
        }

        test(" hi",          vec!["hi"]);
        test("  hi",         vec![" hi"]);
        test("\nhi",         vec!["hi"]);
        test("    \n hi",    vec![" hi"]);
        test("hi ",          vec!["hi"]);
        test("hi  ",         vec!["hi "]);
        test("hi\n",         vec!["hi"]);
        test("hi \n   ",     vec!["hi "]);
        test("  \n hi \n  ", vec![" hi "]);
    }

    #[test]
    fn test_split_lines() {
        fn test(raw: &str, expected: Vec<&str>) {
            assert_eq!(split_lines(raw), expected);
        }

        test("raw\ntext",  vec!["raw", "text"]);
        test("a\r\nb",     vec!["a", "b"]);
        test("a\n\nb",     vec!["a", "", "b"]);
        test("a\r\x0Bb",   vec!["a", "", "b"]);
        test("a\r\n\r\nb", vec!["a", "", "b"]);
    }
}