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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#![deny(missing_docs)]

//! A simple library to read tokens using look ahead

extern crate range;

use std::fmt::{ Display, Formatter };
use std::fmt::Error as FormatError;
use range::Range;

/// Reads an expected token, return `None` if it does not match.
pub fn token(token: &str, chars: &[char], offset: usize) -> Option<Range> {
    if chars.len() < token.len() { return None; }
    for (i, c) in token.chars().enumerate() {
        if c != chars[i] { return None; }
    }
    return Some(Range::new(offset, token.len()))
}

/// Reads a token until any character in string or whitespace.
/// Returns `(range, None)` if stopping at whitespace or end of characters.
/// Returns `(range, Some(x))` if stopping at a character.
pub fn until_any_or_whitespace(
    any: &str,
    chars: &[char],
    offset: usize
) -> (Range, Option<usize>) {
    for (i, &c) in chars.iter().enumerate() {
        if c.is_whitespace() {
            return (Range::new(offset, i), None)
        }
        for (j, b) in any.chars().enumerate() {
            if c == b {
                return (Range::new(offset, i), Some(j))
            }
        }
    }
    (Range::new(offset, chars.len()), None)
}

/// Reads token until any character in string.
/// Returns `(range, None)` if stopping at end of characters.
/// Returns `(range, Some(x))` if stopping at a character.
pub fn until_any(
    any: &str,
    chars: &[char],
    offset: usize
) -> (Range, Option<usize>) {
    for (i, &c) in chars.iter().enumerate() {
        for (j, b) in any.chars().enumerate() {
            if c == b {
                return (Range::new(offset, i), Some(j))
            }
        }
    }
    (Range::new(offset, chars.len()), None)
}

/// Reads whitespace.
pub fn whitespace(chars: &[char], offset: usize) -> Range {
    for (i, &c) in chars.iter().enumerate() {
        if !c.is_whitespace() { return Range::new(offset, i) }
    }
    Range::new(offset, chars.len())
}

/// Reads string with character escapes.
pub fn string(chars: &[char], offset: usize) -> Option<Range> {
    if chars.len() == 0 || chars[0] != '"' { return None; }
    let mut escape = false;
    for i in 1..chars.len() - 1 {
        if chars[i] == '\\' { escape = true; continue; }
        if !escape && chars[i] == '"' { return Some(Range::new(offset, i + 1)) }
        if escape { escape = false; }
    }
    if !escape && chars[chars.len() - 1] == '"' {
        return Some(Range::new(offset, chars.len()))
    } else {
        return None
    }
}

/// Contains errors when parsing a string.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ParseStringError {
    /// Expected four hexadecimals, found less characters
    ExpectedFourHexadecimals(Range),
    /// Expected character `0-9a-fA-F`
    ExpectedHexadecimal(Range),
    /// Found four hexadecimals, but not an invalid unicode character
    ExpectedValidUnicode(Range),
    /// A character escape `\x` is invalid
    ExpectedValidEscapeCharacter(Range),
}

impl ParseStringError {
    /// Gets the range of the error.
    pub fn range(&self) -> Range {
        match self {
            &ParseStringError::ExpectedFourHexadecimals(r) => r,
            &ParseStringError::ExpectedHexadecimal(r) => r,
            &ParseStringError::ExpectedValidUnicode(r) => r,
            &ParseStringError::ExpectedValidEscapeCharacter(r) => r,
        }
    }
}

impl Display for ParseStringError {
    fn fmt(&self, fmt: &mut Formatter) -> Result<(), FormatError> {
        match self {
            &ParseStringError::ExpectedFourHexadecimals(_) =>
                fmt.write_str("Expected four hexadecimals xxxx 0-9A-F"),
            &ParseStringError::ExpectedHexadecimal(_) =>
                fmt.write_str("Expected hexadecimal 0-9A-F"),
            &ParseStringError::ExpectedValidUnicode(_) =>
                fmt.write_str("Expected valid unicode"),
            &ParseStringError::ExpectedValidEscapeCharacter(_) =>
                fmt.write_str("Expected valid escape character '\"\\/bfnrtu'"),
        }
    }
}

