109 lines
2.5 KiB
Rust
109 lines
2.5 KiB
Rust
use std::num::ParseIntError;
|
|
|
|
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
|
pub struct Expression {
|
|
pub expr: String,
|
|
pub value: Value,
|
|
}
|
|
|
|
impl From<&str> for Expression {
|
|
fn from(value: &str) -> Self {
|
|
Self {
|
|
expr: value.to_string(),
|
|
value: Value::String(value.to_string()),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Default, Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
|
|
pub enum Value {
|
|
List(Vec<Value>),
|
|
String(String),
|
|
Number(i64),
|
|
#[default]
|
|
Nil,
|
|
Function,
|
|
True,
|
|
Symbol(Symbol),
|
|
Keyword(Keyword),
|
|
}
|
|
|
|
impl Value {
|
|
fn parse(str: &str) -> Self {
|
|
match str {
|
|
"a" => Self::Symbol(Symbol::from(str)),
|
|
_ => Self::Nil,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<Vec<Value>> for Value {
|
|
fn from(values: Vec<Value>) -> Self {
|
|
Value::List(values)
|
|
}
|
|
}
|
|
|
|
impl From<&str> for Value {
|
|
fn from(s: &str) -> Self {
|
|
let s = s.to_string();
|
|
if let Ok(parse_result) = s.parse::<i64>() {
|
|
Value::Number(parse_result)
|
|
} else if let Some(s) = s.strip_prefix(":") {
|
|
Value::Keyword(Keyword(s.to_string()))
|
|
} else if s == "t".to_owned() {
|
|
Value::True
|
|
} else if s.starts_with(r#"""#) {
|
|
Value::String(s.replace('"', ""))
|
|
} else if s == "fn".to_owned() {
|
|
Value::Function
|
|
} else if s == "defun".to_owned() {
|
|
Value::Function
|
|
} else if s == "nil".to_owned() {
|
|
Value::Nil
|
|
} else {
|
|
Value::Symbol(Symbol(s))
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<String> for Value {
|
|
fn from(str: String) -> Self {
|
|
Self::from(str.as_str())
|
|
}
|
|
}
|
|
|
|
impl From<&String> for Value {
|
|
fn from(str: &String) -> Self {
|
|
Self::from(str.as_str())
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
pub struct Symbol(pub String);
|
|
|
|
impl From<&str> for Symbol {
|
|
fn from(s: &str) -> Self {
|
|
Symbol(String::from(s))
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Display for Symbol {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
std::fmt::Display::fmt(&self.0, f)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
pub struct Keyword(pub String);
|
|
|
|
impl From<&str> for Keyword {
|
|
fn from(s: &str) -> Self {
|
|
Keyword(String::from(s))
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Display for Keyword {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
std::fmt::Display::fmt(&self.0, f)
|
|
}
|
|
}
|