Skip to content

Commit

Permalink
feat: java/parser: 🎉 initial java class parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
plastic-karma committed Oct 10, 2024
1 parent 0ba7c76 commit 17e4806
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/code/java/parser/mod.rs
Original file line number Diff line number Diff line change
@@ -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<Token>) -> 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<std::slice::Iter<'_, Token>>) -> 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<Class>

}

struct Class {
name: String
}

impl CompilationUnit {
fn new() -> Self {
CompilationUnit { classes: Vec::new() }
}
}
31 changes: 31 additions & 0 deletions src/code/java/parser/tests.rs
Original file line number Diff line number Diff line change
@@ -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);
}

}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod code {
pub mod java {
pub mod tokenizer;
pub mod parser;
}
}

Expand Down

0 comments on commit 17e4806

Please sign in to comment.