/// Parses four unicode characters in hexadecimal format.
pub fn parse_unicode(
    chars: &[char],
    offset: usize
) -> Result<char, ParseStringError> {
    use std::char;

    if chars.len() < 4 {
        return Err(ParseStringError::ExpectedFourHexadecimals(
            Range::new(offset, chars.len())
        ));
    }

    let mut u: [u32; 4] = [0; 4];
    for (i, c) in u.iter_mut().enumerate() {
        match chars[i].to_digit(16) {
            Some(x) => *c = x as u32,
            None => {
                return Err(ParseStringError::ExpectedHexadecimal(
                    Range::new(offset + i, 1)
                ))
            }
        }
    }
    let code = (u[0] << 12) | (u[1] << 8) | (u[2] << 4) | u[3];
    match char::from_u32(code) {
        Some(x) => Ok(x),
        None => Err(ParseStringError::ExpectedValidUnicode(
            Range::new(offset, 4)
        ))
    }
}

/// Parses string into a real string according to the JSON standard.
///
/// Assumes the string starts and ends with double-quotes.
/// `offset` is the location at the start of the slice.
/// `next_offset` is the location where the string ends.
pub fn parse_string(
    chars: &[char],
    offset: usize,
    next_offset: usize,
) -> Result<String, ParseStringError> {
    let mut escape = false;
    let length = next_offset - offset - 2;
    let mut txt = String::with_capacity(length);
    for (i, &c) in chars[1..length + 1].iter().enumerate() {
        if c == '\\' { escape = true; continue; }
        if escape {
            escape = false;
            txt.push(match c {
                '\"' => '"',
                '\\' => '\\',
                '/' => '/',
                'b' => '\u{0008}',
                'f' => '\u{000c}',
                'n' => '\n',
                'r' => '\r',
                't' => '\t',
                'u' => {
                    let offset = offset + 1 + i;
                    match parse_unicode(&chars[offset..], offset) {
                        Ok(x) => x,
                        Err(err) => return Err(err)
                    }
                }
                _ => {
                    return Err(ParseStringError::ExpectedValidEscapeCharacter(
                        Range::new(offset + i + 1, 1)
                    ));
                }
            })
        } else {
            txt.push(c)
        }
    }
    Ok(txt)
}

/// Reads number.
pub fn number(chars: &[char], offset: usize) -> Option<Range> {
    let mut has_sign = false;
    let mut has_decimal_separator = false;
    let mut has_scientific = false;
    let mut has_exponent_sign = false;
    for (i, &c) in chars.iter().enumerate() {
        if !has_sign {
            has_sign = true;
            if c == '+' || c == '-' { continue; }
        }
        if c.is_digit(10) { continue; }
        if !has_decimal_separator && c == '.' {
            has_decimal_separator = true;
            continue;
        }
        if !has_scientific && (c == 'e' || c == 'E') {
            has_scientific = true;
            continue;
        }
        if has_scientific && !has_exponent_sign {
            has_exponent_sign = true;
            if c == '+' || c == '-' { continue; }
        }
        if i > 0 { return Some(Range::new(offset, i)) }
        else { return None }
    }
    if chars.len() > 0 { return Some(Range::new(offset, chars.len())) }
    else { return None }
}

/// Reads a number that can have underscore as visual separator.
pub fn underscore_number(chars: &[char], offset: usize) -> Option<Range> {
    let mut has_sign = false;
    let mut has_decimal_separator = false;
    let mut has_scientific = false;
    let mut has_exponent_sign = false;
    let mut has_digit = false;
    for (i, &c) in chars.iter().enumerate() {
        if !has_sign {
            has_sign = true;
            if c == '+' || c == '-' { continue; }
        }
        if c.is_digit(10) { has_digit = true; continue; }
        if has_digit && c == '_' { continue; }
        if !has_decimal_separator && c == '.' {
            has_decimal_separator = true;
            continue;
        }
        if !has_scientific && (c == 'e' || c == 'E') {
            has_scientific = true;
            continue;
        }
        if has_scientific && !has_exponent_sign {
            has_exponent_sign = true;
            if c == '+' || c == '-' { continue; }
        }
        if i > 0 { return Some(Range::new(offset, i)) }
        else { return None }
    }
    if chars.len() > 0 { return Some(Range::new(offset, chars.len())) }
    else { return None }
}


#[cfg(test)]
mod tests {
    use super::*;
    use range::Range;

    #[test]
    pub fn test_token() {
        let text = "one day, a nice day".chars().collect::<Vec<char>>();
        let res = token("one", &text, 0);
        assert_eq!(res, Some(Range::new(0, 3)));
        let res = token("two", &text, 0);
        assert_eq!(res, None);
    }

