use std::cmp::Ordering;
use std::collections::HashSet;
use tree_sitter::{Node, Parser, Query};
const VIS_PREFIXES: [&str; 9] = [
"pub ",
"public ",
"private ",
"protected ",
"export ",
"default ",
"async ",
"static ",
"final ",
];
const DECL_KEYWORDS: [&str; 18] = [
"fn ",
"func ",
"def ",
"function ",
"struct ",
"enum ",
"trait ",
"impl ",
"impl<",
"interface ",
"class ",
"type ",
"const ",
"static ",
"mod ",
"namespace ",
"package ",
"module ",
];
const CONTROL_KEYWORDS: [&str; 13] = [
"if ", "if(", "for ", "for(", "while ", "while(", "switch ", "switch(", "match ", "else",
"do ", "try ", "catch",
];
fn looks_like_signature(t: &str) -> bool {
let trimmed = t.trim_end();
if !trimmed.ends_with('{') {
return false;
}
if !t.contains('(') || !t.contains(')') {
return false;
}
if t.starts_with('}') || t.starts_with("//") || t.starts_with('*') || t.starts_with('@') {
return false;
}
!CONTROL_KEYWORDS.iter().any(|c| t.starts_with(c))
}
fn floor_boundary(s: &str, mut idx: usize) -> usize {
if idx >= s.len() {
return s.len();
}
while idx > 0 && !s.is_char_boundary(idx) {
idx -= 1;
}
idx
}
fn ceil_boundary(s: &str, mut idx: usize) -> usize {
while idx < s.len() && !s.is_char_boundary(idx) {
idx += 1;
}
idx
}
fn prose_excerpt(text: &str, head_budget: usize, tail_budget: usize) -> String {
if text.len() <= head_budget + tail_budget + 64 {
return text.trim().to_string();
}
let head_end = floor_boundary(text, head_budget);
let tail_start = ceil_boundary(text, text.len().saturating_sub(tail_budget));
let elided = tail_start.saturating_sub(head_end);
format!(
"{}\n… [{elided} chars of prose elided] …\n{}",
text[..head_end].trim_end(),
text[tail_start..].trim_start()
)
}
fn is_import(t: &str) -> bool {
["use ", "import ", "from ", "#include", "require("]
.iter()
.any(|p| t.starts_with(p))
}
fn is_doc(t: &str) -> bool {
t.starts_with("///")
|| t.starts_with("//!")
|| t.starts_with("# ")
|| t.starts_with("\"\"\"")
|| t.starts_with("/**")
}
fn rust_ast_body(heavy: &str, max_doc_lines: usize) -> Option<(String, usize)> {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.ok()?;
let tree = parser.parse(heavy, None)?;
let language = tree_sitter_rust::LANGUAGE.into();
let query = Query::new(
&language,
r#"
(use_declaration) @import
(function_item) @decl
(struct_item) @decl
(enum_item) @decl
(trait_item) @decl
(impl_item) @decl
(type_item) @decl
(const_item) @decl
(static_item) @decl
(mod_item) @decl
(macro_definition) @decl
(line_comment) @doc
(block_comment) @doc
"#,
)
.ok()?;
let _capture_names = query.capture_names();
let mut captured: Vec<(usize, &'static str, Node)> = Vec::new();
collect_rust_captures(tree.root_node(), &mut captured);
captured.sort_by_key(|(start, _, _)| *start);
let mut out: Vec<String> = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
let mut doc_budget = max_doc_lines;
let mut elided = 0usize;
let mut decl_count = 0usize;
for (_, capture_name, node) in captured {
if capture_name == "decl" {
decl_count += 1;
}
let rendered = match capture_name {
"import" => node_text(node, heavy)
.map(str::trim_end)
.map(str::to_string),
"doc" => {
let text = node_text(node, heavy)?.trim();
if !is_doc(text) || doc_budget == 0 {
elided += 1;
None
} else {
doc_budget -= 1;
Some(text.to_string())
}
}
"decl" => render_rust_decl(node, heavy),
_ => None,
};
if let Some(line) = rendered {
push_unique_structural(&line, &mut out, &mut seen, &mut elided);
} else {
elided += 1;
}
}
if out.is_empty() {
return None;
}
if decl_count > 0 || elided > 0 || tree.root_node().has_error() {
out.push(format!(
"// … {} implementation lines elided …",
elided.max(1)
));
}
Some((out.join("\n"), elided))
}
fn collect_rust_captures<'tree>(
node: Node<'tree>,
captured: &mut Vec<(usize, &'static str, Node<'tree>)>,
) {
let capture = match node.kind() {
"use_declaration" => Some("import"),
"line_comment" | "block_comment" => Some("doc"),
"function_item" | "struct_item" | "enum_item" | "trait_item" | "impl_item"
| "type_item" | "const_item" | "static_item" | "mod_item" | "macro_definition" => {
Some("decl")
}
_ => None,
};
if let Some(name) = capture {
captured.push((node.start_byte(), name, node));
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i as u32) {
collect_rust_captures(child, captured);
}
}
}
fn node_text<'a>(node: Node, source: &'a str) -> Option<&'a str> {
node.utf8_text(source.as_bytes()).ok()
}
fn render_rust_decl(node: Node, source: &str) -> Option<String> {
match node.kind() {
"function_item" => render_until_child(node, source, &["block"], " { … }"),
"impl_item" | "trait_item" | "mod_item" => {
render_until_child(node, source, &["declaration_list", "block"], " { … }")
}
"struct_item" | "enum_item" | "macro_definition" => render_until_child(
node,
source,
&[
"field_declaration_list",
"ordered_field_declaration_list",
"enum_variant_list",
"token_tree",
],
" { … }",
),
"const_item" | "static_item" => render_until_equals(node, source),
_ => node_text(node, source).map(|s| s.trim_end().to_string()),
}
}
fn render_until_child(
node: Node,
source: &str,
child_kinds: &[&str],
suffix: &str,
) -> Option<String> {
let child = first_named_child_kind(node, child_kinds);
let end = child
.map(|n| n.start_byte())
.unwrap_or_else(|| node.end_byte());
let start = node.start_byte();
let prefix = source.get(start..end)?.trim_end();
Some(format!(
"{}{}",
prefix.trim_end_matches('{').trim_end(),
suffix
))
}
fn first_named_child_kind<'tree>(node: Node<'tree>, child_kinds: &[&str]) -> Option<Node<'tree>> {
for i in 0..node.named_child_count() {
let child = node.named_child(i as u32)?;
if child_kinds.iter().any(|kind| child.kind() == *kind) {
return Some(child);
}
}
None
}
fn is_module_constant(line: &str, trimmed: &str) -> Option<String> {
if line.len() != trimmed.len() {
return None;
}
let eq = trimmed.find('=')?;
let bytes = trimmed.as_bytes();
if eq > 0 {
match bytes[eq - 1] {
b'=' | b'!' | b'<' | b'>' | b':' => return None,
_ => {}
}
}
if bytes.get(eq + 1) == Some(&b'=') {
return None;
}
let name = trimmed[..eq].trim_end();
if name.len() < 2
|| !name
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
|| !name.chars().next().unwrap().is_ascii_uppercase()
{
return None;
}
Some(name.to_string())
}
fn render_until_equals(node: Node, source: &str) -> Option<String> {
let text = node_text(node, source)?.trim_end();
if let Some(eq) = text.find('=') {
return Some(format!("{} = …;", text[..eq].trim_end()));
}
Some(text.to_string())
}
fn strip_decl_prefix(mut s: &str) -> &str {
loop {
let mut changed = false;
for p in VIS_PREFIXES {
if let Some(rest) = s.strip_prefix(p) {
s = rest.trim_start();
changed = true;
}
}
if let Some(rest) = s.strip_prefix("pub(") {
if let Some(i) = rest.find(')') {
s = rest[i + 1..].trim_start();
changed = true;
}
}
if !changed {
break;
}
}
s
}
fn is_decl(t: &str) -> bool {
let s = strip_decl_prefix(t);
DECL_KEYWORDS.iter().any(|k| s.starts_with(k))
}
fn is_function_decl(t: &str) -> bool {
let s = strip_decl_prefix(t);
const FN_KEYWORDS: [&str; 4] = ["fn ", "func ", "def ", "function "];
if FN_KEYWORDS.iter().any(|k| s.starts_with(k)) {
return true;
}
looks_like_signature(t)
}
fn starts_with_kw(t: &str, kw: &str) -> bool {
if let Some(rest) = t.strip_prefix(kw) {
rest.is_empty() || !is_ident_byte(rest.as_bytes()[0])
} else {
false
}
}
pub fn build_digest(
heavy: &str,
session_id: &str,
original_tokens: usize,
recall_norm: f32,
state_hash: &str,
max_doc_lines: usize,
) -> String {
let mut out: Vec<String> = Vec::new();
let mut seen_structural: HashSet<String> = HashSet::new();
let mut doc_budget = max_doc_lines as i32;
let mut elided = 0usize;
let mut code_lines = 0usize;
if let Some((body, _)) = rust_ast_body(heavy, max_doc_lines) {
return format!(
"<axiom_context_digest session=\"{session_id}\" kind=\"structural-skeleton\" \
original_tokens=\"{original_tokens}\" recall_norm=\"{recall_norm:.3}\" state=\"{state_hash}\">\n\
# Lossy digest of elided heavy context. For code: signatures kept, bodies dropped.\n\
# Ask Axiom to expand a named symbol if you need its body.\n\
state_hash={state_hash}\n\
{body}\n\
</axiom_context_digest>"
);
}
for line in heavy.lines() {
let t = line.trim_start();
if t.is_empty() {
continue;
}
if is_import(t) {
push_unique_structural(line.trim_end(), &mut out, &mut seen_structural, &mut elided);
code_lines += 1;
} else if is_decl(t) || looks_like_signature(t) {
let sig = line.split('{').next().unwrap_or(line).trim_end();
let suffix = if line.contains('{') { " { … }" } else { "" };
let structural = format!("{sig}{suffix}");
push_unique_structural(&structural, &mut out, &mut seen_structural, &mut elided);
code_lines += 1;
} else if is_doc(t) && doc_budget > 0 {
let before = seen_structural.len();
push_unique_structural(line.trim_end(), &mut out, &mut seen_structural, &mut elided);
if seen_structural.len() > before {
doc_budget -= 1;
}
} else {
elided += 1;
}
}
let (kind, body) = if code_lines == 0 {
("prose-excerpt", prose_excerpt(heavy, 1200, 500))
} else {
if elided > 0 {
out.push(format!("// … {elided} implementation lines elided …"));
}
("structural-skeleton", out.join("\n"))
};
format!(
"<axiom_context_digest session=\"{session_id}\" kind=\"{kind}\" \
original_tokens=\"{original_tokens}\" recall_norm=\"{recall_norm:.3}\" state=\"{state_hash}\">\n\
# Lossy digest of elided heavy context. For code: signatures kept, bodies dropped.\n\
# Ask Axiom to expand a named symbol if you need its body.\n\
state_hash={state_hash}\n\
{body}\n\
</axiom_context_digest>"
)
}
pub fn skeleton_body(heavy: &str, max_doc_lines: usize) -> String {
if let Some((body, _)) = rust_ast_body(heavy, max_doc_lines) {
return body;
}
let mut out: Vec<String> = Vec::new();
let mut seen_structural: HashSet<String> = HashSet::new();
let mut doc_budget = max_doc_lines as i32;
let mut elided = 0usize;
let mut code_lines = 0usize;
for line in heavy.lines() {
let t = line.trim_start();
if t.is_empty() {
continue;
}
if is_import(t) {
push_unique_structural(line.trim_end(), &mut out, &mut seen_structural, &mut elided);
code_lines += 1;
} else if is_decl(t) || looks_like_signature(t) {
let sig = line.split('{').next().unwrap_or(line).trim_end();
let suffix = if line.contains('{') { " { … }" } else { "" };
let structural = format!("{sig}{suffix}");
push_unique_structural(&structural, &mut out, &mut seen_structural, &mut elided);
code_lines += 1;
} else if is_doc(t) && doc_budget > 0 {
let before = seen_structural.len();
push_unique_structural(line.trim_end(), &mut out, &mut seen_structural, &mut elided);
if seen_structural.len() > before {
doc_budget -= 1;
}
} else {
elided += 1;
}
}
if code_lines == 0 {
prose_excerpt(heavy, 1200, 500)
} else {
if elided > 0 {
out.push(format!("// … {elided} implementation lines elided …"));
}
out.join("\n")
}
}
fn push_unique_structural(
line: &str,
out: &mut Vec<String>,
seen: &mut HashSet<String>,
elided: &mut usize,
) {
let normalized = line.trim();
if normalized.is_empty() {
return;
}
if seen.insert(normalized.to_string()) {
out.push(line.to_string());
} else {
*elided += 1;
}
}
fn indent_of(line: &str) -> usize {
let mut w = 0;
for ch in line.chars() {
match ch {
' ' => w += 1,
'\t' => w += 4,
_ => break,
}
}
w
}
fn contains_symbol(line: &str, name: &str) -> bool {
let bytes = line.as_bytes();
let nb = name.as_bytes();
if nb.is_empty() {
return false;
}
let mut i = 0;
while let Some(pos) = line[i..].find(name) {
let start = i + pos;
let end = start + name.len();
let before_ok = start == 0 || !is_ident_byte(bytes[start - 1]);
let after_ok = end >= bytes.len() || !is_ident_byte(bytes[end]);
if before_ok && after_ok {
return true;
}
i = end;
}
false
}
fn is_ident_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
fn capture_block(lines: &[&str], start: usize) -> String {
let first = lines[start];
if first.contains('{') {
let mut depth: i32 = 0;
let mut out: Vec<&str> = Vec::new();
for line in &lines[start..] {
out.push(line);
for ch in line.chars() {
if ch == '{' {
depth += 1;
} else if ch == '}' {
depth -= 1;
}
}
if depth <= 0 && line.contains('}') {
break;
}
}
out.join("\n")
} else if first.trim_end().ends_with(':') {
let base = indent_of(first);
let mut out: Vec<&str> = vec![first];
for line in &lines[start + 1..] {
if line.trim().is_empty() {
out.push(line);
continue;
}
if indent_of(line) <= base {
break;
}
out.push(line);
}
while out.last().map(|l| l.trim().is_empty()).unwrap_or(false) {
out.pop();
}
out.join("\n")
} else {
first.to_string()
}
}
pub fn expand_symbol(source: &str, name: &str) -> Option<String> {
let lines: Vec<&str> = source.lines().collect();
for (i, line) in lines.iter().enumerate() {
let t = line.trim_start();
if (is_decl(t) || looks_like_signature(t)) && contains_symbol(line, name) {
return Some(capture_block(&lines, i));
}
if let Some(const_name) = is_module_constant(line, t) {
if const_name == name {
return Some(capture_constant_block(&lines, i));
}
}
}
None
}
fn capture_constant_block(lines: &[&str], start: usize) -> String {
let mut out = vec![lines[start].to_string()];
let mut depth = 0i32;
for c in lines[start].chars() {
match c {
'{' | '[' | '(' => depth += 1,
'}' | ']' | ')' => depth -= 1,
_ => {}
}
}
for line in &lines[start + 1..] {
if depth <= 0 && !line.starts_with(' ') && !line.starts_with('\t') && !line.trim().is_empty() {
break;
}
for c in line.chars() {
match c {
'{' | '[' | '(' => depth += 1,
'}' | ']' | ')' => depth -= 1,
_ => {}
}
}
out.push(line.to_string());
if depth <= 0 {
break;
}
}
out.join("\n")
}
struct RankedSymbol {
name: String,
signature: String,
body: String,
score: f64,
}
fn approx_tokens(s: &str) -> usize {
(s.len() / 4).max(1)
}
fn pagerank(adj: &[Vec<usize>], damping: f64, iterations: usize) -> Vec<f64> {
let n = adj.len();
if n == 0 {
return Vec::new();
}
let nf = n as f64;
let mut rank = vec![1.0 / nf; n];
let teleport = (1.0 - damping) / nf;
for _ in 0..iterations {
let mut next = vec![teleport; n];
for (i, outs) in adj.iter().enumerate() {
if outs.is_empty() {
let share = damping * rank[i] / nf;
for r in next.iter_mut() {
*r += share;
}
} else {
let share = damping * rank[i] / outs.len() as f64;
for &j in outs {
next[j] += share;
}
}
}
rank = next;
}
rank
}
fn build_reference_graph(symbols: &[RankedSymbol]) -> Vec<Vec<usize>> {
let n = symbols.len();
let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
for i in 0..n {
for j in 0..n {
if i == j || symbols[j].name.is_empty() {
continue;
}
if contains_symbol(&symbols[i].body, &symbols[j].name) {
adj[i].push(j);
}
}
}
adj
}
fn rust_decl_name(node: Node, source: &str) -> Option<String> {
if let Some(n) = node.child_by_field_name("name") {
if let Some(t) = node_text(n, source) {
let t = t.trim();
if !t.is_empty() {
return Some(t.to_string());
}
}
}
let mut cands: Vec<String> = Vec::new();
for i in 0..node.named_child_count() {
let c = node.named_child(i as u32)?;
match c.kind() {
"declaration_list" | "block" | "field_declaration_list"
| "ordered_field_declaration_list" | "enum_variant_list" | "token_tree" => break,
"identifier" | "type_identifier" => {
if let Some(t) = node_text(c, source) {
let t = t.trim();
if !t.is_empty() {
cands.push(t.to_string());
}
}
}
_ => {}
}
}
if node.kind() == "impl_item" {
cands.pop()
} else {
cands.into_iter().next()
}
}
fn extract_symbols_rust(heavy: &str) -> (Vec<String>, Vec<RankedSymbol>) {
let mut imports = Vec::new();
let mut symbols = Vec::new();
let mut parser = Parser::new();
let Ok(()) = parser.set_language(&tree_sitter_rust::LANGUAGE.into()) else {
return (imports, symbols);
};
let Some(tree) = parser.parse(heavy, None) else {
return (imports, symbols);
};
let mut captured: Vec<(usize, &'static str, Node)> = Vec::new();
collect_rust_captures(tree.root_node(), &mut captured);
captured.sort_by_key(|(start, _, _)| *start);
let mut seen: HashSet<usize> = HashSet::new();
for (_, kind, node) in captured {
if kind == "import" {
if let Some(t) = node_text(node, heavy) {
let t = t.trim_end().to_string();
if !imports.contains(&t) {
imports.push(t);
}
}
} else if kind == "decl" {
let Some(signature) = render_rust_decl(node, heavy) else {
continue;
};
if !seen.insert(node.start_byte()) {
continue;
}
let name = rust_decl_name(node, heavy).unwrap_or_default();
let body = node_text(node, heavy).unwrap_or("").to_string();
symbols.push(RankedSymbol {
name,
signature,
body,
score: 0.0,
});
}
}
(imports, symbols)
}
fn extract_decl_name(line: &str) -> Option<String> {
let mut s = line.trim_start();
loop {
let mut changed = false;
for p in VIS_PREFIXES {
if let Some(rest) = s.strip_prefix(p) {
s = rest.trim_start();
changed = true;
}
}
if let Some(rest) = s.strip_prefix("pub(") {
if let Some(i) = rest.find(')') {
s = rest[i + 1..].trim_start();
changed = true;
}
}
if !changed {
break;
}
}
if let Some(paren) = s.find('(') {
let before = s[..paren].trim_end();
if let Some(tok) = before.split_whitespace().last() {
let name = tok.trim_matches(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
if !name.is_empty() && !is_decl_keyword(name) {
return Some(name.to_string());
}
}
}
if let Some(rest) = s.strip_prefix("impl<") {
if let Some(gt) = rest.find('>') {
s = rest[gt + 1..].trim_start();
}
}
for kw in DECL_KEYWORDS {
if let Some(rest) = s.strip_prefix(kw) {
let mut toks = rest.split_whitespace();
let mut tok = toks.next()?;
if tok.starts_with('<') {
while !tok.contains('>') {
tok = toks.next()?;
}
tok = toks.next()?;
}
let name = tok.trim_matches(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
if !name.is_empty() {
return Some(name.to_string());
}
}
}
None
}
fn is_decl_keyword(name: &str) -> bool {
DECL_KEYWORDS
.iter()
.any(|k| k.trim_end() == name || k.trim_end_matches('<') == name)
}
fn extract_symbols_generic(heavy: &str) -> (Vec<String>, Vec<RankedSymbol>) {
let mut imports = Vec::new();
let mut symbols = Vec::new();
let lines: Vec<&str> = heavy.lines().collect();
let mut seen: HashSet<String> = HashSet::new();
for (i, line) in lines.iter().enumerate() {
let t = line.trim_start();
if t.is_empty() {
continue;
}
if is_import(t) {
let s = line.trim_end().to_string();
if !imports.contains(&s) {
imports.push(s);
}
} else if is_decl(t) || looks_like_signature(t) {
let base = line.split('{').next().unwrap_or(line).trim_end();
let signature = if line.contains('{') {
format!("{base} {{ … }}")
} else {
base.to_string()
};
if !seen.insert(signature.clone()) {
continue;
}
let name = extract_decl_name(line).unwrap_or_default();
let body = capture_block(&lines, i);
symbols.push(RankedSymbol {
name,
signature,
body,
score: 0.0,
});
} else if let Some(const_name) = is_module_constant(line, t) {
let signature = format!("{const_name} = …");
if !seen.insert(signature.clone()) {
continue;
}
symbols.push(RankedSymbol {
name: const_name,
signature,
body: String::new(),
score: 0.0,
});
}
}
(imports, symbols)
}
pub fn skeletonize_ranked(
text: &str,
language: &str,
token_budget: Option<usize>,
) -> String {
let (imports, mut symbols) = if language.eq_ignore_ascii_case("rust")
|| language.eq_ignore_ascii_case("rs")
{
extract_symbols_rust(text)
} else {
extract_symbols_generic(text)
};
if !symbols.is_empty() {
let adj = build_reference_graph(&symbols);
let scores = pagerank(&adj, 0.85, 20);
for (sym, sc) in symbols.iter_mut().zip(scores.iter()) {
sym.score = *sc;
}
symbols.sort_by(|a, b| {
b.score
.partial_cmp(&a.score)
.unwrap_or(Ordering::Equal)
});
}
if imports.is_empty() && symbols.is_empty() {
return prose_excerpt(text, 1200, 500);
}
let mut out: Vec<String> = Vec::new();
let mut used = 0usize;
let mut elided = 0usize;
let import_budget = token_budget.map(|b| b / 4);
let mut import_used = 0usize;
for imp in &imports {
let t = approx_tokens(imp);
if let Some(ibudget) = import_budget {
if import_used + t > ibudget {
elided += 1;
continue;
}
import_used += t;
}
if let Some(budget) = token_budget {
if used + t > budget && !out.is_empty() {
elided += 1;
continue;
}
used += t;
}
out.push(imp.clone());
}
for sym in &symbols {
let t = approx_tokens(&sym.signature);
if let Some(budget) = token_budget {
if used + t > budget && !out.is_empty() {
if !sym.name.is_empty() {
let stub = format!("// {} (… body elided …)", sym.name);
let stub_t = approx_tokens(&stub);
if used + stub_t <= budget {
out.push(stub);
used += stub_t;
continue;
}
}
elided += 1;
continue;
}
used += t;
}
out.push(sym.signature.clone());
}
if elided > 0 {
out.push(format!(
"// … {elided} lower-ranked lines elided by token budget …"
));
}
out.join("\n")
}
fn is_interesting_line(t: &str) -> bool {
is_error_handling(t)
|| is_suspicious(t)
|| is_boundary_condition(t)
|| is_complex_conditional(t)
|| is_return_stmt(t)
}
fn is_error_handling(t: &str) -> bool {
if starts_with_kw(t, "try") || starts_with_kw(t, "except") || starts_with_kw(t, "finally") {
return true;
}
if starts_with_kw(t, "raise") {
return true;
}
if starts_with_kw(t, "catch") || starts_with_kw(t, "throw") {
return true;
}
if t.contains("panic!") || t.contains("unreachable!") {
return true;
}
if t.contains(".unwrap()") || t.contains(".expect(") {
return true;
}
if t.contains("bail!") || t.contains("ensure!") {
return true;
}
if t.starts_with("Err(") || t.contains("=> Err(") || t.contains("return Err(") {
return true;
}
if t.ends_with('?') || t.ends_with("?,") || t.ends_with("?;") {
return true;
}
false
}
fn is_suspicious(t: &str) -> bool {
for m in [
"TODO",
"FIXME",
"XXX",
"HACK",
"BUG",
"KLUDGE",
"WORKAROUND",
] {
if contains_symbol(t, m) {
return true;
}
}
if t == "except:" {
return true;
}
if starts_with_kw(t, "assert") || t.starts_with("debug_assert") {
return true;
}
if t.contains("todo!") || t.contains("unimplemented!") {
return true;
}
false
}
fn generic_close(b: &[u8], i: usize) -> Option<usize> {
let prev = if i > 0 { b[i - 1] } else { return None };
if !(prev.is_ascii_alphanumeric() || prev == b'_' || prev == b'>' || prev == b':') {
return None;
}
let mut depth = 0i32;
let mut j = i;
while j < b.len() {
match b[j] {
b'<' => depth += 1,
b'>' => {
depth -= 1;
if depth == 0 {
return Some(j);
}
}
b if b.is_ascii_alphanumeric()
|| b == b'_'
|| b == b' '
|| b == b'\t'
|| b == b','
|| b == b':'
|| b == b'&'
|| b == b'\''
|| b == b'['
|| b == b']'
|| b == b'('
|| b == b')'
|| b == b'*'
|| b == b'+'
|| b == b'.'
|| b == b'?'
|| b == b'!'
|| b == b'|' => {}
_ => return None,
}
j += 1;
}
None
}
fn has_bare_comparison(t: &str) -> bool {
let b = t.as_bytes();
let mut i = 0;
while i < b.len() {
let c = b[i];
if c == b'<' || c == b'>' {
let prev = if i > 0 { b[i - 1] } else { 0 };
let next = if i + 1 < b.len() { b[i + 1] } else { 0 };
let prev_ok = !(prev == b'<' || prev == b'>' || prev == b'-' || prev == b'=');
let next_ok = !(next == b'<' || next == b'>' || next == b'=');
if prev_ok && next_ok {
if c == b'<' {
if let Some(close) = generic_close(b, i) {
i = close + 1;
continue;
}
}
return true;
}
}
i += 1;
}
false
}
fn is_boundary_condition(t: &str) -> bool {
t.contains("<=")
|| t.contains(">=")
|| t.contains("==")
|| t.contains("!=")
|| has_bare_comparison(t)
}
fn count_bool_connectors(t: &str) -> usize {
let mut count = t.matches("&&").count() + t.matches("||").count();
for tok in t.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) {
if tok == "and" || tok == "or" {
count += 1;
}
}
count
}
fn is_complex_conditional(t: &str) -> bool {
let is_cond =
starts_with_kw(t, "if") || starts_with_kw(t, "elif") || starts_with_kw(t, "while");
if !is_cond {
return false;
}
count_bool_connectors(t) >= 2
}
fn is_return_stmt(t: &str) -> bool {
if !starts_with_kw(t, "return") {
return false;
}
t.len() > "return".len()
}
fn block_end(lines: &[&str], start: usize) -> Option<usize> {
let t = lines[start].trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("//") {
return None;
}
let n = lines.len();
if t.ends_with(':') {
let base = indent_of(lines[start]);
let mut i = start + 1;
while i < n {
let l = lines[i];
if !l.trim().is_empty() && indent_of(l) <= base {
break;
}
i += 1;
}
if i > start + 1 {
Some(i)
} else {
None
}
} else if t.contains('{') {
let mut depth = 0i32;
let mut i = start;
loop {
for ch in lines[i].chars() {
if ch == '{' {
depth += 1;
} else if ch == '}' {
depth -= 1;
}
}
i += 1;
if depth <= 0 || i >= n {
break;
}
}
if i > start + 1 {
Some(i)
} else {
None
}
} else {
None
}
}
fn diagnostic_symbol_body(body: &str) -> String {
let lines: Vec<&str> = body.lines().collect();
let n = lines.len();
if n == 0 {
return String::new();
}
let mut keep = vec![false; n];
let mut idx = 0;
let mut header_end = 0;
while idx < n {
keep[idx] = true;
header_end = idx + 1;
let te = lines[idx].trim_end();
if te.ends_with('{') || te.ends_with(':') {
break;
}
idx += 1;
if idx > 8 {
break;
}
}
for (i, line) in lines.iter().enumerate() {
if keep[i] {
continue;
}
if is_interesting_line(line.trim_start()) {
keep[i] = true;
}
}
let mut i = header_end;
while i < n {
if keep[i] {
if let Some(end) = block_end(&lines, i) {
let end = end.min(n);
for k in keep.iter_mut().take(end).skip(i) {
*k = true;
}
i = end;
continue;
}
}
i += 1;
}
if n >= 1 && lines[n - 1].trim_start().starts_with('}') {
keep[n - 1] = true;
}
if n >= 2 {
let last = lines[n - 1].trim();
if last == "}" || last == "};" {
let prev_trimmed = lines[n - 2].trim();
if !prev_trimmed.is_empty()
&& !prev_trimmed.ends_with(';')
&& !prev_trimmed.ends_with('{')
&& !prev_trimmed.ends_with('}')
&& !keep[n - 2]
&& !is_decl(lines[n - 2].trim_start())
{
keep[n - 2] = true;
}
}
}
let mut out: Vec<String> = Vec::new();
let mut boring = 0usize;
let mut boring_indent = 0usize;
for (i, line) in lines.iter().enumerate() {
if keep[i] {
if boring > 0 {
let pad = " ".repeat(boring_indent);
out.push(format!("{pad}// … [{boring} lines elided] …"));
boring = 0;
}
out.push(line.to_string());
} else if boring == 0 {
boring_indent = indent_of(line);
boring = 1;
} else {
boring += 1;
}
}
out.join("\n")
}
fn rust_diagnostic_body(heavy: &str, max_doc_lines: usize) -> Option<String> {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.ok()?;
let tree = parser.parse(heavy, None)?;
let mut captured: Vec<(usize, &'static str, Node)> = Vec::new();
collect_rust_captures(tree.root_node(), &mut captured);
captured.sort_by_key(|(start, _, _)| *start);
let mut out: Vec<String> = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
let mut doc_budget = max_doc_lines;
let mut elided = 0usize;
let mut fn_count = 0usize;
for (_, capture_name, node) in captured {
let rendered = match capture_name {
"import" => node_text(node, heavy)
.map(str::trim_end)
.map(str::to_string),
"doc" => {
let text = node_text(node, heavy)?.trim();
if !is_doc(text) || doc_budget == 0 {
elided += 1;
None
} else {
doc_budget -= 1;
Some(text.to_string())
}
}
"decl" => {
if node.kind() == "function_item" {
fn_count += 1;
node_text(node, heavy).map(diagnostic_symbol_body)
} else {
render_rust_decl(node, heavy)
}
}
_ => None,
};
if let Some(line) = rendered {
push_unique_structural(&line, &mut out, &mut seen, &mut elided);
} else {
elided += 1;
}
}
if out.is_empty() || fn_count == 0 {
return None;
}
if elided > 0 {
out.push(format!("// … {elided} fully-elided lines …"));
}
Some(out.join("\n"))
}
fn generic_diagnostic_body(heavy: &str, max_doc_lines: usize) -> String {
let mut out: Vec<String> = Vec::new();
let mut seen_structural: HashSet<String> = HashSet::new();
let mut doc_budget = max_doc_lines as i32;
let mut elided = 0usize;
let mut code_lines = 0usize;
let lines: Vec<&str> = heavy.lines().collect();
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let t = line.trim_start();
if t.is_empty() {
i += 1;
continue;
}
if is_import(t) {
push_unique_structural(line.trim_end(), &mut out, &mut seen_structural, &mut elided);
code_lines += 1;
i += 1;
} else if is_decl(t) || looks_like_signature(t) {
if is_function_decl(t) {
let mut start = i;
while start > 0 && lines[start - 1].trim_start().starts_with('@') {
start -= 1;
}
let block = capture_block(&lines, i);
let consumed = block.lines().count();
let body = if start < i {
format!("{}\n{block}", lines[start..i].join("\n"))
} else {
block
};
let diagnostic = diagnostic_symbol_body(&body);
push_unique_structural(&diagnostic, &mut out, &mut seen_structural, &mut elided);
code_lines += 1;
i += consumed.max(1);
} else {
let sig = line.split('{').next().unwrap_or(line).trim_end();
let suffix = if line.contains('{') { " { … }" } else { "" };
let structural = format!("{sig}{suffix}");
push_unique_structural(&structural, &mut out, &mut seen_structural, &mut elided);
code_lines += 1;
i += 1;
}
} else if is_doc(t) && doc_budget > 0 {
let before = seen_structural.len();
push_unique_structural(line.trim_end(), &mut out, &mut seen_structural, &mut elided);
if seen_structural.len() > before {
doc_budget -= 1;
}
i += 1;
} else {
elided += 1;
i += 1;
}
}
if code_lines == 0 {
prose_excerpt(heavy, 1200, 500)
} else {
if elided > 0 {
out.push(format!("// … {elided} fully-elided lines …"));
}
out.join("\n")
}
}
pub fn skeleton_body_diagnostic(heavy: &str, max_doc_lines: usize) -> String {
if let Some(body) = rust_diagnostic_body(heavy, max_doc_lines) {
return body;
}
generic_diagnostic_body(heavy, max_doc_lines)
}
#[cfg(test)]
mod tests {
#[test]
fn ranked_keeps_name_stub_when_signature_exceeds_budget() {
let txt = "def alpha():\n pass\ndef beta():\n pass\ndef gamma():\n pass\n";
let out = skeletonize_ranked(txt, "python", Some(8));
let has_stub = out.contains("(… body elided …)");
let all_names_visible = ["alpha", "beta", "gamma"]
.iter()
.all(|n| out.contains(n));
assert!(
has_stub || all_names_visible,
"budget-elided symbols must keep names: {out}"
);
}
#[test]
fn ranked_emits_all_names_without_budget() {
let txt = "def alpha():\n pass\ndef beta():\n pass\n";
let out = skeletonize_ranked(txt, "python", None);
assert!(out.contains("alpha"), "{out}");
assert!(out.contains("beta"), "{out}");
}
#[test]
fn module_constant_detected() {
assert_eq!(
is_module_constant("RISK_ORDER = {\"low\": 1}", "RISK_ORDER = {\"low\": 1}"),
Some("RISK_ORDER".to_string())
);
assert_eq!(
is_module_constant("MAX_RETRIES = 3", "MAX_RETRIES = 3"),
Some("MAX_RETRIES".to_string())
);
}
#[test]
fn module_constant_rejects_non_constants() {
assert_eq!(is_module_constant(" X = 1", "X = 1"), None);
assert_eq!(is_module_constant("risk_order = 1", "risk_order = 1"), None);
assert_eq!(is_module_constant("X == 1", "X == 1"), None);
assert_eq!(is_module_constant("X = 1", "X = 1"), None);
assert_eq!(is_module_constant("X := 1", "X := 1"), None);
}
#[test]
fn ranked_captures_python_module_constant() {
let txt = "RISK_ORDER = {\"low\": 1, \"high\": 3}\ndef helper():\n pass\n";
let out = skeletonize_ranked(txt, "python", None);
assert!(out.contains("RISK_ORDER"), "{out}");
}
#[test]
fn expand_symbol_returns_full_constant_value() {
let txt = "RISK_ORDER = {\n \"low\": 1,\n \"high\": 3,\n}\ndef helper():\n pass\n";
let expanded = expand_symbol(txt, "RISK_ORDER").expect("must expand");
assert!(expanded.contains("\"low\": 1"), "{expanded}");
assert!(expanded.contains("\"high\": 3"), "{expanded}");
assert!(!expanded.contains("def helper"), "{expanded}");
}
use super::*;
const SAMPLE: &str = r#"
//! A small module.
use std::collections::HashMap;
pub fn add(a: i32, b: i32) -> i32 {
let s = a + b;
s
}
struct Point {
x: f64,
y: f64,
}
impl Point {
pub fn norm(&self) -> f64 {
(self.x * self.x + self.y * self.y).sqrt()
}
}
"#;
#[test]
fn keeps_signatures_drops_bodies() {
let d = build_digest(SAMPLE, "s1", 100, 1.5, "sha256:abc", 3);
assert!(d.contains("pub fn add(a: i32, b: i32) -> i32 { … }"));
assert!(d.contains("struct Point { … }"));
assert!(d.contains("use std::collections::HashMap;"));
assert!(d.contains("//! A small module."));
assert!(!d.contains("let s = a + b"));
assert!(!d.contains("sqrt()"));
assert!(d.contains("recall_norm=\"1.500\""));
assert!(d.contains("state=\"sha256:abc\""));
}
#[test]
fn elision_counter_present() {
let d = build_digest(SAMPLE, "s1", 100, 0.0, "h", 3);
assert!(d.contains("implementation lines elided"));
}
#[test]
fn strips_stacked_visibility() {
let txt = "pub async fn handler() -> Result<()> {\n ok()\n}";
let d = build_digest(txt, "s", 10, 0.0, "h", 0);
assert!(d.contains("pub async fn handler() -> Result<()> { … }"));
}
#[test]
fn rust_ast_keeps_static_mut_declarations() {
let txt = "static mut GLOBAL_COUNTER_XQZ: i64 = 0;\nfn run() { unsafe { GLOBAL_COUNTER_XQZ += 1; } }";
let d = build_digest(txt, "s", 10, 0.0, "h", 0);
assert!(d.contains("static mut GLOBAL_COUNTER_XQZ: i64 = …;"), "{d}");
assert!(d.contains("fn run() { … }"));
assert!(!d.contains("GLOBAL_COUNTER_XQZ += 1"));
}
#[test]
fn go_func_kept() {
let txt = "package main\nimport \"fmt\"\nfunc Add(a, b int) int {\n return a + b\n}";
let d = build_digest(txt, "s", 10, 0.0, "h", 3);
assert!(d.contains("func Add(a, b int) int { … }"));
assert!(d.contains("package main"));
assert!(!d.contains("return a + b"));
}
#[test]
fn python_def_class_kept() {
let txt = "import os\nclass Foo:\n def bar(self, x):\n return x * 2\n";
let d = build_digest(txt, "s", 10, 0.0, "h", 3);
assert!(d.contains("class Foo:"));
assert!(d.contains("def bar(self, x):"));
assert!(!d.contains("return x * 2"));
}
#[test]
fn skeleton_body_has_no_xml_wrapper() {
let b = skeleton_body(SAMPLE, 3);
assert!(!b.contains("<axiom_context_digest"));
assert!(!b.contains("recall_norm="));
assert!(b.contains("pub fn add(a: i32, b: i32) -> i32 { … }"));
assert!(b.contains("struct Point { … }"));
assert!(!b.contains("let s = a + b"));
}
#[test]
fn skeleton_body_python_readable() {
let txt = "import os\nclass Foo:\n def bar(self, x):\n return x * 2\n";
let b = skeleton_body(txt, 3);
assert!(b.contains("class Foo:"));
assert!(b.contains("def bar(self, x):"));
assert!(!b.contains("return x * 2"));
assert!(!b.contains("<axiom_context_digest"));
}
#[test]
fn skeleton_body_prose_falls_back_to_excerpt() {
let txt = "This is just plain prose with no code at all. ".repeat(100);
let b = skeleton_body(&txt, 3);
assert!(b.contains("elided"));
assert!(!b.contains("<axiom_context_digest"));
}
#[test]
fn js_class_method_without_keyword_kept() {
let txt = "class Api {\n async handle(req, res) {\n res.send(req.body)\n }\n}";
let d = build_digest(txt, "s", 10, 0.0, "h", 3);
assert!(d.contains("async handle(req, res) { … }"));
assert!(!d.contains("res.send(req.body)"));
}
#[test]
fn control_flow_not_treated_as_signature() {
let txt = "fn run() {\n if (x > 0) {\n go()\n }\n for (i in xs) {\n step()\n }\n}";
let d = build_digest(txt, "s", 10, 0.0, "h", 0);
assert!(d.contains("fn run() { … }"));
assert!(!d.contains("if (x > 0) { … }"));
assert!(!d.contains("for (i in xs) { … }"));
}
#[test]
fn repeated_declarations_are_deduplicated_in_digest() {
let repeated = "fn calculate_invoice_total(customer_id: &str) -> Result<Money> {\n lookup_contract_discount(customer_id)?;\n}\n\n".repeat(3);
let d = build_digest(&repeated, "s", 100, 0.0, "h", 0);
assert_eq!(d.matches("fn calculate_invoice_total").count(), 1);
assert!(d.contains("implementation lines elided"));
}
#[test]
fn prose_falls_back_to_excerpt_not_destroyed() {
let para = "The quarterly report shows revenue grew across all regions. ".repeat(60);
let d = build_digest(¶, "s", 500, 0.0, "h", 3);
assert!(d.contains("kind=\"prose-excerpt\""));
assert!(d.contains("quarterly report shows revenue"));
assert!(d.contains("chars of prose elided"));
}
#[test]
fn short_prose_kept_whole() {
let txt = "Just a short note, nothing structural here.";
let d = build_digest(txt, "s", 10, 0.0, "h", 3);
assert!(d.contains("Just a short note"));
}
#[test]
fn expand_brace_symbol_returns_full_body() {
let body = expand_symbol(SAMPLE, "add").unwrap();
assert!(body.contains("pub fn add(a: i32, b: i32) -> i32 {"));
assert!(body.contains("let s = a + b;"));
assert!(body.trim_end().ends_with('}'));
}
#[test]
fn expand_python_uses_indentation() {
let src = "class Foo:\n def bar(self, x):\n y = x * 2\n return y\n\ndef other():\n pass\n";
let body = expand_symbol(src, "bar").unwrap();
assert!(body.contains("def bar(self, x):"));
assert!(body.contains("return y"));
assert!(!body.contains("def other"));
}
#[test]
fn expand_unknown_symbol_is_none() {
assert!(expand_symbol(SAMPLE, "does_not_exist").is_none());
}
#[test]
fn expand_matches_whole_identifier_only() {
let src = "fn readd() {\n q()\n}\nfn add() {\n real()\n}\n";
let body = expand_symbol(src, "add").unwrap();
assert!(body.contains("fn add()"));
assert!(body.contains("real()"));
assert!(!body.contains("readd"));
}
#[test]
fn pagerank_orders_by_inbound_references() {
let adj = vec![vec![1, 2], vec![2], vec![]];
let r = pagerank(&adj, 0.85, 20);
assert!(r[2] > r[1], "{r:?}");
assert!(r[1] > r[0], "{r:?}");
let sum: f64 = r.iter().sum();
assert!((sum - 1.0).abs() < 1e-9, "{sum}");
}
#[test]
fn pagerank_uniform_when_no_edges() {
let adj = vec![vec![], vec![], vec![]];
let r = pagerank(&adj, 0.85, 20);
for v in &r {
assert!((*v - 1.0 / 3.0).abs() < 1e-9, "{r:?}");
}
}
#[test]
fn pagerank_empty_graph() {
let r = pagerank(&[], 0.85, 20);
assert!(r.is_empty());
}
#[test]
fn ranked_rust_skeleton_orders_callees_first() {
let src = "fn util() -> i32 {\n 1\n}\nfn helper() -> i32 {\n util() + util()\n}\nfn main() {\n let x = helper();\n}\n";
let out = skeletonize_ranked(src, "rust", None);
let pu = out.find("fn util()").expect("util missing");
let ph = out.find("fn helper()").expect("helper missing");
let pm = out.find("fn main()").expect("main missing");
assert!(pu < ph && ph < pm, "{out}");
}
#[test]
fn ranked_rust_keeps_imports_first() {
let src = "use std::collections::HashMap;\nfn b() {\n a();\n}\nfn a() {}\n";
let out = skeletonize_ranked(src, "rust", None);
let pi = out.find("use std::collections::HashMap;").unwrap();
let pa = out.find("fn a()").unwrap();
assert!(pi < pa, "{out}");
let pb = out.find("fn b()").unwrap();
assert!(pa < pb, "{out}");
}
#[test]
fn token_budget_keeps_top_symbols() {
let src = "fn aaa() {\n bbb();\n}\nfn bbb() {\n ccc();\n}\nfn ccc() -> i32 {\n 42\n}\n";
let out = skeletonize_ranked(src, "rust", Some(10));
assert!(out.contains("fn ccc()"), "{out}");
assert!(!out.contains("fn aaa()"), "{out}");
assert!(out.contains("elided by token budget"), "{out}");
}
#[test]
fn token_budget_none_keeps_everything() {
let src = "fn aaa() {\n bbb();\n}\nfn bbb() {\n ccc();\n}\nfn ccc() -> i32 {\n 42\n}\n";
let out = skeletonize_ranked(src, "rust", None);
assert!(out.contains("fn aaa()"));
assert!(out.contains("fn bbb()"));
assert!(out.contains("fn ccc()"));
assert!(!out.contains("elided by token budget"));
}
#[test]
fn ranked_generic_python_path() {
let src = "import os\nclass Foo:\n def bar(self):\n return baz()\ndef baz():\n return 1\n";
let out = skeletonize_ranked(src, "python", None);
assert!(out.contains("import os"), "{out}");
let pb = out.find("def baz():").expect("baz missing");
let pf = out.find("def bar(self):").expect("bar missing");
assert!(pb < pf, "{out}");
}
#[test]
fn ranked_prose_falls_back_to_excerpt() {
let para = "The quarterly report shows revenue grew. ".repeat(80);
let out = skeletonize_ranked(¶, "english", None);
assert!(out.contains("quarterly report"), "{out}");
}
#[test]
fn extract_decl_name_cases() {
assert_eq!(
extract_decl_name("pub fn add(a: i32) -> i32 {"),
Some("add".to_string())
);
assert_eq!(
extract_decl_name("class Foo:"),
Some("Foo".to_string())
);
assert_eq!(
extract_decl_name(" async handle(req, res) {"),
Some("handle".to_string())
);
assert_eq!(
extract_decl_name("const MAX: usize = 5;"),
Some("MAX".to_string())
);
assert_eq!(
extract_decl_name("impl Point {"),
Some("Point".to_string())
);
assert_eq!(
extract_decl_name("const f: fn() = g;"),
Some("f".to_string())
);
}
const DIAGNOSTIC_PY: &str = r#"import os
class Loader:
def load(self, path):
# TODO: support remote paths
count = 0
total = 0
try:
data = read(path)
except OSError as e:
log(e)
raise
if count > total and total != 0:
count += 1
name = "loader"
return data
"#;
#[test]
fn diagnostic_keeps_error_paths() {
let b = skeleton_body_diagnostic(DIAGNOSTIC_PY, 3);
assert!(b.contains("try:"), "{b}");
assert!(b.contains("except OSError as e:"), "{b}");
assert!(b.contains("log(e)"), "{b}"); assert!(b.contains("raise"), "{b}");
}
#[test]
fn diagnostic_keeps_todo_and_boundary_condition() {
let b = skeleton_body_diagnostic(DIAGNOSTIC_PY, 3);
assert!(b.contains("TODO"), "{b}");
assert!(b.contains("if count > total and total != 0:"), "{b}");
assert!(b.contains("count += 1"), "{b}"); }
#[test]
fn diagnostic_elides_boring_assignments() {
let b = skeleton_body_diagnostic(DIAGNOSTIC_PY, 3);
assert!(!b.contains("total = 0"), "{b}");
assert!(!b.contains("name = \"loader\""), "{b}");
assert!(b.contains("lines elided"), "{b}");
}
#[test]
fn diagnostic_keeps_return_value() {
let b = skeleton_body_diagnostic(DIAGNOSTIC_PY, 3);
assert!(b.contains("return data"), "{b}");
}
#[test]
fn diagnostic_keeps_returned_dict_literal() {
let src = "class P:\n def to_dict(self):\n tmp = 1\n return {\n \"allowed\": self.allowed,\n \"blocked\": self.blocked,\n }\n";
let b = skeleton_body_diagnostic(src, 3);
assert!(b.contains("\"allowed\": self.allowed"), "{b}");
assert!(b.contains("\"blocked\": self.blocked"), "{b}");
assert!(!b.contains("tmp = 1"), "{b}");
}
#[test]
fn diagnostic_keeps_complex_conditional() {
let src = "def f(a, b, c, d):\n x = 1\n if a and b or c and d:\n return 1\n return 0\n";
let b = skeleton_body_diagnostic(src, 3);
assert!(b.contains("if a and b or c and d:"), "{b}");
assert!(!b.contains("x = 1"), "{b}");
}
#[test]
fn diagnostic_and_or_need_word_boundaries() {
assert_eq!(count_bool_connectors("if candle and wax:"), 1);
assert_eq!(count_bool_connectors("if a && b || c:"), 2);
}
#[test]
fn diagnostic_keeps_assert_and_bare_except() {
let src = "def f(x):\n assert x > 0\n try:\n g()\n except:\n pass\n return x\n";
let b = skeleton_body_diagnostic(src, 3);
assert!(b.contains("assert x > 0"), "{b}");
assert!(b.contains("except:"), "{b}");
}
#[test]
fn diagnostic_rust_keeps_unwrap_and_try_operator() {
let src = "use std::collections::HashMap;\nfn get(m: &HashMap<String, i32>, k: &str) -> i32 {\n let v = m.get(k).unwrap();\n let w = v + 1;\n w\n}\nfn load(path: &str) -> Result<String, std::io::Error> {\n let s = std::fs::read_to_string(path)?;\n Ok(s)\n}\n";
let b = skeleton_body_diagnostic(src, 3);
assert!(b.contains(".unwrap()"), "{b}");
assert!(b.contains("?;"), "{b}");
assert!(!b.contains("let w = v + 1;"), "{b}");
}
#[test]
fn diagnostic_rust_keeps_tail_expression() {
let src = "fn inc(x: i32) -> i32 {\n let y = x + 1;\n y\n}\n";
let b = skeleton_body_diagnostic(src, 3);
assert!(b.contains("\n y\n"), "{b}");
assert!(!b.contains("let y = x + 1;"), "{b}");
}
#[test]
fn diagnostic_rust_keeps_err_and_panic() {
let src = "fn div(a: i32, b: i32) -> Result<i32, String> {\n let q = a / b;\n if b == 0 {\n return Err(\"zero\".to_string());\n }\n if q < 0 {\n panic!(\"negative\");\n }\n Ok(q)\n}\n";
let b = skeleton_body_diagnostic(src, 3);
assert!(b.contains("return Err("), "{b}");
assert!(b.contains("panic!"), "{b}");
assert!(b.contains("if b == 0 {"), "{b}");
assert!(!b.contains("let q = a / b;"), "{b}");
}
#[test]
fn diagnostic_bare_comparison_ignores_arrows() {
assert!(!has_bare_comparison("let f = |x| x -> i32;"));
assert!(!has_bare_comparison("Some(x) => foo(),"));
assert!(has_bare_comparison("if x < limit {"));
assert!(has_bare_comparison("while n > 0:"));
}
#[test]
fn diagnostic_generics_are_not_comparisons() {
assert!(!has_bare_comparison("let x: Vec<u8> = Vec::new();"));
assert!(!has_bare_comparison("let r: Result<T, E> = foo();"));
assert!(!has_bare_comparison(
"let m: HashMap<String, Vec<u8>> = HashMap::new();"
));
assert!(!has_bare_comparison("let y = foo::<T>(a);"));
assert!(has_bare_comparison("if x<y {"));
assert!(has_bare_comparison("while n>0 {"));
assert!(has_bare_comparison("if x < y {"));
}
#[test]
fn diagnostic_non_function_decls_stay_signatures() {
let b = skeleton_body_diagnostic(DIAGNOSTIC_PY, 3);
assert!(b.contains("class Loader:"), "{b}");
assert!(b.contains("import os"), "{b}");
assert_eq!(b.matches("def load").count(), 1);
}
const DIAGNOSTIC_SIZE_PY: &str = r#"import os
import sys
CONFIG_PATH = "/etc/app.conf"
DEFAULT_TIMEOUT = 30
class Processor:
def __init__(self, name):
self.name = name
self.count = 0
self.items = []
self.cache = {}
self.enabled = True
self.retries = 3
def process(self, items, limit):
results = []
batch = []
seen = set()
mapping = {}
for item in items:
batch.append(item)
seen.add(item.id)
transformed = item.value * 2
mapping[item.id] = transformed
if len(results) > limit:
raise ValueError("over limit")
total = sum(batch)
average = total / max(1, len(batch))
summary = f"{average:.2f}"
return results
"#;
#[test]
fn diagnostic_size_between_dumb_and_full() {
let dumb = skeleton_body(DIAGNOSTIC_SIZE_PY, 3);
let diagnostic = skeleton_body_diagnostic(DIAGNOSTIC_SIZE_PY, 3);
assert!(
dumb.len() < diagnostic.len(),
"dumb={} diagnostic={}",
dumb.len(),
diagnostic.len()
);
assert!(
diagnostic.len() < DIAGNOSTIC_SIZE_PY.len(),
"diagnostic={} full={}",
diagnostic.len(),
DIAGNOSTIC_SIZE_PY.len()
);
let ratio = diagnostic.len() as f64 / DIAGNOSTIC_SIZE_PY.len() as f64;
assert!(ratio < 0.8, "diagnostic/full ratio={ratio:.2}");
}
#[test]
fn diagnostic_prose_falls_back_to_excerpt() {
let txt = "Just plain prose, no code here. ".repeat(100);
let b = skeleton_body_diagnostic(&txt, 3);
assert!(b.contains("elided"), "{b}");
}
}