Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Centralise error positioning + cover custom de errors #356

Merged
merged 5 commits into from
Feb 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fix issue [#359](https://github.com/ron-rs/ron/issues/359) with `DeserializeSeed` support ([#360](https://github.com/ron-rs/ron/pull/360))
- Bump MSRV to 1.46.0 ([#361](https://github.com/ron-rs/ron/pull/361))
- Fix issue [#337](https://github.com/ron-rs/ron/issues/337) by removing `decimal_floats` PrettyConfig option and unconditional decimals in floats ([#363](https://github.com/ron-rs/ron/pull/363))
- Fix issue [#203](https://github.com/ron-rs/ron/issues/203) with full de error positioning ([#356](https://github.com/ron-rs/ron/pull/356))

## [0.7.0] - 2021-10-22

Expand Down
78 changes: 40 additions & 38 deletions src/de/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/// Deserialization module.
pub use crate::error::{Error, ErrorCode, Position, Result};
pub use crate::error::{Error, Position, SpannedError};

use serde::de::{self, DeserializeSeed, Deserializer as SerdeError, Visitor};
use std::{borrow::Cow, io, str};

use self::{id::IdDeserializer, tag::TagDeserializer};
use crate::{
error::{Result, SpannedResult},
extensions::Extensions,
options::Options,
parse::{AnyNum, Bytes, ParsedStr},
Expand All @@ -29,19 +30,19 @@ pub struct Deserializer<'de> {
impl<'de> Deserializer<'de> {
// Cannot implement trait here since output is tied to input lifetime 'de.
#[allow(clippy::should_implement_trait)]
pub fn from_str(input: &'de str) -> Result<Self> {
pub fn from_str(input: &'de str) -> SpannedResult<Self> {
Self::from_str_with_options(input, Options::default())
}

pub fn from_bytes(input: &'de [u8]) -> Result<Self> {
pub fn from_bytes(input: &'de [u8]) -> SpannedResult<Self> {
Self::from_bytes_with_options(input, Options::default())
}

pub fn from_str_with_options(input: &'de str, options: Options) -> Result<Self> {
pub fn from_str_with_options(input: &'de str, options: Options) -> SpannedResult<Self> {
Self::from_bytes_with_options(input.as_bytes(), options)
}

pub fn from_bytes_with_options(input: &'de [u8], options: Options) -> Result<Self> {
pub fn from_bytes_with_options(input: &'de [u8], options: Options) -> SpannedResult<Self> {
let mut deserializer = Deserializer {
bytes: Bytes::new(input)?,
newtype_variant: false,
Expand All @@ -55,11 +56,15 @@ impl<'de> Deserializer<'de> {
pub fn remainder(&self) -> Cow<'_, str> {
String::from_utf8_lossy(self.bytes.bytes())
}

pub fn span_error(&self, code: Error) -> SpannedError {
self.bytes.span_error(code)
}
}

/// A convenience function for building a deserializer
/// and deserializing a value of type `T` from a reader.
pub fn from_reader<R, T>(rdr: R) -> Result<T>
pub fn from_reader<R, T>(rdr: R) -> SpannedResult<T>
where
R: io::Read,
T: de::DeserializeOwned,
Expand All @@ -69,7 +74,7 @@ where

/// A convenience function for building a deserializer
/// and deserializing a value of type `T` from a string.
pub fn from_str<'a, T>(s: &'a str) -> Result<T>
pub fn from_str<'a, T>(s: &'a str) -> SpannedResult<T>
where
T: de::Deserialize<'a>,
{
Expand All @@ -78,7 +83,7 @@ where

/// A convenience function for building a deserializer
/// and deserializing a value of type `T` from bytes.
pub fn from_bytes<'a, T>(s: &'a [u8]) -> Result<T>
pub fn from_bytes<'a, T>(s: &'a [u8]) -> SpannedResult<T>
where
T: de::Deserialize<'a>,
{
Expand All @@ -94,7 +99,7 @@ impl<'de> Deserializer<'de> {
if self.bytes.bytes().is_empty() {
Ok(())
} else {
self.bytes.err(ErrorCode::TrailingCharacters)
Err(Error::TrailingCharacters)
}
}

Expand Down Expand Up @@ -191,7 +196,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
b'.' => self.deserialize_f64(visitor),
b'"' | b'r' => self.deserialize_string(visitor),
b'\'' => self.deserialize_char(visitor),
other => self.bytes.err(ErrorCode::UnexpectedByte(other as char)),
other => Err(Error::UnexpectedByte(other as char)),
}
}

Expand Down Expand Up @@ -334,7 +339,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {

match res {
Ok(byte_buf) => visitor.visit_byte_buf(byte_buf),
Err(err) => self.bytes.err(ErrorCode::Base64Error(err)),
Err(err) => Err(Error::Base64Error(err)),
}
}

Expand All @@ -359,10 +364,10 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
if self.bytes.consume(")") {
Ok(v)
} else {
self.bytes.err(ErrorCode::ExpectedOptionEnd)
Err(Error::ExpectedOptionEnd)
}
} else {
self.bytes.err(ErrorCode::ExpectedOption)
Err(Error::ExpectedOption)
}
}

Expand All @@ -376,7 +381,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {

visitor.visit_unit()
} else {
self.bytes.err(ErrorCode::ExpectedUnit)
Err(Error::ExpectedUnit)
}
}

Expand Down Expand Up @@ -415,12 +420,12 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
if self.bytes.consume(")") {
Ok(value)
} else {
self.bytes.err(ErrorCode::ExpectedStructEnd)
Err(Error::ExpectedStructLikeEnd)
}
} else if name.is_empty() {
self.bytes.err(ErrorCode::ExpectedStruct)
Err(Error::ExpectedStructLike)
} else {
self.bytes.err(ErrorCode::ExpectedNamedStruct(name))
Err(Error::ExpectedNamedStructLike(name))
}
}

Expand All @@ -437,10 +442,10 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
if self.bytes.consume("]") {
Ok(value)
} else {
self.bytes.err(ErrorCode::ExpectedArrayEnd)
Err(Error::ExpectedArrayEnd)
}
} else {
self.bytes.err(ErrorCode::ExpectedArray)
Err(Error::ExpectedArray)
}
}

Expand All @@ -458,10 +463,10 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
if old_newtype_variant || self.bytes.consume(")") {
Ok(value)
} else {
self.bytes.err(ErrorCode::ExpectedArrayEnd)
Err(Error::ExpectedStructLikeEnd)
}
} else {
self.bytes.err(ErrorCode::ExpectedArray)
Err(Error::ExpectedStructLike)
}
}

