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
use std::{char, str};
use std::num::ParseIntError;
use synom::IResult;

pub fn cooked_string(input: &str) -> IResult<&str, String> {
    let mut s = String::new();
    let mut chars = input.char_indices().peekable();
    while let Some((byte_offset, ch)) = chars.next() {
        match ch {
            '"' => {
                return IResult::Done(&input[byte_offset..], s);
            }
            '\r' => {
                if let Some((_, '\n')) = chars.next() {
                    s.push('\n');
                } else {
                    break;
                }
            }
            '\\' => {
                match chars.next() {
                    Some((_, 'x')) => {
                        match backslash_x_char(&mut chars) {
                            Some(ch) => s.push(ch),
                            None => break,
                        }
                    }
                    Some((_, 'n')) => s.push('\n'),
                    Some((_, 'r')) => s.push('\r'),
                    Some((_, 't')) => s.push('\t'),
                    Some((_, '\\')) => s.push('\\'),
                    Some((_, '0')) => s.push('\0'),
                    Some((_, 'u')) => {
                        match backslash_u(&mut chars) {
                            Some(ch) => s.push(ch),
                            None => break,
                        }
                    }
                    Some((_, '\'')) => s.push('\''),
                    Some((_, '"')) => s.push('"'),
                    Some((_, '\n')) | Some((_, '\r')) => {
                        while let Some(&(_, ch)) = chars.peek() {
                            if ch.is_whitespace() {
                                chars.next();
                            } else {
                                break;
                            }
                        }
                    }
                    _ => break,
                }
            }
            ch => {
                s.push(ch);
            }
        }
    }
    IResult::Error
}

pub fn cooked_byte_string(mut input: &str) -> IResult<&str, Vec<u8>> {
    let mut vec = Vec::new();
    let mut bytes = input.bytes().enumerate();
    'outer: while let Some((offset, b)) = bytes.next() {
        match b {
            b'"' => {
                return IResult::Done(&input[offset..], vec);
            }
            b'\r' => {
                if let Some((_, b'\n')) = bytes.next() {
                    vec.push(b'\n');
                } else {
                    break;
                }
            }
            b'\\' => {
                match bytes.next() {
                    Some((_, b'x')) => {
                        match backslash_x_byte(&mut bytes) {
                            Some(b) => vec.push(b),
                            None => break,
                        }
                    }
                    Some((_, b'n')) => vec.push(b'\n'),
                    Some((_, b'r')) => vec.push(b'\r'),
                    Some((_, b't')) => vec.push(b'\t'),
                    Some((_, b'\\')) => vec.push(b'\\'),
                    Some((_, b'0')) => vec.push(b'\0'),
                    Some((_, b'\'')) => vec.push(b'\''),
                    Some((_, b'"')) => vec.push(b'"'),
                    Some((newline, b'\n')) |
                    Some((newline, b'\r')) => {
                        let rest = &input[newline + 1..];
                        for (offset, ch) in rest.char_indices() {
                            if !ch.is_whitespace() {
                                input = &rest[offset..];
                                bytes = input.bytes().enumerate();
                                continue 'outer;
                            }
                        }
                        break;
                    }
                    _ => break,
                }
            }
            b if b < 0x80 => {
                vec.push(b);
            }
            _ => break,
        }
    }
    IResult::Error
}

pub fn cooked_char(input: &str) -> IResult<&str, char> {
    let mut chars = input.char_indices();
    let ch = match chars.next().map(|(_, ch)| ch) {
        Some('\\') => {
            match chars.next().map(|(_, ch)| ch) {
                Some('x') => backslash_x_char(&mut chars),
                Some('n') => Some('\n'),
                Some('r') => Some('\r'),
                Some('t') => Some('\t'),
                Some('\\') => Some('\\'),
                Some('0') => Some('\0'),
                Some('u') => backslash_u(&mut chars),
                Some('\'') => Some('\''),
                Some('"') => Some('"'),
                _ => None,
            }
        }
        ch => ch,
    };
    match ch {
        Some(ch) => IResult::Done(chars.as_str(), ch),
        None => IResult::Error,
    }
}

