From 2ad36af41d237f3fb4be4d8ed0c78cf227612ea3 Mon Sep 17 00:00:00 2001 From: Bryan Newbold Date: Sat, 23 Oct 2021 20:30:31 -0700 Subject: simplify s-expr enum, to make other parsing easier as well --- src/sexpr.rs | 41 ++++++++--------------------------------- 1 file changed, 8 insertions(+), 33 deletions(-) (limited to 'src/sexpr.rs') diff --git a/src/sexpr.rs b/src/sexpr.rs index da1012e..ea07bf9 100644 --- a/src/sexpr.rs +++ b/src/sexpr.rs @@ -16,23 +16,14 @@ use std::path::Path; //////////// Types and Constants -const SEXPR_BUILTINS: [&'static str; 15] = [ - "=", ">", ">=", "<", "<=", - "+", "-", "*", "/", "^", - "exp", "log", "sin", "cos", "tan", - ]; - #[derive(Clone, PartialEq)] pub enum SExpr { SNull, - STrue, - SFalse, + SBoolean(bool), SInteger(i64), SFloat(f64), - SBuiltin(String), - SSymbol(String), - SIdentifier(String), SString(String), + SIdentifier(String), SList(Vec), } @@ -130,23 +121,18 @@ fn sexpr_parse_token(token: &str) -> Result { // Is it a constant? match token { - "#t" => return Ok(SExpr::STrue), - "#f" => return Ok(SExpr::SFalse), + "#t" => return Ok(SExpr::SBoolean(true)), + "#f" => return Ok(SExpr::SBoolean(false)), _ => () } - // Is it a builtin? - if SEXPR_BUILTINS.contains(&token) { - return Ok(SExpr::SBuiltin(token.to_string())); - } - // Try to parse as an integer match token.parse::() { Ok(x) => return Ok(SExpr::SInteger(x)), Err(_) => () } - // Try to parse as a number + // Try to parse as floating-point number match token.parse::() { Ok(x) => return Ok(SExpr::SFloat(x)), Err(_) => () @@ -157,15 +143,6 @@ fn sexpr_parse_token(token: &str) -> Result { return Ok(SExpr::SString(token.to_string())); } - // Is it a quoted literal? - if token.starts_with("'") && token.len() > 1 { - match sexpr_parse_token(&token[1..]) { - Ok(SExpr::SIdentifier(t)) => return Ok(SExpr::SSymbol(t)), - Ok(e) => return Ok(e), - _ => {}, - } - } - // Else, we'll treat it as an identifier if is_valid_identifier(token) { return Ok(SExpr::SIdentifier(token.to_string())); @@ -232,14 +209,12 @@ pub fn sexpr_parse(tokens: &Vec<&str>, depth: u32) -> Result<(Vec, usize) */ pub fn sexpr_repr(ast: &SExpr) -> Result { return match ast { - &SExpr::STrue => Ok("#t".to_string()), - &SExpr::SFalse => Ok("#f".to_string()), - &SExpr::SNull => Ok("'()".to_string()), // TODO: just () ? + &SExpr::SNull => Ok("()".to_string()), + &SExpr::SBoolean(true) => Ok("#t".to_string()), + &SExpr::SBoolean(false) => Ok("#f".to_string()), &SExpr::SInteger(num) => Ok(format!("{}", num).to_string()), &SExpr::SFloat(num) => Ok(format!("{}", num).to_string()), - &SExpr::SBuiltin(ref b)=> Ok(b.clone()), &SExpr::SString(ref s)=> Ok(s.clone()), - &SExpr::SSymbol(ref s)=> Ok(s.clone()), &SExpr::SIdentifier(ref s)=> Ok(s.to_string()), &SExpr::SList(ref list) => { let elements: Vec = list.iter().map(|ref el| sexpr_repr(&el).unwrap()).collect(); -- cgit v1.2.3