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
use std::{
    borrow::Cow,
    fmt::Write,
    iter::Peekable,
    str::{CharIndices, MatchIndices},
};

use arrayvec::ArrayVec;

use lang_util::SmolStr;

#[derive(Debug, Clone, Copy)]
pub struct Unescaped<'s> {
    src: &'s str,
}

impl<'s> Unescaped<'s> {
    pub fn new(src: &'s str) -> Self {
        Self { src }
    }

    fn backslashes(&self) -> MatchIndices<'s, char> {
        self.src.match_indices('\\')
    }

    pub fn chars(&self) -> UnescapeIter<'s> {
        UnescapeIter {
            chars: self.src.char_indices(),
            backslashes: self.backslashes().peekable(),
        }
    }

    pub fn to_string(self) -> Cow<'s, str> {
        if self.backslashes().next().is_none() {
            Cow::Borrowed(self.src)
        } else {
            Cow::Owned(self.chars().collect::<String>())
        }
    }
}

impl<'s> From<&'s str> for Unescaped<'s> {
    fn from(value: &'s str) -> Self {
        Self::new(value)
    }
}

impl<'s> From<Unescaped<'s>> for SmolStr {
    fn from(src: Unescaped<'s>) -> Self {
        src.chars().collect()
    }
}

impl<'s> PartialEq<&str> for Unescaped<'s> {
    fn eq(&self, other: &&str) -> bool {
        self.chars().eq(other.chars())
    }
}

impl<'s> std::fmt::Display for Unescaped<'s> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for ch in self.chars() {
            f.write_char(ch)?;
        }

        Ok(())
    }
}

pub struct UnescapeIter<'s> {
    chars: CharIndices<'s>,
    backslashes: Peekable<MatchIndices<'s, char>>,
}

impl<'s> Iterator for UnescapeIter<'s> {
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some((cont, _)) = self.backslashes.peek() {
                // There is a continuation coming

                // Create a peekable chars iterator
                let mut chars_copy = self.chars.clone().peekable();

                if let Some((i, _)) = chars_copy.peek() {
                    if *i == *cont {
                        // Consume this backslash match
                        self.backslashes.next();

                        // We are at the start of a potential continuation
                        // Skip 1 char (the backslash character)
                        // Collect 2 chars (worst case for a Windows CRLF)
                        let chars: ArrayVec<_, 2> =
                            chars_copy.map(|(_, ch)| ch).skip(1).take(2).collect();

                        // Consume the backslash char
                        self.chars.next();

                        if chars.starts_with(&['\r', '\n']) || chars.starts_with(&['\n', '\r']) {
                            // CRLF, advance thrice, loop again
                            self.chars.next(); // \r
                            self.chars.next(); // \n
                        } else if chars.starts_with(&['\n']) || chars.starts_with(&['\r']) {
                            // LF, advance twice, loop again
                            self.chars.next(); // \n
                        } else {
                            // Stray backslash, just return as-is
                            return Some('\\');
                        }
                    } else {
                        // We haven't reached the continuation yet
                        return self.chars.next().map(|(_, ch)| ch);
                    }
                } else {
                    // Nothing left
                    return None;
                }
            } else {
                // No continuation, i.e. happy path
                return self.chars.next().map(|(_, ch)| ch);
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenText<'s>(TokenTextRepr<'s>);

#[derive(Debug, Clone, PartialEq, Eq)]
enum TokenTextRepr<'s> {
    Raw(&'s str),
    Unescaped(&'s str),
    JustUnescaped(Cow<'s, str>),
}

impl<'s> TokenText<'s> {
    pub fn push_str(&mut self, rest: TokenText<'_>) {
        let mut self_text = self.to_owned_string();
        self_text.push_str(rest.to_string().as_ref());
        self.0 = TokenTextRepr::JustUnescaped(self_text.into());
    }

    pub fn raw(s: &'s str) -> Self {
        Self(TokenTextRepr::Raw(s))
    }

    pub fn to_owned(&self) -> TokenText<'static> {
        TokenText(TokenTextRepr::JustUnescaped(Cow::Owned(
            self.to_owned_string(),
        )))
    }

    fn to_owned_string(&self) -> String {
        match &self.0 {
            TokenTextRepr::Raw(s) => Unescaped::from(*s).chars().collect(),
            TokenTextRepr::Unescaped(s) => s.to_owned().into(),
            TokenTextRepr::JustUnescaped(s) => (**s).to_owned(),
        }
    }

    pub fn to_string(&self) -> Cow<'s, str> {
        match &self.0 {
            TokenTextRepr::Raw(s) => Cow::Owned(Unescaped::from(*s).chars().collect()),
            TokenTextRepr::Unescaped(s) => (*s).into(),
            TokenTextRepr::JustUnescaped(s) => s.clone(),
        }
    }

    pub fn into_unescaped(self) -> Self {
        Self(match self.0 {
            TokenTextRepr::Raw(s) => {
                TokenTextRepr::JustUnescaped(Cow::Owned(Unescaped::from(s).chars().collect()))
            }
            TokenTextRepr::Unescaped(s) => TokenTextRepr::JustUnescaped(s.into()),
            TokenTextRepr::JustUnescaped(s) => TokenTextRepr::JustUnescaped(s),
        })
    }

    pub fn try_as_str(&'s self) -> Option<&'s str> {
        match &self.0 {
            TokenTextRepr::Raw(_) => None,
            TokenTextRepr::Unescaped(s) => Some(*s),
            TokenTextRepr::JustUnescaped(s) => Some((*s).as_ref()),
        }
    }

    pub unsafe fn unescaped(s: &'s str) -> Self {
        Self(TokenTextRepr::Unescaped(s))
    }
}

impl<'s> std::fmt::Display for TokenText<'s> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            TokenTextRepr::Raw(s) => write!(f, "{}", Unescaped::from(*s)),
            TokenTextRepr::Unescaped(s) => write!(f, "{}", s),
            TokenTextRepr::JustUnescaped(s) => write!(f, "{}", s),
        }
    }
}

impl<'s> From<TokenText<'s>> for SmolStr {
    fn from(value: TokenText<'s>) -> Self {
        match value.0 {
            TokenTextRepr::Raw(raw) => Unescaped::from(raw).into(),
            TokenTextRepr::Unescaped(unescaped) => unescaped.into(),
            TokenTextRepr::JustUnescaped(unescaped) => unescaped.into(),
        }
    }
}