Parse strings and booleans

This commit is contained in:
Araozu 2023-02-10 12:30:10 -05:00
parent 850ed4cdaf
commit 8aba492f15
3 changed files with 44 additions and 1 deletions

View File

@ -20,4 +20,6 @@ pub struct VarBinding<'a> {
pub enum Expression<'a> {
Number(&'a String),
String(&'a String),
Boolean(bool),
}

View File

@ -7,6 +7,12 @@ impl Transpilable for Expression<'_> {
Expression::Number(value) => {
String::from(*value)
}
Expression::String(value) => {
format!("\"{}\"", *value)
}
Expression::Boolean(value) => {
String::from(if *value {"true"} else {"false"})
}
}
}
}
@ -18,11 +24,28 @@ mod tests {
use crate::ast_types::Expression;
#[test]
fn number_should_transpile() {
fn should_transpile_number() {
let str = String::from("42");
let exp = Expression::Number(&str);
let result = exp.transpile();
assert_eq!("42", result);
}
#[test]
fn should_transpile_string() {
let str = String::from("Hello world");
let exp = Expression::String(&str);
let result = exp.transpile();
assert_eq!("\"Hello world\"", result);
}
#[test]
fn should_transpile_boolean() {
let exp = Expression::Boolean(true);
let result = exp.transpile();
assert_eq!("true", result);
}
}

View File

@ -10,6 +10,12 @@ pub fn try_parse(tokens: &Vec<Token>, pos: usize) -> Option<Expression> {
TokenType::Number => {
Some(Expression::Number(&token.value))
}
TokenType::String => {
Some(Expression::String(&token.value))
}
TokenType::Identifier if token.value == "true" || token.value == "false" => {
Some(Expression::Boolean(token.value == "true"))
}
_ => None
}
})
@ -28,6 +34,18 @@ mod tests {
match expression {
Expression::Number(value) => assert_eq!("40", value),
_ => panic!()
}
}
#[test]
fn should_parse_a_string() {
let tokens = get_tokens(&String::from("\"Hello\"")).unwrap();
let expression = try_parse(&tokens, 0).unwrap();
match expression {
Expression::String(value) => assert_eq!("Hello", value),
_ => panic!()
}
}
}