From ff12918696181f1b0f2b8272944044e27c89e319 Mon Sep 17 00:00:00 2001 From: Nadrieril Date: Wed, 10 Apr 2019 19:18:25 +0200 Subject: Add a new Deserialize trait for reading dhall values --- dhall/src/lib.rs | 14 ++++++++++++++ dhall/src/traits.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) (limited to 'dhall') diff --git a/dhall/src/lib.rs b/dhall/src/lib.rs index 3bfc46f..b49d1c1 100644 --- a/dhall/src/lib.rs +++ b/dhall/src/lib.rs @@ -21,7 +21,21 @@ mod imports; mod normalize; mod traits; mod typecheck; +pub use crate::traits::Deserialize; pub use crate::traits::SimpleStaticType; pub use crate::traits::StaticType; pub use dhall_generator::SimpleStaticType; pub mod expr; + +pub fn from_str<'a, T: Deserialize<'a>>( + s: &'a str, + ty: Option<&crate::expr::Type>, +) -> crate::traits::Result { + T::from_str(s, ty) +} + +pub fn from_str_auto_type<'a, T: Deserialize<'a> + StaticType>( + s: &'a str, +) -> crate::traits::Result { + from_str(s, Some(&::get_static_type())) +} diff --git a/dhall/src/traits.rs b/dhall/src/traits.rs index 4925457..370632e 100644 --- a/dhall/src/traits.rs +++ b/dhall/src/traits.rs @@ -19,6 +19,56 @@ pub trait SimpleStaticType { fn get_simple_static_type() -> SimpleType; } +pub type Error = (); +pub type Result = std::result::Result; + +pub trait Deserialize<'a>: Sized { + fn from_str(s: &'a str, ty: Option<&Type>) -> Result; +} + +impl<'a> Deserialize<'a> for Parsed { + /// Simply parses the provided string. Ignores the + /// provided type. + fn from_str(s: &'a str, _ty: Option<&Type>) -> Result { + Ok(Parsed::parse_str(s).map_err(|_| ())?) + } +} + +impl<'a> Deserialize<'a> for Resolved { + /// Parses and resolves the provided string. Ignores the + /// provided type. + fn from_str(s: &'a str, ty: Option<&Type>) -> Result { + Ok(Parsed::from_str(s, ty)? + .resolve() + .map_err(|_| ())? + ) + } +} + +impl<'a> Deserialize<'a> for Typed { + /// Parses, resolves and typechecks the provided string. + fn from_str(s: &'a str, ty: Option<&Type>) -> Result { + // TODO: compare with provided type + Ok(Resolved::from_str(s, ty)? + .typecheck() + .map_err(|_| ())? + ) + } +} + +impl<'a> Deserialize<'a> for Normalized { + /// Parses, resolves, typechecks and normalizes the provided string. + fn from_str(s: &'a str, ty: Option<&Type>) -> Result { + Ok(Typed::from_str(s, ty)?.normalize()) + } +} + +impl<'a> Deserialize<'a> for Type { + fn from_str(s: &'a str, ty: Option<&Type>) -> Result { + Ok(Normalized::from_str(s, ty)?.into_type()) + } +} + fn mktype(x: SubExpr) -> SimpleType { SimpleType(x) } -- cgit v1.2.3