pub fn cooked_byte(input: &str) -> IResult<&str, u8> {
    let mut bytes = input.bytes().enumerate();
    let b = match bytes.next().map(|(_, b)| b) {
        Some(b'\\') => {
            match bytes.next().map(|(_, b)| b) {
                Some(b'x') => backslash_x_byte(&mut bytes),
                Some(b'n') => Some(b'\n'),
                Some(b'r') => Some(b'\r'),
                Some(b't') => Some(b'\t'),
                Some(b'\\') => Some(b'\\'),
                Some(b'0') => Some(b'\0'),
                Some(b'\'') => Some(b'\''),
                Some(b'"') => Some(b'"'),
                _ => None,
            }
        }
        b => b,
    };
    match b {
        Some(b) => {
            match bytes.next() {
                Some((offset, _)) => IResult::Done(&input[offset..], b),
                None => IResult::Done("", b),
            }
        }
        None => IResult::Error,
    }
}

pub fn raw_string(input: &str) -> IResult<&str, (String, usize)> {
    let mut chars = input.char_indices();
    let mut n = 0;
    while let Some((byte_offset, ch)) = chars.next() {
        match ch {
            '"' => {
                n = byte_offset;
                break;
            }
            '#' => {}
            _ => return IResult::Error,
        }
    }
    let mut s = String::new();
    for (byte_offset, ch) in chars {
        match ch {
            '"' if input[byte_offset + 1..].starts_with(&input[..n]) => {
                let rest = &input[byte_offset + 1 + n..];
                return IResult::Done(rest, (s, n));
            }
            '\r' => {}
            _ => s.push(ch),
        }
    }
    IResult::Error
}

macro_rules! next_ch {
    ($chars:ident @ $pat:pat $(| $rest:pat)*) => {
        match $chars.next() {
            Some((_, ch)) => match ch {
                $pat $(| $rest)*  => ch,
                _ => return None,
            },
            None => return None,
        }
    };
}

trait FromStrRadix: Sized {
    fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>;
}

impl FromStrRadix for u8 {
    fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
        u8::from_str_radix(src, radix)
    }
}

impl FromStrRadix for u32 {
    fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
        u32::from_str_radix(src, radix)
    }
}

macro_rules! from_hex {
    ($($ch:ident)+) => {{
        let hex_bytes = &[$($ch as u8),*];
        let hex_str = str::from_utf8(hex_bytes).unwrap();
        FromStrRadix::from_str_radix(hex_str, 16).unwrap()
    }};
}

#[cfg_attr(feature = "cargo-clippy", allow(diverging_sub_expression))]
fn backslash_x_char<I>(chars: &mut I) -> Option<char>
    where I: Iterator<Item = (usize, char)>
{
    let a = next_ch!(chars @ '0'...'7');
    let b = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
    char::from_u32(from_hex!(a b))
}

#[cfg_attr(feature = "cargo-clippy", allow(diverging_sub_expression))]
fn backslash_x_byte<I>(chars: &mut I) -> Option<u8>
    where I: Iterator<Item = (usize, u8)>
{
    let a = next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
    let b = next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F');
    Some(from_hex!(a b))
}

#[cfg_attr(feature = "cargo-clippy", allow(diverging_sub_expression, many_single_char_names))]
fn backslash_u<I>(chars: &mut I) -> Option<char>
    where I: Iterator<Item = (usize, char)>
{
    next_ch!(chars @ '{');
    let a = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F');
    let b = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
    if b == '}' {
        return char::from_u32(from_hex!(a));
    }
    let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
    if c == '}' {
        return char::from_u32(from_hex!(a b));
    }
    let d = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
    if d == '}' {
        return char::from_u32(from_hex!(a b c));
    }
    let e = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
    if e == '}' {
        return char::from_u32(from_hex!(a b c d));
    }
    let f = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}');
    if f == '}' {
        return char::from_u32(from_hex!(a b c d e));
    }
    next_ch!(chars @ '}');
    char::from_u32(from_hex!(a b c d e f))
}

#[test]
fn test_cooked_string() {
    let input = "\\x62 \\\n \\u{7} \\u{64} \\u{bf5} \\u{12ba} \\u{1F395} \\u{102345}\"";
    let expected = "\x62 \u{7} \u{64} \u{bf5} \u{12ba} \u{1F395} \u{102345}";
    assert_eq!(cooked_string(input),
               IResult::Done("\"", expected.to_string()));
}

#[test]
fn test_cooked_byte_string() {
    let input = "\\x62 \\\n \\xEF\"";
    let expected = b"\x62 \xEF";
    assert_eq!(cooked_byte_string(input),
               IResult::Done("\"", expected.to_vec()));
}