Parse strings and booleans
This commit is contained in:
parent
850ed4cdaf
commit
8aba492f15
@ -20,4 +20,6 @@ pub struct VarBinding<'a> {
|
||||
|
||||
pub enum Expression<'a> {
|
||||
Number(&'a String),
|
||||
String(&'a String),
|
||||
Boolean(bool),
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
@ -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!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user