Expand All @@ -478,7 +483,10 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.bytes.consume_struct_name(name)?;
}

self.deserialize_tuple(len, visitor)
self.deserialize_tuple(len, visitor).map_err(|e| match e {
Error::ExpectedStructLike if !name.is_empty() => Error::ExpectedNamedStructLike(name),
e => e,
})
}

fn deserialize_map<V>(mut self, visitor: V) -> Result<V::Value>
Expand All @@ -494,10 +502,10 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
if self.bytes.consume("}") {
Ok(value)
} else {
self.bytes.err(ErrorCode::ExpectedMapEnd)
Err(Error::ExpectedMapEnd)
}
} else {
self.bytes.err(ErrorCode::ExpectedMap)
Err(Error::ExpectedMap)
}
}

Expand Down Expand Up @@ -526,12 +534,12 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
if old_newtype_variant || self.bytes.consume(")") {
Ok(value)
} else {
self.bytes.err(ErrorCode::ExpectedStructEnd)
Err(Error::ExpectedStructLikeEnd)
}
} else if name.is_empty() {
self.bytes.err(ErrorCode::ExpectedStruct)
Err(Error::ExpectedStructLike)
} else {
self.bytes.err(ErrorCode::ExpectedNamedStruct(name))
Err(Error::ExpectedNamedStructLike(name))
}
}

Expand All @@ -553,9 +561,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
where
V: Visitor<'de>,
{
visitor.visit_str(
str::from_utf8(self.bytes.identifier()?).map_err(|e| self.bytes.error(e.into()))?,
)
visitor.visit_str(str::from_utf8(self.bytes.identifier()?).map_err(Error::from)?)
}

fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
Expand All @@ -581,10 +587,6 @@ impl<'a, 'de> CommaSeparated<'a, 'de> {
}
}

fn err<T>(&self, kind: ErrorCode) -> Result<T> {
self.de.bytes.err(kind)
}

fn has_element(&mut self) -> Result<bool> {
self.de.bytes.skip_ws()?;

Expand All @@ -597,7 +599,7 @@ impl<'a, 'de> CommaSeparated<'a, 'de> {
// No trailing comma but terminator
(false, false) => Ok(false),
// No trailing comma or terminator
(false, true) => self.err(ErrorCode::ExpectedComma),
(false, true) => Err(Error::ExpectedComma),
}
}
}
Expand Down Expand Up @@ -655,7 +657,7 @@ impl<'de, 'a> de::MapAccess<'de> for CommaSeparated<'a, 'de> {

Ok(res)
} else {
self.err(ErrorCode::ExpectedMapColon)
Err(Error::ExpectedMapColon)
}
}
}
Expand Down Expand Up @@ -717,10 +719,10 @@ impl<'de, 'a> de::VariantAccess<'de> for Enum<'a, 'de> {
if self.de.bytes.consume(")") {
Ok(val)
} else {
self.de.bytes.err(ErrorCode::ExpectedStructEnd)
Err(Error::ExpectedStructLikeEnd)
}
} else {
self.de.bytes.err(ErrorCode::ExpectedStruct)
Err(Error::ExpectedStructLike)
}
}

