From 3eb53c36123c4a8a8f336c255a9d5a7b44ca922c Mon Sep 17 00:00:00 2001 From: Dominick Allen Date: Sun, 28 Jun 2020 19:50:11 -0500 Subject: Implement Display for Type and SExpr. --- src/lib/sexpr.rs | 11 +++++++++++ src/lib/types.rs | 37 +++++++++++++++++++++++++++++++++---- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/src/lib/sexpr.rs b/src/lib/sexpr.rs index a6fbe49..6956b9b 100644 --- a/src/lib/sexpr.rs +++ b/src/lib/sexpr.rs @@ -1,3 +1,5 @@ +use std::fmt; + use super::types::Type; #[derive(PartialEq, Debug)] @@ -6,6 +8,15 @@ pub enum SExpr { Sexpr(Vec) } +impl fmt::Display for SExpr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + SExpr::Atom(ref t) => write!(f, "{}", t), + SExpr::Sexpr(ref s) => write!(f, "{:?}", s) + } + } +} + #[test] fn construct() { let atom1 = SExpr::Atom(Type::Number(Number::Int(1))); diff --git a/src/lib/types.rs b/src/lib/types.rs index 7755c04..6b17b26 100644 --- a/src/lib/types.rs +++ b/src/lib/types.rs @@ -1,4 +1,5 @@ use std::str::FromStr; +use std::fmt; #[derive(PartialEq, Debug, Clone, Copy)] pub enum Op { @@ -12,7 +13,23 @@ pub enum Op { GrEqTo, Less, LsEqTo, - Define, +} + +impl fmt::Display for Op { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + &Op::Add => write!(f, "+"), + &Op::Sub => write!(f, "-"), + &Op::Mul => write!(f, "*"), + &Op::Div => write!(f, "/"), + &Op::Modulo => write!(f, "%"), + &Op::Equals => write!(f, "="), + &Op::Greater => write!(f, ">"), + &Op::GrEqTo => write!(f, ">="), + &Op::Less => write!(f, "<"), + &Op::LsEqTo => write!(f, "<="), + } + } } impl FromStr for Op { @@ -30,16 +47,17 @@ impl FromStr for Op { ">=" => Ok(Op::GrEqTo), "<" => Ok(Op::Less), "<=" => Ok(Op::LsEqTo), - "define" => Ok(Op::Define), x => Err(format!("{} is not an operator", x)) } } } +pub type FloatType = f64; + #[derive(PartialEq, Debug, Clone)] pub enum Number { Int(isize), - Float(f32) + Float(FloatType) } #[derive(PartialEq, Debug, Clone)] @@ -51,4 +69,15 @@ pub enum Type { Operator(Op), } - +impl fmt::Display for Type { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Type::Bool(b) => write!(f, "{}", b), + Type::Number(Number::Int(n)) => write!(f, "{}", n), + Type::Number(Number::Float(n)) => write!(f, "{}", n), + Type::Str(s) => write!(f, "{}", s), + Type::Symbol(s) => write!(f, "{}", s), + Type::Operator(op) => write!(f, "{}", op) + } + } +} -- cgit v1.2.3