diff --git a/duper-python/src/de.rs b/duper-python/src/de.rs index 2f4ec9f..7131c0d 100644 --- a/duper-python/src/de.rs +++ b/duper-python/src/de.rs @@ -46,7 +46,7 @@ impl<'py> DuperVisitor for Visitor<'py> { let model = pydantic.getattr("create_model")?.call( (identifier .map(|identifier| identifier.as_ref()) - .unwrap_or("Unknown"),), + .unwrap_or("Object"),), Some(&model_fields), )?; Ok(VisitorValue { diff --git a/duper-python/src/ser/well_known_type.rs b/duper-python/src/ser/well_known_type.rs index bf7f604..5315b48 100644 --- a/duper-python/src/ser/well_known_type.rs +++ b/duper-python/src/ser/well_known_type.rs @@ -110,7 +110,6 @@ impl<'py> WellKnownType<'py> { let module: &str = module_attr.extract()?; let classname_attr = class.getattr("__name__")?; let classname: &str = classname_attr.extract()?; - dbg!(module, classname); match (module, classname) { // bson ("bson.objectid", "ObjectId") => { diff --git a/duper/src/ast.rs b/duper/src/ast.rs index 3a5b254..4c1c0e7 100644 --- a/duper/src/ast.rs +++ b/duper/src/ast.rs @@ -92,6 +92,7 @@ impl<'a> DuperIdentifier<'a> { /// Create a valid identifier from the provided [`Cow<'_, str>`], discarding /// any invalid characters if necessary. + // TO-DO: Use parser pub fn try_from_lossy(value: Cow<'a, str>) -> Result> { let mut new_value = None; let mut chars = value.char_indices(); @@ -159,6 +160,7 @@ impl<'a> TryFrom> for DuperIdentifier<'a> { /// Create a valid identifier from the provided [`Cow<'_, str>`], returning /// an error if there are invalid characters. + // TO-DO: Use parser fn try_from(value: Cow<'a, str>) -> Result { let mut chars = value.char_indices(); match chars.next() { diff --git a/duper/src/escape.rs b/duper/src/escape.rs index 8d855f2..b882bef 100644 --- a/duper/src/escape.rs +++ b/duper/src/escape.rs @@ -3,6 +3,7 @@ use unicode_general_category::{GeneralCategory, get_general_category}; #[derive(Debug)] pub(crate) enum UnescapeError { + UnescapedTab, InvalidByteSequence(String), InvalidUnicode(String), } @@ -10,6 +11,7 @@ pub(crate) enum UnescapeError { impl Display for UnescapeError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + UnescapeError::UnescapedTab => f.write_str("unescaped tab not allowed"), UnescapeError::InvalidByteSequence(hex_str) => f.write_fmt(format_args!( "invalid escape sequence for bytes: \\x{hex_str}" )), @@ -31,7 +33,9 @@ pub(crate) fn unescape_str<'a>(input: &'a str) -> Result, UnescapeE let mut chars = input.chars(); while let Some(c) = chars.next() { - if c == '\\' { + if c == '\t' { + return Err(UnescapeError::UnescapedTab); + } else if c == '\\' { match chars.next() { Some('"') => result.push('"'), Some('\\') => result.push('\\'), @@ -208,7 +212,9 @@ pub(crate) fn unescape_bytes<'a>(input: &'a str) -> Result, Unesca let mut buf = [0u8; 4]; while let Some(c) = chars.next() { - if c == '\\' { + if c == '\t' { + return Err(UnescapeError::UnescapedTab); + } else if c == '\\' { match chars.next() { Some('"') => result.push(b'"'), Some('\\') => result.push(b'\\'), diff --git a/duper/src/parser.rs b/duper/src/parser.rs index 96d1d24..90870d8 100644 --- a/duper/src/parser.rs +++ b/duper/src/parser.rs @@ -12,6 +12,8 @@ pub struct DuperParser; impl DuperParser { /// Parse a Duper trunk, i.e. only an array, tuple, or object at the top level. + /// + /// A pretty printed version of the error can be obtained from the [`prettify_error`] method. pub fn parse_duper_trunk<'a>(input: &'a str) -> Result, Vec>> { // duper_trunk().parse(input).into_result() let value = duper_trunk().parse(input).into_result()?; @@ -22,6 +24,8 @@ impl DuperParser { } /// Parse a Duper value at the top level. + /// + /// A pretty printed version of the error can be obtained from the [`prettify_error`] method. pub fn parse_duper_value<'a>(input: &'a str) -> Result, Vec>> { duper_value().parse(input).into_result() } @@ -105,52 +109,10 @@ pub(crate) fn identifier<'a>() pub(crate) fn identified_trunk<'a>() -> impl Parser<'a, &'a str, DuperValue<'a>, extra::Err>> + Clone { - let object = object_key() - .then_ignore(just(':').padded_by(whitespace_and_comments())) - .then(identified_value().clone()) - .padded_by(whitespace_and_comments()) - .separated_by(just(',').padded_by(whitespace_and_comments())) - .allow_trailing() - .collect::>() - .map(|pairs| DuperObject::try_from(pairs)) - .unwrapped() - .delimited_by(just('{'), just('}')); - - let array = identified_value() - .clone() - .padded_by(whitespace_and_comments()) - .separated_by(just(',').padded_by(whitespace_and_comments())) - .allow_trailing() - .collect::>() - .map(|values| DuperArray(values)) - .delimited_by( - just('[').padded_by(whitespace_and_comments()), - just(']').padded_by(whitespace_and_comments()), - ) - .or(just(',') - .padded_by(whitespace_and_comments()) - .delimited_by(just('['), just(']')) - .map(|_| DuperArray(vec![]))); - - let tuple = identified_value() - .padded_by(whitespace_and_comments()) - .separated_by(just(',').padded_by(whitespace_and_comments())) - .allow_trailing() - .collect::>() - .map(|values| DuperTuple(values)) - .delimited_by( - just('(').padded_by(whitespace_and_comments()), - just(')').padded_by(whitespace_and_comments()), - ) - .or(just(',') - .padded_by(whitespace_and_comments()) - .delimited_by(just('('), just(')')) - .map(|_| DuperTuple(vec![]))); - let inner_trunk = choice(( - object.map(DuperInner::Object), - array.map(DuperInner::Array), - tuple.map(DuperInner::Tuple), + object(identified_value()).map(DuperInner::Object), + array(identified_value()).map(DuperInner::Array), + tuple(identified_value()).map(DuperInner::Tuple), )) .padded_by(whitespace_and_comments()); @@ -170,52 +132,10 @@ pub(crate) fn identified_trunk<'a>() pub(crate) fn identified_value<'a>() -> impl Parser<'a, &'a str, DuperValue<'a>, extra::Err>> + Clone { recursive(move |identified_value| { - let object = object_key() - .then_ignore(just(':').padded_by(whitespace_and_comments())) - .then(identified_value.clone()) - .padded_by(whitespace_and_comments()) - .separated_by(just(',').padded_by(whitespace_and_comments())) - .allow_trailing() - .collect::>() - .map(|pairs| DuperObject::try_from(pairs)) - .unwrapped() - .delimited_by(just('{'), just('}')); - - let array = identified_value - .clone() - .padded_by(whitespace_and_comments()) - .separated_by(just(',').padded_by(whitespace_and_comments())) - .allow_trailing() - .collect::>() - .map(|values| DuperArray(values)) - .delimited_by( - just('[').padded_by(whitespace_and_comments()), - just(']').padded_by(whitespace_and_comments()), - ) - .or(just(',') - .padded_by(whitespace_and_comments()) - .delimited_by(just('['), just(']')) - .map(|_| DuperArray(vec![]))); - - let tuple = identified_value - .padded_by(whitespace_and_comments()) - .separated_by(just(',').padded_by(whitespace_and_comments())) - .allow_trailing() - .collect::>() - .map(|values| DuperTuple(values)) - .delimited_by( - just('(').padded_by(whitespace_and_comments()), - just(')').padded_by(whitespace_and_comments()), - ) - .or(just(',') - .padded_by(whitespace_and_comments()) - .delimited_by(just('('), just(')')) - .map(|_| DuperTuple(vec![]))); - let inner_value = choice(( - object.map(DuperInner::Object), - array.map(DuperInner::Array), - tuple.map(DuperInner::Tuple), + object(identified_value.clone()).map(DuperInner::Object), + array(identified_value.clone()).map(DuperInner::Array), + tuple(identified_value).map(DuperInner::Tuple), quoted_string().map(|cow_str| DuperInner::String(DuperString(cow_str))), raw_string().map(|str| DuperInner::String(DuperString(Cow::Borrowed(str)))), quoted_bytes().map(|cow_bytes| DuperInner::Bytes(DuperBytes(cow_bytes))), @@ -241,6 +161,35 @@ pub(crate) fn identified_value<'a>() }) } +pub(crate) fn object<'a>( + identified_value: impl Parser<'a, &'a str, DuperValue<'a>, extra::Err>> + Clone, +) -> impl Parser<'a, &'a str, DuperObject<'a>, extra::Err>> + Clone { + object_key() + .then_ignore( + just(':') + .ignored() + .recover_with(via_parser(value_recovery())) + .padded_by(whitespace_and_comments()), + ) + .then(identified_value) + .padded_by(whitespace_and_comments()) + .separated_by( + just(',') + .ignored() + .recover_with(via_parser(key_recovery())) + .padded_by(whitespace_and_comments()), + ) + .allow_trailing() + .collect::>() + .try_map(|object, span| { + DuperObject::try_from(object).map_err(|err| Rich::custom(span, err)) + }) + .delimited_by( + just('{').padded_by(whitespace_and_comments()), + just('}').padded_by(whitespace_and_comments()), + ) +} + pub(crate) fn object_key<'a>() -> impl Parser<'a, &'a str, DuperKey<'a>, extra::Err>> + Clone { let plain_key = any() @@ -269,25 +218,86 @@ pub(crate) fn object_key<'a>() .map(|str| DuperKey(Cow::Borrowed(str))); quoted_string() - .map(|cow_str| DuperKey(cow_str)) + .map(DuperKey) .or(raw_string().map(|str| DuperKey(Cow::Borrowed(str)))) .or(plain_key) } +pub(crate) fn array<'a>( + identified_value: impl Parser<'a, &'a str, DuperValue<'a>, extra::Err>> + Clone, +) -> impl Parser<'a, &'a str, DuperArray<'a>, extra::Err>> + Clone { + identified_value + .padded_by(whitespace_and_comments()) + .separated_by( + just(',') + .ignored() + .recover_with(via_parser(value_recovery())) + .padded_by(whitespace_and_comments()), + ) + .allow_trailing() + .collect::>() + .map(DuperArray) + .delimited_by( + just('[').padded_by(whitespace_and_comments()), + just(']').padded_by(whitespace_and_comments()), + ) + .or(just(',') + .padded_by(whitespace_and_comments()) + .delimited_by(just('['), just(']')) + .map(|_| DuperArray(vec![]))) +} + +pub(crate) fn tuple<'a>( + identified_value: impl Parser<'a, &'a str, DuperValue<'a>, extra::Err>> + Clone, +) -> impl Parser<'a, &'a str, DuperTuple<'a>, extra::Err>> + Clone { + identified_value + .padded_by(whitespace_and_comments()) + .separated_by( + just(',') + .ignored() + .recover_with(via_parser(value_recovery())) + .padded_by(whitespace_and_comments()), + ) + .allow_trailing() + .collect::>() + .map(DuperTuple) + .delimited_by( + just('(').padded_by(whitespace_and_comments()), + just(')').padded_by(whitespace_and_comments()), + ) + .or(just(',') + .padded_by(whitespace_and_comments()) + .delimited_by(just('('), just(')')) + .map(|_| DuperTuple(vec![]))) +} + +pub(crate) fn key_recovery<'a>() -> impl Parser<'a, &'a str, (), extra::Err>> + Clone +{ + choice((one_of('a'..='z'), one_of('A'..='Z'), one_of("_\""))).ignored() +} + +pub(crate) fn value_recovery<'a>() +-> impl Parser<'a, &'a str, (), extra::Err>> + Clone { + choice(( + one_of('0'..='9'), + one_of('A'..='Z'), + one_of(r#"_"brntf-+{[("#), + )) + .ignored() +} + pub(crate) fn quoted_string<'a>() -> impl Parser<'a, &'a str, Cow<'a, str>, extra::Err>> + Clone { quoted_inner() .delimited_by(just('"'), just('"')) - .map(unescape_str) - .unwrapped() + .try_map(|str, span| unescape_str(str).map_err(|err| Rich::custom(span, err))) } pub(crate) fn quoted_bytes<'a>() -> impl Parser<'a, &'a str, Cow<'a, [u8]>, extra::Err>> + Clone { quoted_inner() .delimited_by(just("b\""), just('"')) - .map(unescape_bytes) - .unwrapped() + .try_map(|bytes, span| unescape_bytes(bytes).map_err(|err| Rich::custom(span, err))) } pub(crate) fn quoted_inner<'a>() @@ -298,7 +308,7 @@ pub(crate) fn quoted_inner<'a>() just('x') .then( any() - .filter(|char: &char| char.is_digit(16)) + .filter(|char: &char| char.is_ascii_hexdigit()) .labelled("a hexadecimal digit") .repeated() .exactly(2), @@ -307,7 +317,7 @@ pub(crate) fn quoted_inner<'a>() just('u') .then( any() - .filter(|char: &char| char.is_digit(16)) + .filter(|char: &char| char.is_ascii_hexdigit()) .labelled("a hexadecimal digit") .repeated() .exactly(4), @@ -407,7 +417,14 @@ pub(crate) fn float<'a>() -> impl Parser<'a, &'a str, f64, extra::Err() -> impl Parser<'a, &'a str, f64, extra::Err() -> impl Parser<'a, &'a str, i64, extra::Err>> + Clone { @@ -429,23 +455,65 @@ pub(crate) fn integer<'a>() -> impl Parser<'a, &'a str, i64, extra::Err { fn default() -> Self { diff --git a/duper_website/docs/spec.md b/duper_website/docs/spec.md index fa02563..a94f3ae 100644 --- a/duper_website/docs/spec.md +++ b/duper_website/docs/spec.md @@ -1,5 +1,5 @@ --- -version: "0.2.1" +version: "0.3.0" ---

@@ -19,6 +19,7 @@ Duper aims to be a human-friendly extension of JSON with quality-of-life improve - Whitespace means tab (U+0009), space (U+0020), line feed (U+000A), or carriage return (U+000D). - Newline means line feed (U+000A) or carriage return (U+000D). - Files must have only one root value. Parsers must always accept objects, arrays, and tuples as the root value, but implementations may allow other values as the root value. +- JSON values are valid Duper values. ## Comments @@ -146,7 +147,7 @@ Defining a key multiple times is invalid. Note that plain keys, quoted keys, and A string may be either quoted or raw. -**Quoted strings** are surrounded by quotation marks `"`. Any Unicode character may be used, except those that must be escaped: quotation mark `"`, backslash `\`, and the control characters other than tab (U+0000 to U+0008, U+000A to U+001F, U+007F). +**Quoted strings** are surrounded by quotation marks `"`. Any Unicode character may be used, except those that must be escaped: quotation mark `"`, backslash `\`, and the control characters including tabs (U+0000 to U+0009, U+000A to U+001F, U+007F). ```duper { @@ -158,12 +159,12 @@ For convenience, some popular characters have a compact escape sequence: ```duper [ + r#" \0 - null (U+0000) "#, r#" \b - backspace (U+0008) "#, - r#" \f - form feed (U+000C) "#, + r#" \t - tab (U+0009) "#, r#" \n - line feed (U+000A) "#, + r#" \f - form feed (U+000C) "#, r#" \r - carriage return (U+000D) "#, - r#" \t - tab (U+0009) "#, - r#" \0 - null (U+0000) "#, r#" \" - quote (U+0022) "#, r#" \\ - backslash (U+005C) "#, r#" \xHH - arbitrary byte (U+00HH) "#, diff --git a/duper_website/src/lib.rs b/duper_website/src/lib.rs index fb9360a..9b205bb 100644 --- a/duper_website/src/lib.rs +++ b/duper_website/src/lib.rs @@ -27,7 +27,7 @@ impl TryFrom<&'_ str> for ConvertTo { "json" => Ok(Self::Json), "yaml" => Ok(Self::Yaml), "toml" => Ok(Self::Toml), - _ => Err(JsError::new(&format!("unknown "))), + _ => Err(JsError::new(&format!("unknown encoding {value}"))), } } } diff --git a/serde_duper/tests/basic.rs b/serde_duper/tests/basic.rs index 3882acc..cb8ff84 100644 --- a/serde_duper/tests/basic.rs +++ b/serde_duper/tests/basic.rs @@ -270,7 +270,7 @@ fn handle_enum_internally_tagged() { assert_eq!(map.get("duper"), Some(&true)); assert_eq!( serde_duper::to_string(&Test::Dup(map)).unwrap(), - // TODO: Find a way to fix this + // TO-DO: Find a way to fix this // r#"Test({type: "Dup", duper: true})"# r#"{type: "Dup", duper: true}"# );