#![deny(unsafe_code)]
use super::decl::{self, ident, is_ident_char, word};
use super::java::{balanced, lex};
use super::{Kind, Symbol};
const MODIFIERS: [&str; 12] = [
"public", "private", "protected", "static", "final", "abstract", "default", "native",
"synchronized", "transient", "volatile", "strictfp",
];
pub fn symbols(src: &str) -> Option<Vec<Symbol>> {
decl::symbols(src, lex, balanced, recognise)
}
fn recognise(line: &str, _raw: &str) -> Option<(Kind, String)> {
let trimmed = line.trim_start();
for (kw, kind) in [("package", Kind::Mod), ("import", Kind::Import)] {
if let Some(rest) = word(trimmed, kw) {
let name = rest.trim().trim_end_matches(';').trim();
let name = word(name, "static").unwrap_or(name);
return Some((kind, name.to_string()));
}
}
let rest = strip_modifiers(trimmed);
for (kw, kind) in [
("class", Kind::Class),
("interface", Kind::Interface),
("record", Kind::Class),
("enum", Kind::Type),
("@interface", Kind::Interface),
] {
if let Some(after) = word(rest, kw) {
return Some((kind, ident(after)));
}
}
method(rest)
}
fn method(rest: &str) -> Option<(Kind, String)> {
let open = rest.find('(')?;
let head = rest[..open].trim_end();
let name = tail_ident(head)?;
if name.is_empty() {
return None;
}
if matches!(
name.as_str(),
"if" | "for" | "while" | "switch" | "catch" | "return" | "new" | "super" | "this"
) {
return None;
}
let before = head[..head.len() - name.len()].trim_end();
let opens_body = rest[open..].contains('{') || rest.trim_end().ends_with(';');
match before.is_empty() && !opens_body {
true => None,
false => Some((Kind::Func, name)),
}
}
fn tail_ident(s: &str) -> Option<String> {
let s = s.trim_end();
let start = s
.char_indices()
.rev()
.take_while(|(_, c)| is_ident_char(*c))
.last()
.map(|(i, _)| i)?;
Some(s[start..].to_string())
}
fn strip_modifiers(line: &str) -> &str {
let mut rest = line;
loop {
if rest.starts_with('@') {
let cut = rest.find(char::is_whitespace).unwrap_or(rest.len());
rest = rest[cut..].trim_start();
continue;
}
if rest.starts_with('<') {
match rest.find('>') {
Some(i) => {
rest = rest[i + 1..].trim_start();
continue;
}
None => return rest,
}
}
match MODIFIERS.iter().find_map(|m| word(rest, m)) {
Some(r) => rest = r,
None => return rest,
}
}
}
#[cfg(test)]
#[path = "java_decl_tests.rs"]
mod tests;