loc-rs 0.2.4

Advanced Lines of Code counter with function extraction, git integration, and parallel processing
// Author: kelexine (https://github.com/kelexine)
// extractors/java.rs — Java/Kotlin/C# function extraction via Tree-sitter

use super::{estimate_complexity, Extractor};
use crate::models::FunctionInfo;
use tree_sitter::Node;

pub struct JavaExtractor;

impl Extractor for JavaExtractor {
    fn extract(&self, content: &str) -> Vec<FunctionInfo> {
        super::with_parsed_tree(tree_sitter_java::LANGUAGE.into(), content, |tree| {
            let lines: Vec<&str> = content.lines().collect();
            let mut functions = Vec::new();
            traverse(tree.root_node(), content, &lines, &mut functions, false);
            functions.sort_by_key(|f| f.line_start);
            functions
        })
        .unwrap_or_default()
    }
}

fn traverse(
    node: Node,
    content: &str,
    lines: &[&str],
    functions: &mut Vec<FunctionInfo>,
    in_class: bool,
) {
    let kind = node.kind();

    if kind == "method_declaration" || kind == "constructor_declaration" {
        if let Some(info) = parse_method(node, content, lines, in_class) {
            functions.push(info);
        }
    } else if (kind == "class_declaration"
        || kind == "record_declaration"
        || kind == "interface_declaration")
        && let Some(info) = parse_class(node, content, lines)
    {
        functions.push(info);
    }

    let is_class_body = kind == "class_body";

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        traverse(child, content, lines, functions, in_class || is_class_body);
    }
}

fn parse_method(
    node: Node,
    content: &str,
    lines: &[&str],
    is_method: bool,
) -> Option<FunctionInfo> {
    let mut name = String::new();
    let mut params_str = String::new();

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        let kind = child.kind();
        if kind == "identifier" && name.is_empty() {
            name = child.utf8_text(content.as_bytes()).unwrap_or("").to_string();
        } else if kind == "formal_parameters" {
            params_str = child.utf8_text(content.as_bytes()).unwrap_or("").to_string();
        }
    }

    if name.is_empty() {
        return None;
    }

    let start_line = node.start_position().row + 1;
    let end_line = node.end_position().row + 1;

    let block = &lines[start_line.saturating_sub(1)..end_line.min(lines.len())];
    let complexity = estimate_complexity(block);

    let mut parameters = Vec::new();
    let trimmed_params = params_str.trim_start_matches('(').trim_end_matches(')');
    if !trimmed_params.is_empty() {
        for p in trimmed_params.split(',') {
            let p_trim = p.trim();
            if !p_trim.is_empty() {
                parameters.push(p_trim.to_string());
            }
        }
    }

    Some(FunctionInfo {
        name,
        line_start: start_line,
        line_end: end_line,
        parameters,
        is_async: false,
        is_method,
        is_class: false,
        docstring: None,
        decorators: vec![],
        complexity,
    })
}

fn parse_class(node: Node, content: &str, _lines: &[&str]) -> Option<FunctionInfo> {
    let mut name = String::new();

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "identifier" && name.is_empty() {
            name = child.utf8_text(content.as_bytes()).unwrap_or("").to_string();
            break;
        }
    }

    if name.is_empty() {
        name = "?".to_string();
    }

    let start_line = node.start_position().row + 1;
    let end_line = node.end_position().row + 1;

    Some(FunctionInfo {
        name,
        line_start: start_line,
        line_end: end_line,
        parameters: vec![],
        is_async: false,
        is_method: false,
        is_class: true,
        docstring: None,
        decorators: vec![],
        complexity: 1,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_java_functions() {
        let content = r#"
public class Main {
    public static void main(String[] args) {}
    private int calc(int a, int b) { return a + b; }
}
"#;
        let extractor = JavaExtractor;
        let mut fns = extractor.extract(content);
        fns.sort_by(|a, b| a.name.cmp(&b.name));

        assert_eq!(fns.len(), 3);

        let c = fns.iter().find(|f| f.name == "Main").unwrap();
        assert!(c.is_class);

        let m = fns.iter().find(|f| f.name == "main").unwrap();
        assert!(m.is_method);
        assert_eq!(m.parameters, vec!["String[] args"]);

        let calc = fns.iter().find(|f| f.name == "calc").unwrap();
        assert!(calc.is_method);
        assert_eq!(calc.parameters, vec!["int a", "int b"]);
    }
}