    #[test]
    pub fn test_until_any_or_whitespace() {
        let text = "one day, a nice day".chars().collect::<Vec<char>>();
        let res = until_any_or_whitespace(",", &text, 0);
        assert_eq!(res, (Range::new(0, 3), None));
        let res = until_any_or_whitespace(",", &text[3..], 3);
        assert_eq!(res, (Range::empty(3), None));
        let res = until_any_or_whitespace(",", &text[4..], 4);
        assert_eq!(res, (Range::new(4, 3), Some(0)));
    }

    #[test]
    pub fn test_until_any() {
        let text = "one day, a nice day".chars().collect::<Vec<char>>();
        let res = until_any(",", &text, 0);
        assert_eq!(res, (Range::new(0, 7), Some(0)));
        let res = until_any(",", &text[3..], 3);
        assert_eq!(res, (Range::new(3, 4), Some(0)));
        let res = until_any(",", &text[8..], 8);
        assert_eq!(res, (Range::new(8, 11), None));
    }

    #[test]
    pub fn test_whitespace() {
        let text = "   123".chars().collect::<Vec<char>>();
        let res = whitespace(&text, 0);
        assert_eq!(res, Range::new(0, 3));
    }

    #[test]
    pub fn test_string() {
        let text = "\"hello\"".chars().collect::<Vec<char>>();
        let res = string(&text, 0);
        assert_eq!(res, Some(Range::new(0, 7)));
        let txt = parse_string(&text, 0, res.unwrap().next_offset()).ok().unwrap();
        assert_eq!(txt, "hello");

        let text = "\"he\\\"llo\"".chars().collect::<Vec<char>>();
        let res = string(&text, 0);
        assert_eq!(res, Some(Range::new(0, 9)));
        let txt = parse_string(&text, 0, res.unwrap().next_offset());
        let txt = txt.ok().unwrap();
        assert_eq!(txt, "he\"llo");

        let text = "\"he\"llo\"".chars().collect::<Vec<char>>();
        let res = string(&text, 0);
        assert_eq!(res, Some(Range::new(0, 4)));
        let txt = parse_string(&text, 0, res.unwrap().next_offset());
        let txt = txt.ok().unwrap();
        assert_eq!(txt, "he");

        let text = "\"hello\\\"".chars().collect::<Vec<char>>();
        let res = string(&text, 0);
        assert_eq!(res, None);
    }

    #[test]
    pub fn test_number() {
        let _: f64 = "20".parse().unwrap();
        let _: f64 = "-20".parse().unwrap();
        let _: f64 = "2e2".parse().unwrap();
        let _: f64 = "2.5".parse().unwrap();
        let _: f64 = "2.5e2".parse().unwrap();
        let _: f64 = "2.5E2".parse().unwrap();
        let _: f64 = "2.5E-2".parse().unwrap();

        let text = "20".chars().collect::<Vec<char>>();
        let res = number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 2)));

        let text = "-20".chars().collect::<Vec<char>>();
        let res = number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 3)));

        let text = "2e2".chars().collect::<Vec<char>>();
        let res = number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 3)));

        let text = "2.5".chars().collect::<Vec<char>>();
        let res = number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 3)));

        let text = "2.5e2".chars().collect::<Vec<char>>();
        let res = number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 5)));

        let text = "2.5E2".chars().collect::<Vec<char>>();
        let res = number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 5)));

        let text = "2.5E-2".chars().collect::<Vec<char>>();
        let res = number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 6)));
    }

    #[test]
    pub fn test_underscore_number() {
        let _: f64 = "20".parse().unwrap();
        let _: f64 = "-20".parse().unwrap();
        let _: f64 = "2e2".parse().unwrap();
        let _: f64 = "2.5".parse().unwrap();
        let _: f64 = "2.5e2".parse().unwrap();
        let _: f64 = "2.5E2".parse().unwrap();
        let _: f64 = "2.5E-2".parse().unwrap();

        let text = "20".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 2)));

        let text = "-20".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 3)));

        let text = "2e2".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 3)));

        let text = "2.5".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 3)));

        let text = "2.5e2".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 5)));

        let text = "2.5E2".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 5)));

        let text = "2.5E-2".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 6)));

        let text = "_2.5E-2".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, None);

        let text = "2_.5E-2".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 7)));

        let text = "2_000_000.5E-2".chars().collect::<Vec<char>>();
        let res = underscore_number(&text, 0);
        assert_eq!(res, Some(Range::new(0, 14)));
    }
}