Expand Down
52 changes: 28 additions & 24 deletions src/de/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use serde::Deserialize;
use serde_bytes;

use super::*;
use crate::{
de::from_str,
error::{Error, Position, SpannedError, SpannedResult},
parse::{AnyNum, Bytes},
};

#[derive(Debug, PartialEq, Deserialize)]
struct EmptyStruct1;
Expand Down Expand Up @@ -149,40 +153,40 @@ y: 2.0 // 2!
);
}

fn err<T>(kind: ErrorCode, line: usize, col: usize) -> Result<T> {
Err(Error {
fn err<T>(kind: Error, line: usize, col: usize) -> SpannedResult<T> {
Err(SpannedError {
code: kind,
position: Position { line, col },
})
}

#[test]
fn test_err_wrong_value() {
use self::ErrorCode::*;
use self::Error::*;
use std::collections::HashMap;

assert_eq!(from_str::<f32>("'c'"), err(ExpectedFloat, 1, 1));
assert_eq!(from_str::<String>("'c'"), err(ExpectedString, 1, 1));
assert_eq!(from_str::<HashMap<u32, u32>>("'c'"), err(ExpectedMap, 1, 1));
assert_eq!(from_str::<[u8; 5]>("'c'"), err(ExpectedArray, 1, 1));
assert_eq!(from_str::<[u8; 5]>("'c'"), err(ExpectedStructLike, 1, 1));
assert_eq!(from_str::<Vec<u32>>("'c'"), err(ExpectedArray, 1, 1));
assert_eq!(from_str::<MyEnum>("'c'"), err(ExpectedIdentifier, 1, 1));
assert_eq!(
from_str::<MyStruct>("'c'"),
err(ExpectedNamedStruct("MyStruct"), 1, 1)
err(ExpectedNamedStructLike("MyStruct"), 1, 1)
);
assert_eq!(
from_str::<MyStruct>("NotMyStruct(x: 4, y: 2)"),
err(
ExpectedStructName {
ExpectedDifferentStructName {
expected: "MyStruct",
found: String::from("NotMyStruct")
},
1,
1
12
)
);
assert_eq!(from_str::<(u8, bool)>("'c'"), err(ExpectedArray, 1, 1));
assert_eq!(from_str::<(u8, bool)>("'c'"), err(ExpectedStructLike, 1, 1));
assert_eq!(from_str::<bool>("notabool"), err(ExpectedBoolean, 1, 1));

assert_eq!(
Expand Down Expand Up @@ -234,54 +238,54 @@ fn rename() {

#[test]
fn forgot_apostrophes() {
let de: Result<(i32, String)> = from_str("(4, \"Hello)");
let de: SpannedResult<(i32, String)> = from_str("(4, \"Hello)");

assert!(match de {
Err(Error {
code: ErrorCode::ExpectedStringEnd,
assert!(matches!(
de,
Err(SpannedError {
code: Error::ExpectedStringEnd,
position: _,
}) => true,
_ => false,
});
})
));
}

#[test]
fn expected_attribute() {
let de: Result<String> = from_str("#\"Hello\"");
let de: SpannedResult<String> = from_str("#\"Hello\"");

assert_eq!(de, err(ErrorCode::ExpectedAttribute, 1, 2));
assert_eq!(de, err(Error::ExpectedAttribute, 1, 2));
}

#[test]
fn expected_attribute_end() {
let de: Result<String> = from_str("#![enable(unwrap_newtypes) \"Hello\"");
let de: SpannedResult<String> = from_str("#![enable(unwrap_newtypes) \"Hello\"");

assert_eq!(de, err(ErrorCode::ExpectedAttributeEnd, 1, 28));
assert_eq!(de, err(Error::ExpectedAttributeEnd, 1, 28));
}

#[test]
fn invalid_attribute() {
let de: Result<String> = from_str("#![enable(invalid)] \"Hello\"");
let de: SpannedResult<String> = from_str("#![enable(invalid)] \"Hello\"");

assert_eq!(
de,
err(ErrorCode::NoSuchExtension("invalid".to_string()), 1, 18)
err(Error::NoSuchExtension("invalid".to_string()), 1, 18)
);
}

#[test]
fn multiple_attributes() {
#[derive(Debug, Deserialize, PartialEq)]
struct New(String);
let de: Result<New> =
let de: SpannedResult<New> =
from_str("#![enable(unwrap_newtypes)] #![enable(unwrap_newtypes)] \"Hello\"");

assert_eq!(de, Ok(New("Hello".to_owned())));
}

#[test]
fn uglified_attribute() {
let de: Result<()> = from_str(
let de: SpannedResult<()> = from_str(
"# !\
// We definitely want to add a comment here
[\t\tenable( // best style ever
Expand Down
Loading