#![deny(unsafe_code)]
use super::scan::{blank, Span};
use super::{disambiguate, Kind, Symbol};
pub type Recognise = fn(&str, &str) -> Option<(Kind, String)>;
pub fn is_container(kind: Kind) -> bool {
matches!(
kind,
Kind::Impl | Kind::Trait | Kind::Class | Kind::Interface
)
}
pub fn symbols(
src: &str,
lex: fn(&str) -> Vec<Span>,
balanced: fn(&str, &[Span]) -> bool,
recognise: Recognise,
) -> Option<Vec<Symbol>> {
let toks = lex(src);
if !balanced(src, &toks) {
return None;
}
let blanked = blank(src, &toks);
let lines: Vec<&str> = blanked.lines().collect();
let raw: Vec<&str> = src.lines().collect();
let depths = depths(&lines);
let mut out: Vec<Symbol> = Vec::new();
let mut container: Option<(String, i32)> = None;
let mut sig_until = 0usize;
for i in 0..lines.len() {
if let Some((_, d)) = &container {
if depths[i] <= *d {
container = None;
}
}
if i < sig_until {
continue;
}
let depth = depths[i];
if depth > 1 || (depth == 1 && container.is_none()) {
continue;
}
let Some((kind, name)) = recognise(lines[i], raw.get(i).copied().unwrap_or("")) else {
continue;
};
if name.is_empty() {
continue;
}
let (sig_end, body) = extent(&lines, &depths, i);
sig_until = sig_end;
let path = match &container {
Some((c, _)) if !c.is_empty() => format!("{c}::{name}"),
_ => name.clone(),
};
if is_container(kind) {
container = Some((name.clone(), depth));
}
out.push(Symbol {
kind,
name,
path,
depth: (depth == 1) as u8,
doc: doc_above(&raw, i),
sig: (i, sig_end),
body,
});
}
disambiguate(&mut out);
Some(out)
}
pub fn depths(lines: &[&str]) -> Vec<i32> {
let mut out = Vec::with_capacity(lines.len());
let mut d = 0i32;
for l in lines {
out.push(d);
for b in l.bytes() {
match b {
b'{' => d += 1,
b'}' => d -= 1,
_ => {}
}
}
}
out
}
pub fn extent(lines: &[&str], _depths: &[i32], i: usize) -> (usize, (usize, usize)) {
let mut depth = 0i32;
let mut opener: Option<usize> = None;
let mut first_open: Option<usize> = None;
for (n, line) in lines.iter().enumerate().skip(i) {
for b in line.bytes() {
match b {
b'{' => {
if depth == 0 && opener.is_none() {
opener = Some(n);
}
depth += 1;
}
b'(' | b'[' => depth += 1,
b'}' | b')' | b']' => depth -= 1,
_ => {}
}
if depth > 0 && first_open.is_none() {
first_open = Some(n);
}
}
if depth > 0 {
continue;
}
if let Some(o) = opener {
return (o + 1, (o + 1, n + 1));
}
if line.contains(';') {
return match first_open {
Some(f) if f < n => (f + 1, (f + 1, n + 1)),
_ => (n + 1, (n + 1, n + 1)),
};
}
}
(i + 1, (i + 1, i + 1))
}
pub fn doc_above(raw: &[&str], i: usize) -> (usize, usize) {
let mut start = i;
while start > 0 {
let prev = raw[start - 1].trim_start();
let is_doc = prev.starts_with("//")
|| prev.starts_with('#')
|| prev.starts_with("/*")
|| prev.starts_with('*')
|| prev.starts_with('@'); if !is_doc {
break;
}
start -= 1;
}
(start, i)
}
pub fn word<'a>(s: &'a str, kw: &str) -> Option<&'a str> {
starts_word(s, kw).then(|| s[kw.len()..].trim_start())
}
pub fn starts_word(s: &str, kw: &str) -> bool {
s.starts_with(kw) && !s[kw.len()..].starts_with(is_ident_char)
}
pub fn is_ident_char(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
pub fn ident(s: &str) -> String {
let s = s.trim_start();
let end = s.find(|c: char| !is_ident_char(c)).unwrap_or(s.len());
s[..end].to_string()
}
pub type Block = (usize, usize, usize);
pub fn blocks(lines: &[&str], min: usize) -> Vec<Block> {
let mut out = Vec::new();
let mut open: Vec<usize> = Vec::new();
for (n, line) in lines.iter().enumerate() {
for b in line.bytes() {
match b {
b'{' => open.push(n),
b'}' => {
if let Some(head) = open.pop() {
if n > head && n - head >= min {
out.push((head, head + 1, n + 1));
}
}
}
_ => {}
}
}
}
out.sort_by_key(|(h, _, _)| *h);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn depth_is_counted_at_the_start_of_each_line() {
let lines = vec!["fn a() {", " x", "}", "fn b() {}"];
assert_eq!(depths(&lines), vec![0, 1, 1, 0]);
}
#[test]
fn a_body_runs_to_the_line_that_closes_it() {
let lines = vec!["fn a() {", " x", "}", ""];
let d = depths(&lines);
assert_eq!(extent(&lines, &d, 0), (1, (1, 3)));
}
#[test]
fn an_initializer_full_of_braces_folds_as_one() {
let lines = vec![
"const BINDINGS: &[Binding] = &[",
" Binding {",
" keys: \"j\",",
" },",
" Binding {",
" keys: \"k\",",
" },",
"];",
"",
];
let d = depths(&lines);
assert_eq!(extent(&lines, &d, 0), (1, (1, 8)));
}
#[test]
fn a_multi_line_signature_still_finds_its_body() {
let lines = vec!["fn f(", " a: u8,", ") -> u8 {", " a", "}", ""];
let d = depths(&lines);
assert_eq!(extent(&lines, &d, 0), (3, (3, 5)), "params stay visible");
}
#[test]
fn a_declaration_with_no_body_ends_at_its_semicolon() {
let lines = vec!["use a::b;", ""];
let d = depths(&lines);
assert_eq!(extent(&lines, &d, 0), (1, (1, 1)));
}
#[test]
fn comments_and_decorators_above_a_declaration_belong_to_it() {
let raw = vec!["", "// note", "/// doc", "#[attr]", "@Component", "fn f() {}"];
assert_eq!(doc_above(&raw, 5), (1, 5));
assert_eq!(doc_above(&raw, 1), (1, 1), "a blank line stops it");
}
#[test]
fn blocks_are_found_innermost_and_short_ones_skipped() {
let lines = vec![
"fn f() {", " if a {", " x();", " y();", " }", " z();", "}", "fn g() { h() }", ];
let got = blocks(&lines, 2);
assert_eq!(got, vec![(0, 1, 7), (1, 2, 5)], "the fn and the if, not the one-liner");
let (h, b, e) = got[1];
assert!(5 >= e || 5 < b, "row 5 is not inside {h}..{e}");
assert_eq!(blocks(&lines, 5), vec![(0, 1, 7)]);
}
#[test]
fn words_match_whole_and_identifiers_stop_at_punctuation() {
assert!(starts_word("fn f()", "fn"));
assert!(!starts_word("fnord()", "fn"));
assert_eq!(word("fn f()", "fn"), Some("f()"));
assert_eq!(ident(" name(x)"), "name");
assert_eq!(ident("(x)"), "");
}
}