Unverified Commit 2cef1e6b authored by John DiSanti's avatar John DiSanti Committed by GitHub
Browse files

Implement JSON token stream deserializer (#454)

* Implement JSON token stream deserializer

* Stop allocating string values and fix surrogate pair unescaping

* Add documentation on how to test against JSONTestSuite
parent 6a92568b
Loading
Loading
Loading
Loading
+115 −0
Original line number Diff line number Diff line
How to run JSONTestSuite against smithy-json deserialize
========================================================

When making changes to the `deserialize` module, it is a good idea
to run the changes against the [JSONTestSuite](https://github.com/nst/JSONTestSuite)
and manually examine the test results.

### How to setup the JSONTestSuite

1. Clone the [JSONTestSuite](https://github.com/nst/JSONTestSuite) repository.
2. In `JSONTestSuite/parsers`, create a new Cargo bin project named `test_json-smithy_json`.
3. Add the following dependencies to the `Cargo.toml` (be sure to replace `<local-path-to-smithy-rs>`:

```
smithy-json = { path = "<local-path-to-smithy-rs>/rust-runtime/smithy-json" }
```

4. Replace the code in `main.rs` with:

```rust
use std::fs::File;
use std::io::Read;
use std::env;

use smithy_json::deserialize::{json_token_iter, Token, Error};

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() != 2 {
        println!("Usage: {} file.json", args[0]);
        std::process::exit(1);
    }

    let ref path = args[1];
    let mut s = String::new();
    let mut f = File::open(path).expect("Unable to open file");
    match f.read_to_string(&mut s) {
        Err(_) => std::process::exit(1),
        Ok(_) => println!("{}", s),
    }

    let result: Result<Vec<Token>, Error> = json_token_iter(s.as_bytes()).collect();
    match result {
        Err(_) => std::process::exit(1),
        Ok(value) => if value.is_empty() {
            std::process::exit(1)
        } else {
            // The test suite includes incomplete objects and arrays (i.e., "[null,").
            // These are completely valid for this parser, so we'll just pretend to have
            // failed to parse these to satisfy the test suite.
            if value.first() == Some(&Token::StartObject) && value.last() != Some(&Token::EndObject) {
                std::process::exit(1)
            }
            if value.first() == Some(&Token::StartArray) && value.last() != Some(&Token::EndArray) {
                std::process::exit(1)
            }
            // Unescape all strings and fail if any of them failed to unescape.
            for token in value {
                if let Token::ValueString(escaped) = token {
                    if escaped.into_unescaped().is_err() {
                        std::process::exit(1)
                    }
                }
            }
            std::process::exit(0)
        }
    }
}
```

5. Compile this program with `cargo build --release`.
6. Modify `JSONTestSuite/run_tests.py` so that the `programs` dictionary only contains this one entry:

```
programs = {
   "Rust smithy-json":
       {
           "url":"dontcare",
           "commands":[os.path.join(PARSERS_DIR, "test_json-smithy_json/target/release/sj")]
       }
}
```

7. Run `run_tests.py` and examine the output with a web browser by opening `JSONTestSuite/results/parsing.html`.

### Examining the results

When looking at `JSONTestSuite/results/parsing.html`, there is a matrix of test cases against their
results with a legend at the top.

Any test result marked with blue or light blue is for a test case where correct behavior isn't specified,
so use your best judgement to decide if it should have succeeded or failed.

The other colors are bad and should be carefully examined. At time of writing, the following test cases
succeed when they should fail, and we intentionally left it that way since we're not currently concerned
about being more lenient in the number parsing:

```
n_number_-01.json                           [-01]
n_number_-2..json                           [-2.]
n_number_0.e1.json                          [0.e1]
n_number_2.e+3.json                         [2.e+3]
n_number_2.e-3.json                         [2.e-3]
n_number_2.e3.json                          [2.e3]
n_number_neg_int_starting_with_zero.json    [-012]
n_number_neg_real_without_int_part.json     [-.123]
n_number_real_without_fractional_part.json  [1.]
n_number_with_leading_zero.json             [012]
```

This test case succeeds with our parser and that's OK since we're
a token streaming parser (multiple values are allowed):
```
n_structure_double_array.json               [][]
```
+865 −0

File added.

Preview size limit exceeded, changes collapsed.

+213 −0
Original line number Diff line number Diff line
@@ -4,6 +4,41 @@
 */

use std::borrow::Cow;
use std::fmt;

#[derive(Debug, PartialEq, Eq)]
pub enum Error {
    ExpectedSurrogatePair(String),
    InvalidEscapeCharacter(char),
    InvalidSurrogatePair(u16, u16),
    InvalidUnicodeEscape(String),
    InvalidUtf8,
    UnexpectedEndOfString,
}

impl std::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use Error::*;
        match self {
            ExpectedSurrogatePair(low) => {
                write!(
                    f,
                    "expected a UTF-16 surrogate pair, but got {} as the low word",
                    low
                )
            }
            InvalidEscapeCharacter(chr) => write!(f, "invalid JSON escape: \\{}", chr),
            InvalidSurrogatePair(high, low) => {
                write!(f, "invalid surrogate pair: \\u{:04X}\\u{:04X}", high, low)
            }
            InvalidUnicodeEscape(escape) => write!(f, "invalid JSON Unicode escape: \\u{}", escape),
            InvalidUtf8 => write!(f, "invalid UTF-8 codepoint in JSON string"),
            UnexpectedEndOfString => write!(f, "unexpected end of string"),
        }
    }
}

/// Escapes a string for embedding in a JSON string value.
pub fn escape_string(value: &str) -> Cow<str> {
@@ -45,9 +80,119 @@ fn escape_string_inner(start: &[u8], rest: &[u8]) -> String {
    unsafe { String::from_utf8_unchecked(escaped) }
}

/// Unescapes a JSON-escaped string.
/// If there are no escape sequences, it directly returns the reference.
pub fn unescape_string(value: &str) -> Result<Cow<str>, Error> {
    let bytes = value.as_bytes();
    for (index, byte) in bytes.iter().enumerate() {
        if *byte == b'\\' {
            return unescape_string_inner(&bytes[0..index], &bytes[index..]).map(Cow::Owned);
        }
    }
    Ok(Cow::Borrowed(value))
}

fn unescape_string_inner(start: &[u8], rest: &[u8]) -> Result<String, Error> {
    let mut unescaped = Vec::with_capacity(start.len() + rest.len());
    unescaped.extend(start);

    let mut index = 0;
    while index < rest.len() {
        match rest[index] {
            b'\\' => {
                index += 1;
                if index == rest.len() {
                    return Err(Error::UnexpectedEndOfString);
                }
                match rest[index] {
                    b'u' => {
                        index -= 1;
                        index += read_unicode_escapes(&rest[index..], &mut unescaped)?;
                    }
                    byte => {
                        match byte {
                            b'\\' => unescaped.push(b'\\'),
                            b'/' => unescaped.push(b'/'),
                            b'"' => unescaped.push(b'"'),
                            b'b' => unescaped.push(0x08),
                            b'f' => unescaped.push(0x0C),
                            b'n' => unescaped.push(b'\n'),
                            b'r' => unescaped.push(b'\r'),
                            b't' => unescaped.push(b'\t'),
                            _ => return Err(Error::InvalidEscapeCharacter(byte.into())),
                        }
                        index += 1;
                    }
                }
            }
            byte => {
                unescaped.push(byte);
                index += 1
            }
        }
    }

    String::from_utf8(unescaped).map_err(|_| Error::InvalidUtf8)
}

fn is_utf16_low_surrogate(codepoint: u16) -> bool {
    codepoint & 0xFC00 == 0xDC00
}

fn is_utf16_high_surrogate(codepoint: u16) -> bool {
    codepoint & 0xFC00 == 0xD800
}

fn read_codepoint(rest: &[u8]) -> Result<u16, Error> {
    if rest.len() < 6 {
        return Err(Error::UnexpectedEndOfString);
    }
    if &rest[0..2] != b"\\u" {
        // The first codepoint is always prefixed with "\u" since unescape_string_inner does
        // that check, so this error will always be for the low word of a surrogate pair.
        return Err(Error::ExpectedSurrogatePair(
            String::from_utf8_lossy(&rest[0..6]).into(),
        ));
    }

    let codepoint_str = std::str::from_utf8(&rest[2..6]).map_err(|_| Error::InvalidUtf8)?;
    u16::from_str_radix(codepoint_str, 16)
        .map_err(|_| Error::InvalidUnicodeEscape(codepoint_str.into()))
}

/// Reads JSON Unicode escape sequences (i.e., "\u1234"). Will also read
/// an additional codepoint if the first codepoint is the start of a surrogate pair.
fn read_unicode_escapes(bytes: &[u8], into: &mut Vec<u8>) -> Result<usize, Error> {
    let high = read_codepoint(bytes)?;
    let (bytes_read, chr) = if is_utf16_high_surrogate(high) {
        let low = read_codepoint(&bytes[6..])?;
        if !is_utf16_low_surrogate(low) {
            return Err(Error::InvalidSurrogatePair(high, low));
        }

        let codepoint =
            char::from_u32(0x10000 + (high - 0xD800) as u32 * 0x400 + (low - 0xDC00) as u32)
                .ok_or(Error::InvalidSurrogatePair(high, low))?;
        (12, codepoint)
    } else {
        let codepoint = char::from_u32(high as u32).ok_or_else(|| {
            Error::InvalidUnicodeEscape(String::from_utf8_lossy(&bytes[0..6]).into())
        })?;
        (6, codepoint)
    };

    match chr.len_utf8() {
        1 => into.push(chr as u8),
        _ => into.extend_from_slice(chr.encode_utf8(&mut [0; 4]).as_bytes()),
    }
    Ok(bytes_read)
}

#[cfg(test)]
mod test {
    use super::escape_string;
    use crate::escape::{unescape_string, Error};
    use std::borrow::Cow;

    #[test]
    fn escape() {
@@ -66,6 +211,49 @@ mod test {
        assert_eq!("\\u001f", escape_string("\u{1f}").as_ref());
    }

    #[test]
    fn unescape_no_escapes() {
        let unescaped = unescape_string("test test").unwrap();
        assert_eq!("test test", unescaped);
        assert!(matches!(unescaped, Cow::Borrowed(_)));
    }

    #[test]
    fn unescape() {
        assert_eq!(
            "\x08f\x0Co\to\r\n",
            unescape_string(r#"\bf\fo\to\r\n"#).unwrap()
        );
        assert_eq!("\"test\"", unescape_string(r#"\"test\""#).unwrap());
        assert_eq!("\x00", unescape_string("\\u0000").unwrap());
        assert_eq!("\x1f", unescape_string("\\u001f").unwrap());
        assert_eq!("foo\r\nbar", unescape_string("foo\\r\\nbar").unwrap());
        assert_eq!("foo\r\n", unescape_string("foo\\r\\n").unwrap());
        assert_eq!("\r\nbar", unescape_string("\\r\\nbar").unwrap());
        assert_eq!("\u{10437}", unescape_string("\\uD801\\uDC37").unwrap());

        assert_eq!(Err(Error::UnexpectedEndOfString), unescape_string("\\"));
        assert_eq!(Err(Error::UnexpectedEndOfString), unescape_string("\\u"));
        assert_eq!(Err(Error::UnexpectedEndOfString), unescape_string("\\u00"));
        assert_eq!(
            Err(Error::InvalidEscapeCharacter('z')),
            unescape_string("\\z")
        );

        assert_eq!(
            Err(Error::ExpectedSurrogatePair("\\nasdf".into())),
            unescape_string("\\uD801\\nasdf")
        );
        assert_eq!(
            Err(Error::UnexpectedEndOfString),
            unescape_string("\\uD801\\u00")
        );
        assert_eq!(
            Err(Error::InvalidSurrogatePair(0xD801, 0xC501)),
            unescape_string("\\uD801\\uC501")
        );
    }

    use proptest::proptest;
    proptest! {
        #[test]
@@ -74,6 +262,31 @@ mod test {
            let serde_escaped = &serde_escaped[1..(serde_escaped.len() - 1)];
            assert_eq!(serde_escaped,escape_string(&s))
        }

        #[test]
        fn round_trip(chr in proptest::char::any()) {
            let mut original = String::new();
            original.push(chr);

            let escaped = escape_string(&original);
            let unescaped = unescape_string(&escaped).unwrap();
            assert_eq!(original, unescaped);
        }

        #[test]
        fn unicode_surrogates(chr in proptest::char::range(
            char::from_u32(0x10000).unwrap(),
            char::from_u32(0x10FFFF).unwrap(),
        )) {
            let mut codepoints = [0; 2];
            chr.encode_utf16(&mut codepoints);

            let escaped = format!("\\u{:04X}\\u{:04X}", codepoints[0], codepoints[1]);
            let unescaped = unescape_string(&escaped).unwrap();

            let expected = format!("{}", chr);
            assert_eq!(expected, unescaped);
        }
    }

    #[test]
+1 −0
Original line number Diff line number Diff line
@@ -5,5 +5,6 @@

//! JSON Abstractions for Smithy

pub mod deserialize;
mod escape;
pub mod serialize;