From 6c9352a4a7cd830c0368b513dd997c1667250691 Mon Sep 17 00:00:00 2001 From: cowuake Date: Sun, 7 Jul 2024 17:16:51 +0200 Subject: [PATCH] Add check on parenthesis balancing --- schemius/src/core/reader.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/schemius/src/core/reader.rs b/schemius/src/core/reader.rs index 4f2c03a..ed25bfe 100644 --- a/schemius/src/core/reader.rs +++ b/schemius/src/core/reader.rs @@ -16,10 +16,30 @@ lazy_static! { } pub fn read(line: &mut String) -> Result { + if !has_balanced_parentheses(line) { + return Err("Exception: Invalid syntax: Unbalanced parentheses.".to_string()); + } + let first_token = init(line); advance(line, &first_token) } +fn has_balanced_parentheses(s: &str) -> bool { + let mut balance = 0; + for c in s.chars() { + match c { + '(' | '[' => balance += 1, + ')' | ']' => balance -= 1, + _ => {} + } + if balance < 0 { + // If balance is negative, there are more ')' than '(' at some point. + return false; + } + } + balance == 0 // True if balanced, false otherwise. +} + fn init(line: &mut String) -> String { let current_line: String = line.clone(); @@ -221,3 +241,20 @@ fn parse_polar_complex(token: &str) -> SExpr { SExpr::Number(SNumber::Complex(NativeComplex::from_polar(magnitude, angle))) } + +#[cfg(test)] +mod tests { + #[test] + fn test_read() { + let mut line = "(+ 1 2)".to_string(); + let res = super::read(&mut line); + assert!(res.is_ok()); + } + + #[test] + fn test_read_unbalanced_parentheses() { + let mut line = "(+ 1 2".to_string(); + let res = super::read(&mut line); + assert!(res.is_err()); + } +}