From 36a6f9a09b966922baf4838599e57250982b0fc3 Mon Sep 17 00:00:00 2001 From: Nadrieril Date: Thu, 11 Apr 2019 15:15:20 +0200 Subject: Abstract get_type() into a trait --- dhall/src/traits/dynamic_type.rs | 56 ++++++++++++++++++++++++++++++++++++++++ dhall/src/traits/mod.rs | 2 ++ 2 files changed, 58 insertions(+) create mode 100644 dhall/src/traits/dynamic_type.rs (limited to 'dhall/src/traits') diff --git a/dhall/src/traits/dynamic_type.rs b/dhall/src/traits/dynamic_type.rs new file mode 100644 index 0000000..25fe52d --- /dev/null +++ b/dhall/src/traits/dynamic_type.rs @@ -0,0 +1,56 @@ +use crate::expr::*; +use crate::traits::StaticType; +use crate::typecheck::{TypeError, TypeMessage}; +use dhall_core::context::Context; +use dhall_core::{Const, ExprF, X}; +use std::borrow::Cow; + +pub trait DynamicType { + fn get_type<'a>(&'a self) -> Result, TypeError>; +} + +impl DynamicType for T { + fn get_type<'a>(&'a self) -> Result, TypeError> { + Ok(Cow::Owned(T::get_static_type())) + } +} + +impl DynamicType for Type { + fn get_type(&self) -> Result, TypeError> { + use TypeInternal::*; + match &self.0 { + Expr(e) => e.get_type(), + SuperType => Err(TypeError::new( + &Context::new(), + dhall_core::rc(ExprF::Const(Const::Sort)), + TypeMessage::Untyped, + )), + } + } +} + +impl DynamicType for Normalized { + fn get_type(&self) -> Result, TypeError> { + match &self.1 { + Some(t) => Ok(Cow::Borrowed(t)), + None => Err(TypeError::new( + &Context::new(), + self.0.clone(), + TypeMessage::Untyped, + )), + } + } +} + +impl DynamicType for Typed { + fn get_type(&self) -> Result, TypeError> { + match &self.1 { + Some(t) => Ok(Cow::Borrowed(t)), + None => Err(TypeError::new( + &Context::new(), + self.0.clone(), + TypeMessage::Untyped, + )), + } + } +} diff --git a/dhall/src/traits/mod.rs b/dhall/src/traits/mod.rs index 4ce8f97..315e17a 100644 --- a/dhall/src/traits/mod.rs +++ b/dhall/src/traits/mod.rs @@ -1,4 +1,6 @@ mod deserialize; +mod dynamic_type; mod static_type; pub use deserialize::Deserialize; +pub use dynamic_type::DynamicType; pub use static_type::{SimpleStaticType, StaticType}; -- cgit v1.2.3