[parser, types] Clean up obj parsers

- Define ListParser, SymParser in their own separate modules
- Add some stuff to types to make working with them more ergonomic
This commit is contained in:
Eryn Wells 2018-08-23 17:52:56 -07:00
parent b6a9b8a855
commit 929846152e
8 changed files with 129 additions and 56 deletions

View file

@ -2,18 +2,28 @@
* Eryn Wells <eryn@erynwells.me>
*/
use object::Object;
use predicates::IsBool;
use std::fmt;
use object::Obj;
use preds;
impl IsBool for Object {
fn is_bool(&self) -> bool {
match *self {
Object::Bool(_) => true,
_ => false,
/// The Scheme boolean type. It can be `True` or `False`.
pub enum Bool { True, False }
impl Obj for Bool { }
impl fmt::Display for Bool {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Bool::True => write!(f, "#t"),
Bool::False => write!(f, "#f")
}
}
}
impl preds::IsBool for Bool {
fn is_bool(&self) -> bool { true }
}
#[cfg(test)]
mod tests {
use object::Object;

View file

@ -23,7 +23,8 @@ pub enum Obj {
}
pub trait Object:
fmt::Display
fmt::Debug +
fmt::Display
{
fn as_any(&self) -> &Any;
fn as_pair(&self) -> Option<&Pair>;
@ -31,6 +32,10 @@ pub trait Object:
}
impl Obj {
pub fn new<T: 'static + Object>(obj: T) -> Obj {
Obj::Ptr(Box::new(obj))
}
pub fn unbox_as<T: 'static + Object>(&self) -> Option<&T> {
match self {
Obj::Null => None,
@ -48,6 +53,12 @@ impl fmt::Display for Obj {
}
}
impl fmt::Debug for Obj {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
//#[derive(Debug, PartialEq)]
//pub enum Object {
// ByteVector(Vec<u8>),

View file

@ -13,6 +13,10 @@ pub struct Pair {
}
impl Pair {
pub fn empty() -> Pair {
Pair { car: Obj::Null, cdr: Obj::Null }
}
fn fmt_pair(&self, f: &mut fmt::Formatter) -> fmt::Result {
let r = write!(f, "{}", self.car);
r.and_then(|r| match self.cdr {
@ -39,3 +43,9 @@ impl fmt::Display for Pair {
.and_then(|_| write!(f, ")"))
}
}
impl fmt::Debug for Pair {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}

View file

@ -9,6 +9,12 @@ use super::*;
pub struct Sym(String);
impl Sym {
pub fn new(value: String) -> Sym {
Sym(value)
}
}
impl Object for Sym {
fn as_any(&self) -> &Any { self }
fn as_pair(&self) -> Option<&Pair> { None }
@ -20,3 +26,9 @@ impl fmt::Display for Sym {
write!(f, "{}", self.0)
}
}
impl fmt::Debug for Sym {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}