crates/edge/json/src/parse.rs 16.5 KiB 484 lines Raw
1 //! The JSON reader.2 //!3 //! RFC 8259 exactly, plus four rules that the spec adds because a parser that4 //! accepts them turns a bad catalogue into a silent one:5 //!6 //! - A key repeated in one object is `DuplicateKey`. Two `serve` entries would7 //!   otherwise resolve by whichever the map happened to keep.8 //! - Nesting is capped at [`MAX_DEPTH`]. A decoder recurses, and one level is9 //!   one stack frame.10 //! - A number that does not fit `i64` widens to `Float`; one that does not fit11 //!   `f64` is `Number`. There is no bignum in this tree.12 //! - Bytes after the value are `Trailing`. One document per call, with nothing13 //!   stuck to it.14 //!15 //! Every error carries the byte offset of the fault, because the caller prints16 //! it to an operator who has the offending file open.17 18 use std::fmt;19 20 use crate::value::Value;21 22 /// The deepest container that the reader accepts.23 pub const MAX_DEPTH: usize = 128;24 25 /// Text that is not JSON this codec accepts.26 #[derive(Clone, PartialEq, Eq, Debug)]27 pub enum JsonError {28     /// The text ends where a value, or the rest of one, is required.29     Eof { offset: usize },30     /// A byte that cannot start or continue a value, such as the `/` of a31     /// comment or the `,` of a trailing comma.32     Unexpected { offset: usize, byte: u8 },33     /// The same key twice in one object.34     DuplicateKey { offset: usize, key: String },35     /// A container nested below [`MAX_DEPTH`].36     Depth { offset: usize },37     /// A number that does not fit `f64`, or that its grammar cannot hold.38     Number { offset: usize },39     /// A byte below 0x20 written raw inside a string.40     Control { offset: usize },41     /// An escape that JSON does not define, or a surrogate with no partner.42     Escape { offset: usize },43     /// Bytes after the value.44     Trailing { offset: usize },45     /// Text that is not UTF-8.46     Utf8 { offset: usize },47 }48 49 impl JsonError {50     /// The byte offset of the fault.51     pub fn offset(&self) -> usize {52         match self {53             JsonError::Eof { offset }54             | JsonError::Unexpected { offset, .. }55             | JsonError::DuplicateKey { offset, .. }56             | JsonError::Depth { offset }57             | JsonError::Number { offset }58             | JsonError::Control { offset }59             | JsonError::Escape { offset }60             | JsonError::Trailing { offset }61             | JsonError::Utf8 { offset } => *offset,62         }63     }64 }65 66 impl fmt::Display for JsonError {67     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {68         match self {69             JsonError::Eof { offset } => write!(f, "the text ends at {offset}"),70             JsonError::Unexpected { offset, byte } => {71                 write!(f, "byte {byte:#04x} at {offset} cannot appear there")72             }73             JsonError::DuplicateKey { offset, key } => {74                 write!(f, "key {key:?} appears twice at {offset}")75             }76             JsonError::Depth { offset } => {77                 write!(f, "nesting at {offset} is deeper than {MAX_DEPTH}")78             }79             JsonError::Number { offset } => write!(f, "the number at {offset} is out of range"),80             JsonError::Control { offset } => {81                 write!(f, "a control byte at {offset} is raw inside a string")82             }83             JsonError::Escape { offset } => write!(f, "the escape at {offset} is not valid"),84             JsonError::Trailing { offset } => write!(f, "byte {offset} follows the value"),85             JsonError::Utf8 { offset } => write!(f, "the text is not UTF-8 at {offset}"),86         }87     }88 }89 90 impl std::error::Error for JsonError {}91 92 /// One JSON value read from a byte slice that is never copied.93 struct Reader<'a> {94     bytes: &'a [u8],95     at: usize,96 }97 98 impl<'a> Reader<'a> {99     /// The byte at `at`, or `Eof` when the text is exhausted.100     fn byte(&self, at: usize) -> Result<u8, JsonError> {101         self.bytes102             .get(at)103             .copied()104             .ok_or(JsonError::Eof { offset: at })105     }106 107     /// The next byte, without consuming it.108     fn peek(&self) -> Option<u8> {109         self.bytes.get(self.at).copied()110     }111 112     /// True when the next byte is one of the four JSON whitespace bytes.113     fn is_space(&self) -> bool {114         matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r'))115     }116 117     /// Steps over whitespace.118     fn skip_space(&mut self) {119         while self.is_space() {120             self.at += 1;121         }122     }123 124     /// Reads one value. `depth` is how many containers enclose it.125     fn value(&mut self, depth: usize) -> Result<Value, JsonError> {126         self.skip_space();127         let at = self.at;128         match self.byte(at)? {129             b'[' => self.array(depth, at),130             b'{' => self.object(depth, at),131             b'"' => self.string().map(Value::Str),132             b'n' => self.literal(b"null").map(|()| Value::Null),133             b't' => self.literal(b"true").map(|()| Value::Bool(true)),134             b'f' => self.literal(b"false").map(|()| Value::Bool(false)),135             b'-' | b'0'..=b'9' => self.number(),136             byte => Err(JsonError::Unexpected { offset: at, byte }),137         }138     }139 140     /// Consumes `word`. A byte that differs from it is `Unexpected` at that141     /// byte, so `trux` names the `x` and not the end of the token.142     fn literal(&mut self, word: &[u8]) -> Result<(), JsonError> {143         let start = self.at;144         for (index, expected) in word.iter().enumerate() {145             let at = start + index;146             let byte = self.byte(at)?;147             if byte != *expected {148                 return Err(JsonError::Unexpected { offset: at, byte });149             }150         }151         self.at = start + word.len();152         Ok(())153     }154 155     /// Reads `[ ... ]`. `open` is the `[`.156     fn array(&mut self, depth: usize, open: usize) -> Result<Value, JsonError> {157         if depth + 1 > MAX_DEPTH {158             return Err(JsonError::Depth { offset: open });159         }160         self.at += 1;161         let mut items = Vec::new();162         self.skip_space();163         if self.peek() == Some(b']') {164             self.at += 1;165             return Ok(Value::Array(items));166         }167         loop {168             items.push(self.value(depth + 1)?);169             self.skip_space();170             match self.peek() {171                 Some(b',') => self.at += 1,172                 Some(b']') => {173                     self.at += 1;174                     return Ok(Value::Array(items));175                 }176                 Some(byte) => {177                     return Err(JsonError::Unexpected {178                         offset: self.at,179                         byte,180                     });181                 }182                 None => return Err(JsonError::Eof { offset: self.at }),183             }184         }185     }186 187     /// Reads `{ ... }`. `open` is the `{`.188     fn object(&mut self, depth: usize, open: usize) -> Result<Value, JsonError> {189         if depth + 1 > MAX_DEPTH {190             return Err(JsonError::Depth { offset: open });191         }192         self.at += 1;193         let mut map = std::collections::BTreeMap::new();194         self.skip_space();195         if self.peek() == Some(b'}') {196             self.at += 1;197             return Ok(Value::Object(map));198         }199         loop {200             self.skip_space();201             let key_at = self.at;202             match self.peek() {203                 Some(b'"') => {}204                 Some(byte) => {205                     return Err(JsonError::Unexpected {206                         offset: key_at,207                         byte,208                     });209                 }210                 None => return Err(JsonError::Eof { offset: key_at }),211             }212             let key = self.string()?;213             if map.contains_key(&key) {214                 return Err(JsonError::DuplicateKey {215                     offset: key_at,216                     key,217                 });218             }219             self.skip_space();220             match self.peek() {221                 Some(b':') => self.at += 1,222                 Some(byte) => {223                     return Err(JsonError::Unexpected {224                         offset: self.at,225                         byte,226                     });227                 }228                 None => return Err(JsonError::Eof { offset: self.at }),229             }230             let value = self.value(depth + 1)?;231             map.insert(key, value);232 233             self.skip_space();234             match self.peek() {235                 Some(b',') => self.at += 1,236                 Some(b'}') => {237                     self.at += 1;238                     return Ok(Value::Object(map));239                 }240                 Some(byte) => {241                     return Err(JsonError::Unexpected {242                         offset: self.at,243                         byte,244                     });245                 }246                 None => return Err(JsonError::Eof { offset: self.at }),247             }248         }249     }250 251     /// Reads one string, starting at its opening quote.252     fn string(&mut self) -> Result<String, JsonError> {253         let open = self.at;254         self.at += 1;255         let mut raw: Vec<u8> = Vec::new();256         loop {257             let at = self.at;258             let byte = self.byte(at)?;259             match byte {260                 b'"' => {261                     self.at += 1;262                     // The input is UTF-8 as a whole, so the bytes copied here263                     // are UTF-8 too; the check keeps that a fact and not an264                     // assumption.265                     return String::from_utf8(raw).map_err(|_| JsonError::Utf8 { offset: open });266                 }267                 b'\\' => self.escape(&mut raw, at)?,268                 0x00..=0x1f => return Err(JsonError::Control { offset: at }),269                 _ => {270                     raw.push(byte);271                     self.at += 1;272                 }273             }274         }275     }276 277     /// Reads one escape, starting at its backslash (`at`), and appends the278     /// text it stands for.279     fn escape(&mut self, raw: &mut Vec<u8>, at: usize) -> Result<(), JsonError> {280         self.at += 1;281         let mark = self.at;282         match self.byte(mark)? {283             b'"' => {284                 raw.push(b'"');285                 self.at += 1;286             }287             b'\\' => {288                 raw.push(b'\\');289                 self.at += 1;290             }291             b'/' => {292                 raw.push(b'/');293                 self.at += 1;294             }295             b'b' => {296                 raw.push(0x08);297                 self.at += 1;298             }299             b'f' => {300                 raw.push(0x0c);301                 self.at += 1;302             }303             b'n' => {304                 raw.push(b'\n');305                 self.at += 1;306             }307             b'r' => {308                 raw.push(b'\r');309                 self.at += 1;310             }311             b't' => {312                 raw.push(b'\t');313                 self.at += 1;314             }315             b'u' => {316                 self.at += 1;317                 let high = self.hex4(at)?;318                 match high {319                     // A low surrogate on its own has no code point.320                     0xDC00..=0xDFFF => return Err(JsonError::Escape { offset: at }),321                     0xD800..=0xDBFF => {322                         // A high surrogate is a code point only together with323                         // the low one that must follow it.324                         if self.peek() != Some(b'\\') {325                             return Err(JsonError::Escape { offset: at });326                         }327                         let low_at = self.at;328                         self.at += 1;329                         if self.peek() != Some(b'u') {330                             return Err(JsonError::Escape { offset: low_at });331                         }332                         self.at += 1;333                         let low = self.hex4(low_at)?;334                         if !matches!(low, 0xDC00..=0xDFFF) {335                             return Err(JsonError::Escape { offset: low_at });336                         }337                         let combined = 0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00);338                         push_scalar(raw, combined, at)?;339                     }340                     scalar => push_scalar(raw, scalar, at)?,341                 }342             }343             _ => return Err(JsonError::Escape { offset: at }),344         }345         Ok(())346     }347 348     /// Reads the four hex digits of a `\u`. A short or non-hex run is `Escape`349     /// at the backslash (`at`).350     fn hex4(&mut self, at: usize) -> Result<u32, JsonError> {351         let start = self.at;352         if self.bytes.len() - start < 4 {353             self.at = self.bytes.len();354             return Err(JsonError::Escape { offset: at });355         }356         let mut value = 0u32;357         for byte in &self.bytes[start..start + 4] {358             let digit = match byte {359                 b'0'..=b'9' => u32::from(byte - b'0'),360                 b'a'..=b'f' => u32::from(byte - b'a') + 10,361                 b'A'..=b'F' => u32::from(byte - b'A') + 10,362                 _ => {363                     self.at = start + 4;364                     return Err(JsonError::Escape { offset: at });365                 }366             };367             value = (value << 4) | digit;368         }369         self.at += 4;370         Ok(value)371     }372 373     /// Reads one number. Its bytes are checked against the RFC grammar before374     /// any of them is converted.375     fn number(&mut self) -> Result<Value, JsonError> {376         let start = self.at;377         if self.peek() == Some(b'-') {378             self.at += 1;379         }380         match self.peek() {381             Some(b'0') => self.at += 1,382             Some(b'1'..=b'9') => self.digits(),383             Some(byte) => {384                 return Err(JsonError::Unexpected {385                     offset: self.at,386                     byte,387                 });388             }389             None => return Err(JsonError::Eof { offset: self.at }),390         }391         let mut integral = true;392         if self.peek() == Some(b'.') {393             integral = false;394             self.at += 1;395             if !matches!(self.peek(), Some(b'0'..=b'9')) {396                 return Err(self.hole());397             }398             self.digits();399         }400         if matches!(self.peek(), Some(b'e') | Some(b'E')) {401             integral = false;402             self.at += 1;403             if matches!(self.peek(), Some(b'+') | Some(b'-')) {404                 self.at += 1;405             }406             if !matches!(self.peek(), Some(b'0'..=b'9')) {407                 return Err(self.hole());408             }409             self.digits();410         }411 412         // The token is ASCII by construction, so this cannot fail. The error413         // arm keeps an unwrap out of the parser.414         let text = std::str::from_utf8(&self.bytes[start..self.at])415             .map_err(|_| JsonError::Number { offset: start })?;416         if integral && let Ok(n) = text.parse::<i64>() {417             return Ok(Value::Int(n));418         }419         let widened = text420             .parse::<f64>()421             .map_err(|_| JsonError::Number { offset: start })?;422         if !widened.is_finite() {423             return Err(JsonError::Number { offset: start });424         }425         Ok(Value::Float(widened))426     }427 428     /// Steps over one or more digits, which the caller has already checked.429     fn digits(&mut self) {430         while matches!(self.peek(), Some(b'0'..=b'9')) {431             self.at += 1;432         }433     }434 435     /// The error for a spot that must hold a digit: `Unexpected` when a byte436     /// is there, `Eof` when the text is not.437     fn hole(&self) -> JsonError {438         match self.peek() {439             Some(byte) => JsonError::Unexpected {440                 offset: self.at,441                 byte,442             },443             None => JsonError::Eof { offset: self.at },444         }445     }446 }447 448 /// Appends the UTF-8 form of a scalar value.449 fn push_scalar(raw: &mut Vec<u8>, scalar: u32, at: usize) -> Result<(), JsonError> {450     match char::from_u32(scalar) {451         Some(c) => {452             raw.extend(c.encode_utf8(&mut [0u8; 4]).bytes());453             Ok(())454         }455         None => Err(JsonError::Escape { offset: at }),456     }457 }458 459 /// Reads one value from text that is already UTF-8.460 pub fn parse(text: &str) -> Result<Value, JsonError> {461     let mut reader = Reader {462         bytes: text.as_bytes(),463         at: 0,464     };465     let value = reader.value(0)?;466     reader.skip_space();467     if reader.at != reader.bytes.len() {468         return Err(JsonError::Trailing { offset: reader.at });469     }470     Ok(value)471 }472 473 /// Reads one value from bytes, which must be UTF-8.474 pub fn parse_bytes(bytes: &[u8]) -> Result<Value, JsonError> {475     let text = match std::str::from_utf8(bytes) {476         Ok(text) => text,477         Err(e) => {478             return Err(JsonError::Utf8 {479                 offset: e.valid_up_to(),480             });481         }482     };483     parse(text)484 }