Implement parsing and evaluation of boolean expressions

This commit is contained in:
Jeff 2024-08-07 10:50:19 -04:00
parent 692f1145cd
commit 5d01f1caf9
3 changed files with 34 additions and 30 deletions

View File

@ -124,7 +124,7 @@ impl<'a> Lexer<'a> {
self.source[self.position..].chars().nth(1) self.source[self.position..].chars().nth(1)
} }
fn peek_until_whitespace(&self) -> Option<&str> { fn _peek_until_whitespace(&self) -> Option<&str> {
let start = self.position; let start = self.position;
let end = self.source[self.position..] let end = self.source[self.position..]
.find(char::is_whitespace) .find(char::is_whitespace)

View File

@ -105,6 +105,14 @@ impl<'src> Parser<'src> {
fn parse_primary(&mut self) -> Result<Node, ParseError> { fn parse_primary(&mut self) -> Result<Node, ParseError> {
match self.current.clone() { match self.current.clone() {
(Token::Boolean(boolean), span) => {
self.next_token()?;
Ok(Node::new(
Statement::Constant(Value::boolean(boolean)),
span,
))
}
(Token::Float(float), span) => { (Token::Float(float), span) => {
self.next_token()?; self.next_token()?;
@ -213,6 +221,16 @@ mod tests {
use super::*; use super::*;
#[test]
fn boolean() {
let input = "true";
assert_eq!(
parse(input),
Ok([Node::new(Statement::Constant(Value::boolean(true)), (0, 4))].into())
);
}
#[test] #[test]
fn list_access() { fn list_access() {
let input = "[1, 2, 3].0"; let input = "[1, 2, 3].0";

View File

@ -144,16 +144,6 @@ impl Vm {
}); });
} }
} }
_ => {
return Err(VmError::ExpectedDifferentReservedIdentifier {
position: right_span,
expected: vec![
ReservedIdentifier::IsEven,
ReservedIdentifier::IsOdd,
ReservedIdentifier::Length,
],
})
}
} }
} }
@ -181,25 +171,11 @@ pub enum VmError {
// Anaylsis Failures // Anaylsis Failures
// These should be prevented by running the analyzer before the VM // These should be prevented by running the analyzer before the VM
ExpectedIdentifier { ExpectedIdentifier { position: Span },
position: Span, ExpectedIdentifierOrInteger { position: Span },
}, ExpectedInteger { position: Span },
ExpectedIdentifierOrInteger { ExpectedList { position: Span },
position: Span, ExpectedValue { position: Span },
},
ExpectedInteger {
position: Span,
},
ExpectedList {
position: Span,
},
ExpectedDifferentReservedIdentifier {
position: Span,
expected: Vec<ReservedIdentifier>,
},
ExpectedValue {
position: Span,
},
} }
impl From<ParseError> for VmError { impl From<ParseError> for VmError {
@ -218,6 +194,16 @@ impl From<ValueError> for VmError {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn boolean() {
let input = "true";
assert_eq!(
run(input, &mut HashMap::new()),
Ok(Some(Value::boolean(true)))
);
}
#[test] #[test]
fn is_even() { fn is_even() {
let input = "42.is_even"; let input = "42.is_even";