diff --git a/src/ast/build.rs b/src/ast/build.rs index c3847a3..569f4a8 100644 --- a/src/ast/build.rs +++ b/src/ast/build.rs @@ -1,6 +1,7 @@ use crate::ast::*; use crate::parser::Rule; use pest::iterators::{Pair, Pairs}; +use std::str::FromStr; fn expect_and_use( file_id: usize, @@ -1227,7 +1228,27 @@ fn build_literal(file_id: usize, literal_pair: Pair) -> Literal { } fn build_number_literal(file_id: usize, pair: Pair) -> Literal { - todo!() + let inner_pair = pair.into_inner().next().unwrap(); + match inner_pair.as_rule() { + Rule::DoubleLiteral => build_double_literal(file_id, inner_pair), + Rule::LongLiteral => build_long_literal(file_id, inner_pair), + Rule::IntLiteral => build_int_literal(file_id, inner_pair), + _ => unreachable!(), + } +} + +fn build_double_literal(file_id: usize, inner_pair: Pair) -> Literal { + Literal::Double(f64::from_str(&inner_pair.as_str()).unwrap()) +} + +fn build_long_literal(file_id: usize, inner_pair: Pair) -> Literal { + let as_string = inner_pair.as_str(); + let without_el = &as_string[0..(as_string.len() - 1)]; + Literal::Long(i64::from_str(without_el).unwrap()) +} + +fn build_int_literal(file_id: usize, inner_pair: Pair) -> Literal { + Literal::Integer(i32::from_str(&inner_pair.as_str()).unwrap()) } fn build_string_literal(file_id: usize, pair: Pair) -> Literal { @@ -1265,15 +1286,16 @@ fn build_backtick_string(file_id: usize, pair: Pair) -> Literal { #[cfg(test)] mod tests { use super::*; + use crate::ast::pretty_print::PrettyPrint; use crate::parser::DeimosParser; use indoc::indoc; - fn assert_builds(src: &str) { + fn assert_builds(src: &str) -> CompilationUnit { let parse_result = DeimosParser::parse(Rule::CompilationUnit, src); if let Err(e) = parse_result { panic!("Parsing failed.\n{}", e) } else { - build_ast(0, parse_result.unwrap().next().unwrap()); + build_ast(0, parse_result.unwrap().next().unwrap()) } } @@ -1283,15 +1305,30 @@ mod tests { fn main() { let x = foo[a]; } - "}) + "}); } #[test] fn object_index_and_call() { - assert_builds(indoc! {"\ + assert_builds(indoc! {" fn main() { a[b]().c() } - "}) + "}); + } + + #[test] + fn int_literal() { + assert_builds("fn main() { 0 }"); + } + + #[test] + fn long_literal() { + assert_builds("fn main() { 1L }"); + } + + #[test] + fn double_literal() { + assert_builds("fn main() { 1.0 }"); } }