From 17e48062aa4c7e5298931abd1d2cc876f5fe7e78 Mon Sep 17 00:00:00 2001 From: Benjamin Rogge Date: Thu, 10 Oct 2024 15:30:26 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20java/parser:=20=F0=9F=8E=89=20initial?= =?UTF-8?q?=20java=20class=20parsing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/code/java/parser/mod.rs | 45 +++++++++++++++++++++++++++++++++++ src/code/java/parser/tests.rs | 31 ++++++++++++++++++++++++ src/main.rs | 1 + 3 files changed, 77 insertions(+) create mode 100644 src/code/java/parser/mod.rs create mode 100644 src/code/java/parser/tests.rs diff --git a/src/code/java/parser/mod.rs b/src/code/java/parser/mod.rs new file mode 100644 index 0000000..5607a62 --- /dev/null +++ b/src/code/java/parser/mod.rs @@ -0,0 +1,45 @@ +use std::iter::Peekable; + +use crate::code::java::tokenizer::Token; +use crate::code::java::tokenizer::TokenType::{Keyword, Identifier}; + +#[cfg(test)] +mod tests; + +fn parse(tokens: &Vec) -> CompilationUnit { + let mut iter = tokens.iter().peekable(); + let mut compilation_unit = CompilationUnit::new(); + while let Some(token) = iter.next() { + if let Keyword = token.token_type { + if token.value == "class" { + compilation_unit.classes.push(parse_class(&mut iter)); + } + } + } + compilation_unit + +} + +fn parse_class(iter: &mut Peekable>) -> Class { + if let Some(token) = iter.next() { + if token.token_type == Identifier { + return Class { name: token.value.clone() }; + } + } + panic!("Expected identifier after class keyword"); +} + +struct CompilationUnit { + classes: Vec + +} + +struct Class { + name: String +} + +impl CompilationUnit { + fn new() -> Self { + CompilationUnit { classes: Vec::new() } + } +} diff --git a/src/code/java/parser/tests.rs b/src/code/java/parser/tests.rs new file mode 100644 index 0000000..9f26003 --- /dev/null +++ b/src/code/java/parser/tests.rs @@ -0,0 +1,31 @@ +#[cfg(test)] +mod tests { + use crate::code::java::parser::parse; + use crate::code::java::tokenizer::tokenize; + + + #[test] + fn test_parse_class() { + let tokens = tokenize(r#" + import java.util.List; + class Test { + int i = 3; + }"#); + let compilation_unit = parse(&tokens); + + assert_eq!(compilation_unit.classes.len(), 1); + assert!(compilation_unit.classes.iter().any(|class| class.name == "Test")); + } + + #[test] + #[should_panic(expected = "Expected identifier after class keyword")] + fn test_parse_bad_class() { + let tokens = tokenize(r#" + import java.util.List; + class return { + int i = 3; + }"#); + let compilation_unit = parse(&tokens); + } + +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 9b63401..92ba1ad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ mod code { pub mod java { pub mod tokenizer; + pub mod parser; } }