Skip to content

Commit

Permalink
Add check on parenthesis balancing
Browse files Browse the repository at this point in the history
  • Loading branch information
cowuake committed Jul 7, 2024
1 parent 9087a0d commit 6c9352a
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions schemius/src/core/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,30 @@ lazy_static! {
}

pub fn read(line: &mut String) -> Result<SExpr, String> {
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();

Expand Down Expand Up @@ -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());
}
}

0 comments on commit 6c9352a

Please sign in to comment.