#![deny(unsafe_code)]
use super::decl::{doc_above, ident, word};
use super::py::{balanced, lex};
use super::scan::blank;
use super::{disambiguate, Kind, Symbol};
const TAB: usize = 4;
pub fn symbols(src: &str) -> 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 mut out: Vec<Symbol> = Vec::new();
let mut container: Option<(String, usize, Option<usize>)> = None;
for i in 0..lines.len() {
let line = lines[i];
if line.trim().is_empty() {
continue;
}
let col = indent(line);
if let Some((_, at, _)) = &container {
if col <= *at {
container = None;
}
}
let Some((kind, name)) = recognise(line.trim_start(), raw[i].trim_start()) else {
continue;
};
let member = match &mut container {
Some((_, _, member_col)) => match member_col {
None => {
*member_col = Some(col);
true
}
Some(m) if col == *m => true,
_ => continue,
},
None => {
if col > 0 {
continue; }
false
}
};
let (sig_end, body_end) = extent(&lines, &raw, i, col, kind);
let path = match &container {
Some((c, _, _)) => format!("{c}::{name}"),
None => name.clone(),
};
if kind == Kind::Class {
container = Some((name.clone(), col, None));
}
out.push(Symbol {
kind,
name,
path,
depth: member as u8,
doc: doc_above(&raw, i),
sig: (i, sig_end),
body: (sig_end, body_end),
});
}
disambiguate(&mut out);
Some(out)
}
fn indent(line: &str) -> usize {
let mut col = 0usize;
for c in line.chars() {
match c {
' ' => col += 1,
'\t' => col += TAB - (col % TAB),
_ => break,
}
}
col
}
fn recognise(line: &str, raw: &str) -> Option<(Kind, String)> {
if let Some(rest) = word(line, "import") {
return Some((Kind::Import, rest.split(' ').next()?.trim().to_string()));
}
if let Some(rest) = word(line, "from") {
return Some((Kind::Import, rest.split(' ').next()?.trim().to_string()));
}
let after_async = word(line, "async").unwrap_or(line);
if let Some(rest) = word(after_async, "def") {
return Some((Kind::Func, ident(rest)));
}
if let Some(rest) = word(line, "class") {
return Some((Kind::Class, ident(rest)));
}
let name = ident(line);
if !name.is_empty() && name.chars().all(|c| c.is_ascii_uppercase() || c == '_' || c.is_ascii_digit()) {
let rest = raw[name.len()..].trim_start();
if rest.starts_with('=') || rest.starts_with(':') {
return Some((Kind::Const, name));
}
}
None
}
fn extent(lines: &[&str], raw: &[&str], start: usize, col: usize, kind: Kind) -> (usize, usize) {
if kind == Kind::Import || kind == Kind::Const {
return (start + 1, start + 1);
}
let mut depth = 0i32;
let mut sig_end = start + 1;
for (n, line) in lines.iter().enumerate().skip(start) {
for b in line.bytes() {
match b {
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' => depth -= 1,
_ => {}
}
}
if depth <= 0 && line.trim_end().ends_with(':') {
sig_end = n + 1;
break;
}
sig_end = n + 1;
}
let sig_end = docstring_end(raw, sig_end);
let mut end = sig_end;
for (n, line) in lines.iter().enumerate().skip(sig_end) {
if line.trim().is_empty() {
continue;
}
if indent(line) <= col {
break;
}
end = n + 1;
}
(sig_end, end.max(sig_end))
}
fn docstring_end(raw: &[&str], from: usize) -> usize {
let Some(line) = raw.get(from) else {
return from;
};
let text = line.trim_start();
let body = text.trim_start_matches(|c: char| {
matches!(c.to_ascii_lowercase(), 'r' | 'b' | 'f' | 'u')
});
let Some(quote) = ["\"\"\"", "'''"].into_iter().find(|q| body.starts_with(q)) else {
return from;
};
if body[quote.len()..].contains(quote) {
return from + 1;
}
for (n, l) in raw.iter().enumerate().skip(from + 1) {
if l.contains(quote) {
return n + 1;
}
}
from
}
pub fn blocks(lines: &[&str], min: usize) -> Vec<super::decl::Block> {
let mut out = Vec::new();
let mut depth = 0i32;
for (n, line) in lines.iter().enumerate() {
let opened_at = depth;
for b in line.bytes() {
match b {
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' => depth -= 1,
_ => {}
}
}
let _ = opened_at;
if depth > 0 || !line.trim_end().ends_with(':') {
continue;
}
let head = line.trim_start();
if word(head, "def").is_some()
|| word(head, "class").is_some()
|| word(word(head, "async").unwrap_or(head), "def").is_some()
{
continue;
}
let col = indent(line);
let mut end = n;
for (k, l) in lines.iter().enumerate().skip(n + 1) {
if l.trim().is_empty() {
continue;
}
if indent(l) <= col {
break;
}
end = k;
}
if end > n && end - n >= min {
out.push((n, n + 1, end + 1));
}
}
out
}
#[cfg(test)]
#[path = "py_decl_tests.rs"]
mod tests;