use std::borrow::Cow;
use crate::lex::word_end;
use crate::py_space;
#[derive(Clone, Copy)]
struct Token<'a> {
text: &'a str,
line: usize,
at: usize,
end: usize,
body: Option<(usize, usize)>,
raw: bool,
}
#[derive(Default)]
struct Node<'a> {
kind: &'a str,
children: Vec<usize>,
chain: Option<usize>,
annotated: bool,
literal: Option<Vec<Token<'a>>>,
}
const HEADERS: &[&str] =
&["def", "class", "if", "elif", "else", "for", "while", "try", "except", "finally", "with", "match", "case"];
const KEYWORDS: &[&str] = &[
"return", "del", "pass", "raise", "global", "nonlocal", "assert", "import", "from", "lambda", "yield", "await",
"break", "continue", "not", "None", "True", "False",
];
fn nesting(t: &str) -> i64 {
match t {
"(" | "[" | "{" => 1,
")" | "]" | "}" => -1,
_ => 0,
}
}
fn is_prefix(word: &str) -> bool {
matches!(
word.to_ascii_lowercase().as_bytes(),
[b'r' | b'b' | b'u' | b'f' | b't'] | [b'r', b'b' | b'f' | b't'] | [b'b' | b'f' | b't', b'r']
)
}
fn unescape(body: &str) -> Cow<'_, str> {
if !body.contains('\\') {
return Cow::Borrowed(body);
}
let escape = regex!(r"(?s)\\(?:([0-7]{1,3})|x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8})|(.))");
escape.replace_all(body, |caps: ®ex::Captures| {
let Some(other) = caps.get(5) else {
let (digits, radix) = caps.get(1).map_or_else(|| ((2..=4).find_map(|k| caps.get(k)), 16), |d| (Some(d), 8));
let value = digits.and_then(|d| u32::from_str_radix(d.as_str(), radix).ok());
return value.and_then(char::from_u32).unwrap_or('\u{fffd}').to_string();
};
match "\nabfnrtv\\'\"".find(other.as_str()) {
Some(k) => ["", "\x07", "\x08", "\x0c", "\n", "\r", "\t", "\x0b", "\\", "'", "\""][k].into(),
None => caps[0].into(),
}
})
}
fn string(b: &[u8], i: usize, f: bool) -> usize {
let n = b.len();
let width = if b[i..].starts_with(&[b[i]; 3]) { 3 } else { 1 };
let (mut braces, mut j) = (0, i + width);
while j < n {
let c = b[j];
if c == b'\\' {
j += 1;
} else if braces == 0 && b[j..].starts_with(&b[i..i + width]) {
return j + width;
} else if c == b'\n' && width == 1 && braces == 0 {
return if f { j } else { memchr::memchr(b'\n', &b[i..]).map_or(n, |k| i + k) };
} else if f && c == b'{' {
if b.get(j + 1) == Some(&b'{') && braces == 0 {
j += 1;
} else {
braces += 1;
}
} else if c == b'}' && braces > 0 {
braces -= 1;
} else if braces > 0 && (c == b'\'' || c == b'"') {
j = string(b, j, false) - 1;
}
j += 1;
}
n
}
fn logical_lines(source: &str) -> Vec<(usize, Vec<Token<'_>>)> {
let b = source.as_bytes();
let n = b.len();
let (mut lines, mut tokens) = (Vec::new(), Vec::new());
let (mut indent, mut depth, mut start, mut line) = (0, 0i64, true, 0);
let mut i = 0;
while i < n {
if start {
let mut column = 0;
while i < n && matches!(b[i], b' ' | b'\t' | b'\x0c') {
column = match b[i] {
b'\t' => (column & !7) + 8,
b'\x0c' => 0,
_ => column + 1,
};
i += 1;
}
if i < n && b[i] != b'\n' && b[i] != b'#' {
(indent, start) = (column, false);
}
if i >= n {
break;
}
}
let c = b[i];
if c == b'\n' {
line += 1;
i += 1;
if depth == 0 && !tokens.is_empty() {
lines.push((indent, std::mem::take(&mut tokens)));
}
start = depth == 0 && tokens.is_empty();
} else if c == b'\\' && b.get(i + 1) == Some(&b'\n') {
(i, line) = (i + 2, line + 1);
} else if c == b'#' {
i = memchr::memchr(b'\n', &b[i..]).map_or(n, |k| i + k);
} else if matches!(c, b' ' | b'\t' | b'\x0c') {
i += 1;
} else {
let word = word_end(source, i);
let mut end = if word > i { word } else { i + source[i..].chars().next().map_or(1, char::len_utf8) };
let text = &source[i..end];
let mut token = Token { text, line, at: i, end: line, body: None, raw: false };
let quote = |k: usize| matches!(b.get(k), Some(b'\'' | b'"'));
if quote(i) || quote(end) && is_prefix(text) {
let prefix = if quote(i) { String::new() } else { text.to_ascii_lowercase() };
let body = i + prefix.len();
end = string(b, body, prefix.contains(['f', 't']));
line += memchr::memchr_iter(b'\n', &b[body..end]).count();
let width = if b[body..].starts_with(&[b[body]; 3]) { 3 } else { 1 };
token.text = "string";
if !prefix.contains(['b', 'f', 't']) {
token.body = Some((body + width, end.saturating_sub(width).max(body + width)));
token.raw = prefix.contains('r');
}
} else if c == b':' && b.get(i + 1) == Some(&b'=') {
(token.text, end) = (":=", i + 2);
}
token.end = line;
depth = (depth + nesting(token.text)).max(0);
tokens.push(token);
i = end;
}
}
if !tokens.is_empty() {
lines.push((indent, tokens));
}
lines
}
fn header_colon(tokens: &[Token]) -> Option<usize> {
let first = tokens[0].text;
let second = tokens.get(1).map(|t| t.text);
if !HEADERS.contains(&first) && !(first == "async" && second.is_some_and(|s| HEADERS.contains(&s))) {
return None;
}
if matches!(first, "match" | "case") && second.is_none_or(|s| s.starts_with([':', '=', '.']) || s == "=") {
return None;
}
let (mut depth, mut lambdas) = (0i64, 0i64);
for (k, t) in tokens.iter().enumerate() {
match t.text {
t if nesting(t) != 0 => depth += nesting(t),
"lambda" if depth == 0 => lambdas += 1,
":" if depth == 0 => {
if lambdas == 0 {
return Some(k);
}
lambdas -= 1;
}
_ => {}
}
}
None
}
fn simple<'a>(tokens: &[Token<'a>]) -> Vec<Node<'a>> {
let mut nodes = Vec::new();
let mut depth = 0i64;
let mut from = 0;
for k in 0..=tokens.len() {
let t = tokens.get(k).map(|t| t.text);
depth += t.map_or(0, nesting);
if t.is_some_and(|t| t != ";" || depth != 0) {
continue;
}
let part = &tokens[from..k];
from = k + 1;
if part.is_empty() {
continue;
}
let opening = part.iter().take_while(|p| p.text == "(").count();
let strings = part[opening..].iter().take_while(|p| p.text == "string").count();
let closing = part[opening + strings..].iter().take_while(|p| p.text == ")").count();
let literal = strings > 0
&& opening == closing
&& opening + strings + closing == part.len()
&& part[opening..opening + strings].iter().all(|p| p.body.is_some());
let mut annotated = !KEYWORDS.contains(&part[0].text);
let mut level = 0i64;
for (i, p) in part.iter().enumerate() {
if !annotated {
break;
}
level += nesting(p.text);
if level == 0 && (p.text == "=" || p.text == "lambda") {
annotated = false;
} else if level == 0 && p.text == ":" {
break;
} else if i == part.len() - 1 {
annotated = false;
}
}
let literal = literal.then(|| part[opening..opening + strings].to_vec());
nodes.push(Node { kind: "simple", annotated, literal, ..Node::default() });
}
nodes
}
fn add<'a>(nodes: &mut Vec<Node<'a>>, parent: usize, node: Node<'a>) -> usize {
nodes.push(node);
let index = nodes.len() - 1;
nodes[parent].children.push(index);
index
}
fn tree(source: &str) -> Vec<Node<'_>> {
let mut nodes = vec![Node { kind: "module", ..Node::default() }];
let mut stack: Vec<(i64, usize, Option<usize>)> = vec![(-1, 0, None)];
let mut pending: Option<usize> = None;
for (indent, tokens) in logical_lines(source) {
let indent = indent as i64;
if tokens[0].text == "@" {
continue;
}
match pending.take() {
Some(node) => stack.push((indent, node, None)),
None => {
while stack.len() > 1 && stack.last().is_some_and(|b| b.0 > indent) {
stack.pop();
}
}
}
let top = stack.len() - 1;
let (_, block, last) = stack[top];
let Some(colon) = header_colon(&tokens) else {
for node in simple(&tokens) {
stack[top].2 = Some(add(&mut nodes, block, node));
}
continue;
};
let kind = tokens[usize::from(tokens[0].text == "async")].text;
let owner = last.unwrap_or(block);
let target = match kind {
"elif" => {
let parent = nodes[owner].chain.unwrap_or(owner);
let target = add(&mut nodes, parent, Node { kind, ..Node::default() });
nodes[owner].chain = Some(target);
target
}
"except" => add(&mut nodes, owner, Node { kind, ..Node::default() }),
"else" | "finally" => last.map_or(block, |l| nodes[l].chain.unwrap_or(l)),
_ => {
let target = add(&mut nodes, block, Node { kind, ..Node::default() });
nodes[target].chain = (kind == "if").then_some(target);
stack[top].2 = Some(target);
target
}
};
if colon + 1 < tokens.len() {
for node in simple(&tokens[colon + 1..]) {
add(&mut nodes, target, node);
}
} else {
pending = Some(target);
}
}
nodes
}
fn cleandoc(doc: &str) -> Vec<String> {
let mut lines: Vec<String> = doc
.split('\n')
.map(|line| {
if !line.contains('\t') {
return line.to_string();
}
let (mut out, mut column) = (String::new(), 0);
for c in line.chars() {
if c == '\t' {
let width = 8 - column % 8;
out.extend(std::iter::repeat_n(' ', width));
column += width;
} else {
out.push(c);
column += 1;
}
}
out
})
.collect();
let margin = lines[1..]
.iter()
.filter_map(|l| {
let content = l.trim_start_matches(' ');
(!content.is_empty()).then(|| l.len() - content.len())
})
.min();
lines[0] = lines[0].trim_start_matches(' ').to_string();
if let Some(margin) = margin {
for line in &mut lines[1..] {
*line = line[margin.min(line.len())..].to_string();
}
}
while lines.last().is_some_and(String::is_empty) {
lines.pop();
}
let blank = lines.iter().take_while(|l| l.is_empty()).count();
lines.drain(..blank);
if lines.is_empty() {
lines.push(String::new());
}
lines
}
pub struct Docstring {
pub kind: char,
pub start: usize,
pub text: Vec<String>,
}
pub fn docstrings(source: &str, source_lines: &[&str]) -> Vec<Docstring> {
let nodes = tree(source);
let mut found: Vec<(char, Option<usize>)> = Vec::new();
let mut queue = vec![0];
let mut k = 0;
while k < queue.len() {
let node = &nodes[queue[k]];
k += 1;
if matches!(node.kind, "module" | "def" | "class") {
found.push((if node.kind == "module" { '!' } else { '"' }, node.children.first().copied()));
}
if node.kind == "class" {
for (i, &child) in node.children.iter().enumerate() {
if nodes[child].annotated && i + 1 < node.children.len() {
found.push(('"', Some(node.children[i + 1])));
}
}
}
queue.extend(&node.children);
}
let mut docs = Vec::new();
for (kind, node) in found {
let Some(literal) = node.and_then(|n| nodes[n].literal.as_ref()) else { continue };
let (first, last) = (literal[0], literal[literal.len() - 1]);
let line_start = source[..first.at].rfind('\n').map_or(0, |k| k + 1);
let opening: String = source_lines[first.line].chars().skip(first.at - line_start).collect();
let opening = opening.trim_start_matches(['r', 'R', 'u', 'U']);
let rest: String = opening.chars().skip(3).collect();
let below = rest.trim_matches(py_space).is_empty() && last.end > first.line;
let value: String = literal
.iter()
.map(|t| {
let (from, to) = t.body.unwrap_or_default();
let body = source.get(from..to).unwrap_or_default();
if t.raw { Cow::Borrowed(body) } else { unescape(body) }
})
.collect();
docs.push(Docstring { kind, start: first.line + usize::from(below), text: cleandoc(&value) });
}
docs
}