1use std::collections::{BTreeMap, HashMap};
2use std::path::Path;
3
4use crate::models::{
5 BlastRadiusResult, ContextSlice, ImpactedSymbol, ReferenceSite, SearchExplain, Symbol,
6 SymbolSearchResult, TestTarget,
7};
8
9pub fn format_file_skeleton(
11 file_path: &str,
12 symbols: &[Symbol],
13 line_count: Option<usize>,
14 parse_errors: usize,
15) -> String {
16 let mut out = String::new();
17 let lines_str = match line_count {
18 Some(c) => format!(" (Lines 1-{c})"),
19 None => String::new(),
20 };
21 out.push_str(&format!("// File: {file_path}{lines_str}\n\n"));
22
23 if parse_errors > 0 {
24 let noun = if parse_errors == 1 { "error" } else { "errors" };
25 out.push_str(&format!(
26 "// {parse_errors} parse {noun}: symbols may be incomplete\n\n"
27 ));
28 }
29
30 if symbols.is_empty() {
31 out.push_str("// No exported symbols indexed.\n");
32 return out;
33 }
34
35 let mut children_map: HashMap<Option<String>, Vec<&Symbol>> = HashMap::new();
37 for s in symbols {
38 children_map
39 .entry(s.parent_symbol_id.clone())
40 .or_default()
41 .push(s);
42 }
43
44 if let Some(roots) = children_map.get(&None) {
46 for root in roots {
47 render_symbol_skeleton(&mut out, root, None, &children_map, 0);
48 }
49 } else {
50 for s in symbols {
52 render_symbol_skeleton(&mut out, s, None, &children_map, 0);
53 }
54 }
55
56 out
57}
58
59fn is_container_kind(kind: &str) -> bool {
60 let hides_its_body = matches!(
61 kind,
62 "function" | "method" | "constructor" | "destructor" | "operator"
63 );
64 !is_skippable_kind(kind) && !hides_its_body
65}
66
67pub(crate) fn display_kind(sym: &Symbol) -> &str {
71 match (sym.language.as_str(), sym.kind.as_str()) {
72 ("html", "class") => "element",
73 ("sql", "class") => "table",
74 ("markdown", "module") => "section",
75 ("markdown", "import") => "link",
76 (language, "property")
77 if language != "fsharp"
78 && sym.signature.as_deref().is_some_and(|sig| {
79 ["self.", "this.", "cls."]
80 .iter()
81 .any(|p| sig.starts_with(p))
82 }) =>
83 {
84 "attribute"
85 }
86 (_, kind) => kind,
87 }
88}
89
90fn is_skippable_kind(kind: &str) -> bool {
91 matches!(kind, "variable" | "parameter" | "import")
92}
93
94fn value_row_signature(sig: &str) -> std::borrow::Cow<'_, str> {
97 let sig = sig.trim_end().trim_end_matches(';').trim_end();
98 if !sig.contains('\n') && sig.chars().count() <= 120 {
99 return sig.into();
100 }
101 let joined = one_line(sig);
102 let Some(equals) = value_equals(&joined) else {
103 if joined.chars().count() <= 120 {
104 return joined.into();
105 }
106 let cut: String = joined.chars().take(119).collect();
107 return format!("{}…", cut.trim_end()).into();
108 };
109 let (declaration, value) = joined.split_at(equals);
110 let budget = 120usize.saturating_sub(declaration.chars().count()).max(40);
111 if value.chars().count() <= budget {
112 return joined.into();
113 }
114 let cut: String = value.chars().take(budget - 1).collect();
115 format!("{declaration}{}…", cut.trim_end()).into()
116}
117
118fn one_line(sig: &str) -> String {
120 let mut joined = sig
121 .lines()
122 .map(|line| {
123 let code = [" # ", " // "]
124 .iter()
125 .filter_map(|marker| line.find(marker))
126 .min()
127 .map_or(line, |at| &line[..at]);
128 code.trim().trim_end_matches('\\').trim_end()
129 })
130 .filter(|line| !line.is_empty())
131 .collect::<Vec<_>>()
132 .join(" ");
133 for (from, to) in [
134 ("( ", "("),
135 ("[ ", "["),
136 ("{ ", "{"),
137 (", )", ")"),
138 (", ]", "]"),
139 (", }", "}"),
140 (" )", ")"),
141 (" ]", "]"),
142 (" }", "}"),
143 ] {
144 joined = joined.replace(from, to);
145 }
146 joined
147}
148
149fn assigns_a_value(sig: &str) -> bool {
152 value_equals(sig).is_some()
153}
154
155fn value_equals(sig: &str) -> Option<usize> {
157 let bytes = sig.as_bytes();
158 let mut depth = 0usize;
159 for (i, &byte) in bytes.iter().enumerate() {
160 match byte {
161 b'(' | b'[' => depth += 1,
162 b')' | b']' => depth = depth.saturating_sub(1),
163 b'{' if depth == 0 => return None,
164 b'=' if depth == 0 => {
165 let before = i.checked_sub(1).map(|j| bytes[j]);
166 let after = bytes.get(i + 1).copied();
167 let operator_before = before.is_some_and(|b| b"<>!=^*~|$+-/%&:?".contains(&b));
168 let operator_after = after.is_some_and(|b| b == b'=' || b == b'>');
169 if !operator_before && !operator_after {
170 return Some(i);
171 }
172 }
173 _ => {}
174 }
175 }
176 None
177}
178
179fn sanitize_skeleton_sig<'a>(sig: &'a str, sym: &'a Symbol) -> std::borrow::Cow<'a, str> {
180 if matches!(
181 sym.kind.as_str(),
182 "variable" | "constant" | "property" | "field" | "enum_member"
183 ) && assigns_a_value(sig)
184 {
185 return value_row_signature(sig);
186 }
187 container_signature(sig, sym)
188}
189
190fn container_signature<'a>(sig: &'a str, sym: &'a Symbol) -> std::borrow::Cow<'a, str> {
192 let expression_arrow = if sym.language == "csharp"
193 && matches!(
194 sym.kind.as_str(),
195 "method" | "function" | "constructor" | "operator"
196 ) {
197 sig.match_indices("=>")
198 .find_map(|(idx, _)| sig[..idx].trim_end().ends_with(')').then_some(idx))
199 } else {
200 None
201 };
202 let cutoff = sig
203 .find('{')
204 .into_iter()
205 .chain(expression_arrow)
206 .min()
207 .unwrap_or(sig.len());
208 let clean = sig[..cutoff].trim_end();
209 let trimmed = clean.trim_end_matches(';').trim_end();
210 if trimmed.is_empty() {
211 sym.name.as_str().into()
212 } else {
213 trimmed.into()
214 }
215}
216
217fn signature_without_duplicate_body<'a>(signature: &'a str, body: &str) -> &'a str {
218 let body = body.trim();
219 if body.is_empty() {
220 return signature;
221 }
222
223 let trimmed_signature = signature.trim_end();
224 trimmed_signature
225 .strip_suffix(body)
226 .map(str::trim_end)
227 .unwrap_or(signature)
228}
229
230fn unspelled_kind(sym: &Symbol) -> &'static str {
234 if sym.kind != "event" {
235 return "";
236 }
237 let spelled = sym.signature.as_deref().is_some_and(|sig| {
238 sig.split_whitespace()
239 .any(|word| word == "signal" || word == "event")
240 });
241 if spelled { "" } else { "event " }
242}
243
244fn assigning_method(
247 sym: &Symbol,
248 parent: Option<&Symbol>,
249 children_map: &HashMap<Option<String>, Vec<&Symbol>>,
250) -> String {
251 if !sym
252 .signature
253 .as_deref()
254 .is_some_and(|sig| sig.starts_with("self."))
255 {
256 return String::new();
257 }
258 parent
259 .and_then(|parent| children_map.get(&Some(parent.symbol_id.clone())))
260 .and_then(|siblings| {
261 siblings.iter().find(|method| {
262 matches!(method.kind.as_str(), "method" | "function" | "constructor")
263 && method.start_line <= sym.start_line
264 && sym.end_line <= method.end_line
265 })
266 })
267 .map_or_else(String::new, |method| format!("in {}(), ", method.name))
268}
269
270fn is_shown(sym: &Symbol, parent: Option<&Symbol>) -> bool {
273 let python_declaration = sym.kind == "variable"
274 && sym.language == "python"
275 && parent.is_none_or(|parent| parent.kind == "class");
276 !is_skippable_kind(&sym.kind) || python_declaration
277}
278
279fn is_misparsed_c_function(child: &Symbol) -> bool {
284 matches!(child.language.as_str(), "c" | "cpp")
285 && matches!(child.kind.as_str(), "function" | "method")
286 && !child.is_test
287 && !child.test_container
288}
289
290fn nested_definitions(children: &[&Symbol]) -> String {
291 let names: Vec<String> = children
292 .iter()
293 .filter(|child| {
294 matches!(
295 child.kind.as_str(),
296 "function" | "method" | "class" | "struct"
297 )
298 })
299 .filter(|child| {
300 !child
301 .signature
302 .as_deref()
303 .is_some_and(|sig| sig.starts_with("lambda"))
304 })
305 .filter(|child| !is_misparsed_c_function(child))
306 .map(|child| format!("`{}`", child.name))
307 .fold(Vec::new(), |mut names, name| {
308 if !names.contains(&name) {
309 names.push(name);
310 }
311 names
312 });
313 match names.len() {
314 0 => String::new(),
315 1..=5 => format!("; defines {}", names.join(", ")),
316 n => format!("; defines {}, +{} more", names[..5].join(", "), n - 5),
317 }
318}
319
320fn render_symbol_skeleton(
321 out: &mut String,
322 sym: &Symbol,
323 parent: Option<&Symbol>,
324 children_map: &HashMap<Option<String>, Vec<&Symbol>>,
325 indent_level: usize,
326) {
327 if !is_shown(sym, parent) {
328 return;
329 }
330
331 let indent = " ".repeat(indent_level);
332
333 if let Some(ref doc) = sym.doc_comment {
334 let document = crate::queries::DOCUMENTATION_LANGUAGES.contains(&sym.language.as_str());
335 let lines: Vec<_> = if document {
336 doc.lines().collect()
337 } else {
338 doc.lines()
339 .map(doc_line_text)
340 .filter(|line| !line.is_empty())
341 .collect()
342 };
343 let cap = 3;
344 for line in lines.iter().take(cap) {
345 out.push_str(&format!("{indent}/// {line}\n"));
346 }
347 if lines.len() > cap {
348 out.push_str(&format!(
349 "{indent}/// ... ({} more lines)\n",
350 lines.len() - cap
351 ));
352 }
353 }
354
355 let span_str = format!("L{}-{}", sym.start_line, sym.end_line);
356 let leaf_note = format!(
357 "{}{}{span_str}",
358 unspelled_kind(sym),
359 assigning_method(sym, parent, children_map)
360 );
361
362 let children = children_map.get(&Some(sym.symbol_id.clone()));
363
364 let spans_multiple_lines = sym.end_line > sym.start_line;
365
366 if is_container_kind(&sym.kind)
367 && children.is_some_and(|list| list.iter().any(|child| is_shown(child, Some(sym))))
368 && (spans_multiple_lines || sym.kind == "enum")
369 {
370 let raw_sig = sym.signature.as_deref().unwrap_or(&sym.name);
371 let sig = container_signature(raw_sig, sym);
372 out.push_str(&format!("{indent}{sig} {{\n"));
373 if let Some(child_list) = children {
374 for child in child_list {
375 render_symbol_skeleton(out, child, Some(sym), children_map, indent_level + 1);
376 }
377 }
378 out.push_str(&format!("{indent}}} // {span_str}\n\n"));
379 } else {
380 if let Some(count) = sym.hidden_body_line_count() {
381 let raw_sig = sym.signature.as_deref().unwrap_or(&sym.name);
382 let sig = if count > 1 {
383 container_signature(raw_sig, sym)
384 } else {
385 sanitize_skeleton_sig(raw_sig, sym)
386 };
387 let b_start = sym.body_start_line.unwrap_or(sym.start_line);
388 let b_end = sym.body_end_line.unwrap_or(sym.end_line);
389
390 if count > 1 {
391 let defines = nested_definitions(children.map(Vec::as_slice).unwrap_or_default());
392 out.push_str(&format!(
393 "{indent}{sig} {{ /* {count} lines hidden: L{b_start}-L{b_end}{defines} */ }}\n"
394 ));
395 } else {
396 out.push_str(&format!("{indent}{sig}; // {leaf_note}\n"));
397 }
398 } else if let Some(ref raw_sig) = sym.signature {
399 let sig = sanitize_skeleton_sig(raw_sig, sym);
400 out.push_str(&format!("{indent}{sig}; // {leaf_note}\n"));
401 } else {
402 out.push_str(&format!(
403 "{indent}{} {sym_name}; // {span_str}\n",
404 display_kind(sym),
405 sym_name = sym.name
406 ));
407 }
408 if sym.kind == "namespace"
409 && let Some(child_list) = children
410 {
411 for child in child_list {
412 render_symbol_skeleton(out, child, Some(sym), children_map, indent_level);
413 }
414 }
415 }
416}
417
418#[derive(Default)]
420pub struct OutlineNode {
421 pub files: BTreeMap<String, Vec<String>>, pub subdirs: BTreeMap<String, OutlineNode>,
423 pub hidden_files: usize,
425 pub plain_files: Vec<String>,
427 pub unsupported_files: usize,
429}
430
431fn outline_components(file_path: &str, norm_filter: &str) -> Option<Vec<String>> {
434 let normalized = file_path.replace('\\', "/");
435 let rel_path_str = if norm_filter.is_empty() {
436 normalized.as_str()
437 } else if normalized.eq_ignore_ascii_case(norm_filter) {
438 Path::new(&normalized)
439 .file_name()
440 .and_then(|n| n.to_str())
441 .unwrap_or(&normalized)
442 } else if normalized.len() > norm_filter.len()
443 && normalized.as_bytes()[norm_filter.len()] == b'/'
444 && normalized[..norm_filter.len()].eq_ignore_ascii_case(norm_filter)
445 {
446 &normalized[norm_filter.len() + 1..]
447 } else {
448 return None;
449 };
450
451 let path = Path::new(rel_path_str);
452 let components: Vec<String> = path
453 .components()
454 .map(|c| c.as_os_str().to_str().unwrap_or(""))
455 .filter(|s| !s.is_empty())
456 .map(str::to_string)
457 .collect();
458
459 if components.is_empty() {
460 return None;
461 }
462
463 Some(components)
464}
465
466pub fn add_unsupported_to_outline(
469 root_node: &mut OutlineNode,
470 file_path: &str,
471 max_depth: usize,
472 norm_filter: &str,
473) {
474 let Some(components) = outline_components(file_path, norm_filter) else {
475 return;
476 };
477 let mut curr = root_node;
478 for (i, comp) in components
479 .iter()
480 .take(components.len() - 1)
481 .take(max_depth)
482 .enumerate()
483 {
484 if i > 0 && !curr.subdirs.contains_key(comp) {
485 break;
486 }
487 curr = curr.subdirs.entry(comp.clone()).or_default();
488 }
489 curr.unsupported_files += 1;
490}
491
492pub fn add_path_to_outline(
494 root_node: &mut OutlineNode,
495 file_path: &str,
496 symbols_by_file: &HashMap<String, Vec<Symbol>>,
497 counts: &HashMap<String, crate::queries::OutlineCounts>,
498 max_depth: usize,
499 norm_filter: &str,
500) {
501 let Some(components) = outline_components(file_path, norm_filter) else {
502 return;
503 };
504 let normalized = file_path.replace('\\', "/");
505
506 let mut curr = root_node;
507 let depth = components.len();
508
509 for (i, comp) in components.iter().enumerate() {
510 if i == depth - 1 {
511 if depth > max_depth {
512 curr.hidden_files += 1;
513 } else {
514 let mut sym_tags: Vec<String> = symbols_by_file
515 .get(&normalized)
516 .into_iter()
517 .flatten()
518 .filter(|s| !s.is_test && !s.test_container)
519 .take(5)
520 .map(|s| format!("{} {}", display_kind(s), s.name))
521 .collect();
522 let count = counts.get(&normalized).copied().unwrap_or_default();
523 if count.definitions > sym_tags.len() {
524 sym_tags.push(format!("+{} more", count.definitions - sym_tags.len()));
525 }
526 if count.tests > 0 {
527 sym_tags.push(format!("{} {}", count.tests, plural(count.tests, "test")));
528 }
529 if count.fixtures > 0 {
530 sym_tags.push(format!(
531 "{} {}",
532 count.fixtures,
533 plural(count.fixtures, "fixture")
534 ));
535 }
536 if sym_tags.is_empty() {
537 curr.plain_files.push(comp.to_string());
538 } else {
539 curr.files.insert(comp.to_string(), sym_tags);
540 }
541 }
542 } else if i < max_depth {
543 curr = curr.subdirs.entry(comp.to_string()).or_default();
544 } else {
545 curr.hidden_files += 1;
546 break;
547 }
548 }
549}
550
551const FILES_LISTED_PER_FOLDER: usize = 40;
553
554pub fn render_outline_tree(
555 out: &mut String,
556 node: &OutlineNode,
557 prefix: &str,
558 depth: usize,
559 max_depth: usize,
560) {
561 if depth >= max_depth {
562 return;
563 }
564
565 let listed = if depth == 0 {
566 node.files.len()
567 } else {
568 node.files.len().min(FILES_LISTED_PER_FOLDER)
569 };
570 let more_files = node.files.len() - listed;
571 let total_items = node.subdirs.len()
572 + listed
573 + usize::from(more_files > 0)
574 + usize::from(!node.plain_files.is_empty());
575 let mut index = 0;
576
577 for (name, sub) in &node.subdirs {
579 index += 1;
580 let is_last = index == total_items;
581 let branch = if is_last { "└── " } else { "├── " };
582 let next_prefix = format!("{}{}", prefix, if is_last { " " } else { "│ " });
583
584 let hidden = match (sub.hidden_files, sub.unsupported_files) {
585 (0, 0) => String::new(),
586 (0, m) => format!(" ({m} unsupported {})", plural(m, "file")),
587 (n, 0) => format!(" ({n} indexed {})", plural(n, "file")),
588 (n, m) => format!(" ({n} indexed {}, {m} unsupported)", plural(n, "file")),
589 };
590 out.push_str(&format!("{prefix}{branch}{name}/{hidden}\n"));
591 render_outline_tree(out, sub, &next_prefix, depth + 1, max_depth);
592 }
593
594 for (file_name, syms) in node.files.iter().take(listed) {
596 index += 1;
597 let is_last = index == total_items;
598 let branch = if is_last { "└── " } else { "├── " };
599
600 let sym_suffix = if !syms.is_empty() {
601 format!(" [{}]", syms.join(", "))
602 } else {
603 String::new()
604 };
605
606 out.push_str(&format!("{prefix}{branch}{file_name}{sym_suffix}\n"));
607 }
608
609 if more_files > 0 {
610 index += 1;
611 let branch = if index == total_items {
612 "└── "
613 } else {
614 "├── "
615 };
616 out.push_str(&format!(
617 "{prefix}{branch}(+{more_files} more {} with functions or classes; pass this folder as the path to list them)\n",
618 plural(more_files, "file")
619 ));
620 }
621
622 if !node.plain_files.is_empty() {
623 let count = node.plain_files.len();
624 let names = if count <= 5 {
625 node.plain_files.join(", ")
626 } else {
627 format!("{}, +{} more", node.plain_files[..3].join(", "), count - 3)
628 };
629 out.push_str(&format!(
630 "{prefix}└── ({count} {} without functions or classes: {names})\n",
631 plural(count, "file")
632 ));
633 }
634}
635
636pub fn format_symbol_body(symbol: &Symbol, source: &str) -> String {
639 let mut out = format!(
640 "// {}:{}-{} ({})\n{source}",
641 symbol.path, symbol.start_line, symbol.end_line, symbol.name
642 );
643 if !source.ends_with('\n') {
644 out.push('\n');
645 }
646 out
647}
648
649pub fn format_context_slice(slice: &ContextSlice) -> String {
651 let sym = &slice.target_symbol;
652 let mut out = String::new();
653 out.push_str(&format!(
654 "### Target: `{}` ({}:{}-{})\n\n",
655 sym.name, sym.path, sym.start_line, sym.end_line
656 ));
657
658 if let Some(ref sig) = sym.signature {
659 let sig = signature_without_duplicate_body(sig, &slice.target_body);
660 if !sig.trim().is_empty() {
661 out.push_str(&format!("Signature: `{sig}`\n\n"));
662 }
663 }
664
665 out.push_str(&format!("```{}\n", sym.language));
666 out.push_str(&slice.target_body);
667 if !slice.target_body.ends_with('\n') {
668 out.push('\n');
669 }
670 out.push_str("```\n\n");
671
672 if !slice.callee_signatures.is_empty() {
673 out.push_str("### Dependencies (Signatures):\n");
674 for callee in &slice.callee_signatures {
675 out.push_str(&format!("- {callee}\n"));
676 }
677 if slice.callee_signatures.len() >= 10 {
678 out.push_str("[Showing 10 dependencies (limit reached)]\n");
679 }
680 out.push('\n');
681 }
682
683 if !slice.related_types.is_empty() {
684 out.push_str("### Types:\n");
685 for t in &slice.related_types {
686 out.push_str(&format!("- {t}\n"));
687 }
688 out.push('\n');
689 }
690
691 if !slice.related_tests.is_empty() {
692 out.push_str("### Related Tests:\n");
693 for test in &slice.related_tests {
694 out.push_str(&format!(
695 "- `{}` ({}:{})\n",
696 test.name, test.path, test.start_line
697 ));
698 }
699 if slice.related_tests.len() >= 5 {
700 out.push_str("[Showing 5 tests (limit reached)]\n");
701 }
702 out.push_str("These tests call, use, or name this symbol; blast_radius also lists tests that can reach it through callers.\n\n");
703 } else {
704 out.push_str(
705 "### Related Tests:\nNo test calls, uses, or names this symbol; blast_radius lists tests that can reach it through callers.\n",
706 );
707 }
708
709 out
710}
711
712fn cap_notice(shown: usize, limit: usize) -> String {
713 let advice = if limit >= crate::queries::MAX_RESULT_LIMIT {
714 "narrow the query to see more"
715 } else {
716 "increase limit to see more"
717 };
718 format!("\n[Showing {shown} results (limit reached); {advice}.]\n")
719}
720
721fn match_line(snippet: &str, signature: &str) -> Option<String> {
724 let line = snippet
725 .lines()
726 .enumerate()
727 .map(|(i, text)| match i {
728 0 => text.trim(),
729 _ => text.trim().trim_start_matches(['/', '*', '!']).trim(),
730 })
731 .flat_map(str::split_whitespace)
732 .collect::<Vec<_>>()
733 .join(" ");
734 let plain = |text: &str| {
735 text.split_whitespace()
736 .collect::<String>()
737 .replace(['[', ']'], "")
738 };
739 let matched = plain(line.trim_start_matches("...").trim_end_matches("..."));
740 (!line.is_empty() && !plain(signature).contains(&matched)).then_some(line)
741}
742
743fn callee_name(name: &str) -> String {
746 let line = name.split_whitespace().collect::<Vec<_>>().join(" ");
747 if line.chars().count() <= 60 || !line.contains('(') {
748 return line;
749 }
750 match line.rsplit_once('.') {
751 Some((_, last)) if !last.is_empty() => format!("….{last}"),
752 _ => line,
753 }
754}
755
756pub fn format_import_summary(sites: &[(String, usize)]) -> String {
759 if sites.is_empty() {
760 return String::new();
761 }
762 let files: std::collections::BTreeSet<&str> =
763 sites.iter().map(|(path, _)| path.as_str()).collect();
764 let first: Vec<String> = sites
765 .iter()
766 .take(3)
767 .map(|(path, line)| format!("{path}:{line}"))
768 .collect();
769 let more = if sites.len() > 3 { ", …" } else { "" };
770 format!(
771 "Imported {} {} in {} {}: {}{more} (lookup_symbol with kind=\"import\" lists them)\n",
772 sites.len(),
773 plural(sites.len(), "time"),
774 files.len(),
775 plural(files.len(), "file"),
776 first.join(", ")
777 )
778}
779
780pub fn format_references(
781 target_name: &str,
782 refs: &[ReferenceSite],
783 direction: &str,
784 limit: usize,
785) -> String {
786 let mut out = String::new();
787 let dir_label = if direction == "callers" {
788 "Callers of"
789 } else {
790 "Callees called by"
791 };
792 out.push_str(&format!(
793 "{dir_label} `{target_name}` ({} found):\n",
794 refs.len()
795 ));
796
797 if refs.is_empty() {
798 out.push_str(" (none)\n");
799 return out;
800 }
801
802 for r in refs {
803 let line_info = match r.start_line {
804 Some(l) => format!(":{l}"),
805 None => String::new(),
806 };
807 let other = if direction == "callers" {
808 r.from_symbol_name.clone()
809 } else {
810 callee_name(&r.to_symbol_name)
811 };
812 let in_file = match r.occurrences {
813 Some(n) => format!(", {n} in file"),
814 None => String::new(),
815 };
816 let target = match &r.target {
817 Some(target) if direction != "callers" => format!(" → {target}"),
818 _ => String::new(),
819 };
820 out.push_str(&format!(
821 "- `{other}` [{}{line_info}] (kind: {}{in_file}){target}\n",
822 r.path, r.kind
823 ));
824 }
825
826 if refs.len() >= limit {
827 out.push_str(&cap_notice(refs.len(), limit));
828 }
829
830 out
831}
832
833fn other_names_line(query: &str, others: &[&Symbol]) -> String {
837 let mut groups: Vec<(String, &str, usize)> = Vec::new();
838 for s in others {
839 let kind = display_kind(s);
840 match groups
841 .iter_mut()
842 .find(|(name, k, _)| *name == s.name && *k == kind)
843 {
844 Some(group) => group.2 += 1,
845 None => groups.push((s.name.clone(), kind, 1)),
846 }
847 }
848 let listed: Vec<String> = groups
849 .iter()
850 .take(8)
851 .map(|(name, kind, count)| match count {
852 1 => format!("`{name}` ({kind})"),
853 n => format!("`{name}` ({kind}, {n}×)"),
854 })
855 .collect();
856 let more = match groups.len().saturating_sub(8) {
857 0 => String::new(),
858 n => format!(", +{n} more"),
859 };
860 format!(
861 "- {} other {} `{query}`, ignoring case: {}{more} (lookup_symbol with one of these names lists its rows)\n",
862 others.len(),
863 if others.len() == 1 {
864 "row starts with or contains"
865 } else {
866 "rows start with or contain"
867 },
868 listed.join(", ")
869 )
870}
871
872fn doc_line_text(line: &str) -> &str {
875 let mut text = line.trim();
876 for marker in [
877 "///", "//!", "//", "/**", "/*!", "/*", "##", "#'", "#", "--", "*", "'''", "'",
878 ] {
879 if let Some(rest) = text.strip_prefix(marker) {
880 text = rest.trim_start();
881 break;
882 }
883 }
884 for tag in ["<summary>", "</summary>"] {
885 text = text.strip_prefix(tag).unwrap_or(text).trim_start();
886 }
887 for suffix in ["*/", "</summary>"] {
888 text = text.strip_suffix(suffix).unwrap_or(text).trim_end();
889 }
890 text
891}
892
893fn sentence_end(text: &str) -> Option<usize> {
896 let mut depth = 0usize;
897 for (index, c) in text.char_indices() {
898 match c {
899 '(' => depth += 1,
900 ')' => depth = depth.saturating_sub(1),
901 '.' if depth == 0 => {
902 let rest = &text[index + 1..];
903 if rest.starts_with(' ') && !rest[1..].starts_with(|next: char| next.is_lowercase())
904 {
905 return Some(index);
906 }
907 }
908 _ => {}
909 }
910 }
911 None
912}
913
914fn doc_summary(doc: &str) -> Option<String> {
917 let paragraph = doc
918 .lines()
919 .map(doc_line_text)
920 .skip_while(|line| line.is_empty())
921 .take_while(|line| !line.is_empty())
922 .collect::<Vec<_>>()
923 .join(" ");
924 let summary = match sentence_end(¶graph) {
925 Some(end) => paragraph[..=end].to_string(),
926 None if paragraph.chars().count() > 200 => {
927 format!("{}…", paragraph.chars().take(200).collect::<String>())
928 }
929 None => paragraph,
930 };
931 (!summary.is_empty()).then_some(summary)
932}
933
934pub fn format_find_symbol_results(
935 query: &str,
936 exact_matches: &[Symbol],
937 fts_matches: &[SymbolSearchResult],
938 limit: usize,
939) -> String {
940 if !exact_matches.is_empty() {
941 let dotted = query.replace("::", ".");
942 let is_exact = |s: &Symbol| s.name == dotted || s.name.ends_with(&format!(".{dotted}"));
943 let named_exactly = exact_matches.iter().filter(|s| is_exact(s)).count();
944 let exact_note = if named_exactly < exact_matches.len() {
945 format!(" ({named_exactly} named exactly `{query}`; the rest start with or contain it)")
946 } else {
947 String::new()
948 };
949 let owner = query
950 .strip_suffix("::")
951 .or_else(|| query.strip_suffix('.'))
952 .filter(|owner| !owner.is_empty());
953 let mut out = match owner {
954 Some(owner) => format!("Found {} members of `{owner}`:\n\n", exact_matches.len()),
955 None => format!(
956 "Found {} symbols matching \"{query}\"{exact_note}:\n\n",
957 exact_matches.len()
958 ),
959 };
960 let has_definition = exact_matches.iter().any(|s| s.kind != "import");
961 let folds = |s: &Symbol| crate::queries::folds_into_import_line(query, s, has_definition);
962 let imports: Vec<&Symbol> = exact_matches.iter().filter(|s| folds(s)).collect();
963 let (shown, others): (Vec<&Symbol>, Vec<&Symbol>) = exact_matches
964 .iter()
965 .filter(|s| !folds(s))
966 .partition(|s| named_exactly == 0 || is_exact(s));
967 for s in shown {
968 let sig = s.signature.as_deref().unwrap_or(&s.name);
969 out.push_str(&format!(
970 "- {} `{}` [{}:{}-{}] id={}\n",
971 display_kind(s),
972 s.name,
973 s.path,
974 s.start_line,
975 s.end_line,
976 s.symbol_id
977 ));
978 out.push_str(&format!(" Signature: {sig}\n"));
979 if let Some(doc) = s.doc_comment.as_deref().and_then(doc_summary) {
980 out.push_str(&format!(" Doc: {doc}\n"));
981 }
982 }
983 if !imports.is_empty() {
984 let shown = imports
985 .iter()
986 .take(3)
987 .map(|s| format!("{}:{}", s.path, s.start_line))
988 .collect::<Vec<_>>()
989 .join(", ");
990 let more = if imports.len() > 3 { ", …" } else { "" };
991 let cut_inside_exact_names = exact_matches
992 .last()
993 .is_some_and(|s| s.name.eq_ignore_ascii_case(query) || folds(s));
994 let capped = if exact_matches.len() - imports.len() >= limit && cut_inside_exact_names {
995 "at least "
996 } else {
997 ""
998 };
999 out.push_str(&format!(
1000 "- {capped}{} {} of `{query}`: {shown}{more} (lookup_symbol with kind=\"import\" lists them)\n",
1001 imports.len(),
1002 plural(imports.len(), "import")
1003 ));
1004 }
1005 if !others.is_empty() {
1006 out.push_str(&other_names_line(query, &others));
1007 }
1008 if exact_matches.len() - imports.len() >= limit {
1009 out.push_str(&cap_notice(exact_matches.len() - imports.len(), limit));
1010 }
1011 out
1012 } else if !fts_matches.is_empty() {
1013 let mut out = format!(
1014 "No exact name match; {} full-text matches for \"{query}\":\n\n",
1015 fts_matches.len()
1016 );
1017 for r in fts_matches {
1018 let s = &r.symbol;
1019 let sig = s.signature.as_deref().unwrap_or(&s.name);
1020 out.push_str(&format!(
1021 "- {} `{}` [{}:{}-{}] (score: {:.2}) id={}\n",
1022 display_kind(s),
1023 s.name,
1024 s.path,
1025 s.start_line,
1026 s.end_line,
1027 r.score,
1028 s.symbol_id
1029 ));
1030 out.push_str(&format!(" Signature: {sig}\n"));
1031 if let Some(line) = r.snippet.as_deref().and_then(|m| match_line(m, sig)) {
1032 out.push_str(&format!(" Match: {line}\n"));
1033 } else if let Some(doc) = s.doc_comment.as_deref().and_then(doc_summary) {
1034 out.push_str(&format!(" Doc: {doc}\n"));
1035 }
1036 }
1037 if fts_matches.len() >= limit {
1038 out.push_str(&cap_notice(fts_matches.len(), limit));
1039 }
1040 out
1041 } else {
1042 format!("No symbols found matching \"{query}\".\n")
1043 }
1044}
1045
1046pub fn no_facts_heading(category: &str, path_filter: Option<&str>) -> String {
1049 match path_filter {
1050 Some(path) => format!("No facts match '{category}' under `{path}`."),
1051 None => format!("No facts match '{category}' in this repository."),
1052 }
1053}
1054
1055pub fn format_no_facts(
1059 category: &str,
1060 path_filter: Option<&str>,
1061 categories: &[(String, usize)],
1062) -> String {
1063 let mut out = format!("{}\n\n", no_facts_heading(category, path_filter));
1064 if !crate::queries::is_category_alias(category) {
1065 out.push_str(&format_fact_categories(categories));
1066 return out;
1067 }
1068 if matches!(category.to_ascii_lowercase().as_str(), "import" | "imports") {
1069 out.push_str("Most languages record imports as symbols: lookup_symbol with kind=\"import\" lists them.\n\n");
1070 }
1071 out.push_str(&alias_summary(categories));
1072 out
1073}
1074
1075fn alias_summary(categories: &[(String, usize)]) -> String {
1076 let aliases = crate::queries::alias_fact_counts(categories);
1077 if aliases.is_empty() {
1078 return String::new();
1079 }
1080 let parts: Vec<String> = aliases
1081 .iter()
1082 .map(|(alias, patterns, facts)| {
1083 format!(
1084 "{alias} ({patterns} {}, {facts} {})",
1085 plural(*patterns, "pattern"),
1086 plural(*facts, "fact")
1087 )
1088 })
1089 .collect();
1090 format!("Aliases: {}\n\n", parts.join(", "))
1091}
1092
1093pub fn format_fact_categories(categories: &[(String, usize)]) -> String {
1094 if categories.is_empty() {
1095 return "No structural facts or literals indexed in this repository.".to_string();
1096 }
1097 let mut out = String::new();
1098 out.push_str(&alias_summary(categories));
1099 let (patterns, literal_kinds): (Vec<_>, Vec<_>) = categories
1101 .iter()
1102 .filter(|(name, _)| !name.ends_with(".decorated_definition.v1"))
1103 .partition(|(name, _)| name.contains('.'));
1104 out.push_str(&format!(
1105 "Available structural fact categories ({} found):\n\n",
1106 patterns.len()
1107 ));
1108 for (name, count) in &patterns {
1109 out.push_str(&format!(
1110 "- `{name}` ({count} {})\n",
1111 plural(*count, "fact")
1112 ));
1113 }
1114 if !literal_kinds.is_empty() {
1115 out.push_str("\nString literal kinds (the same command lists the literals of a kind):\n\n");
1116 for (name, count) in &literal_kinds {
1117 out.push_str(&format!(
1118 "- `{name}` ({count} {})\n",
1119 plural(*count, "literal")
1120 ));
1121 }
1122 }
1123 out
1124}
1125
1126fn plural(count: usize, word: &str) -> String {
1127 if count == 1 {
1128 word.to_string()
1129 } else {
1130 format!("{word}s")
1131 }
1132}
1133
1134pub fn format_structural_facts(
1136 facts: &[crate::models::StructuralFact],
1137 literals: &[crate::models::LiteralFact],
1138 category: &str,
1139 limit: usize,
1140) -> String {
1141 let mut out = format!(
1142 "Structural facts for '{category}' ({} found):\n",
1143 facts.len()
1144 );
1145 for f in facts {
1146 let label = f.key.as_deref().unwrap_or(&f.capture_name);
1147 let details = format!("{}{}", qt_property_details(f), flask_route_details(f));
1148 let api_style = f
1149 .metadata
1150 .as_ref()
1151 .and_then(|m| m.get("api_style"))
1152 .and_then(|v| v.as_str());
1153 let place = match api_style {
1154 Some("decorator_routing") => "handler",
1155 Some("call_routing") => "registered in",
1156 _ => "in",
1157 };
1158 let parent = f
1159 .containing_symbol_name
1160 .as_deref()
1161 .map(|p| format!(", {place}: {p}"))
1162 .unwrap_or_default();
1163 out.push_str(&format!(
1164 "- {label} [{}:{}] (pattern: {}{details}{parent})\n",
1165 f.path, f.start_line, f.pattern_id
1166 ));
1167 }
1168 if limit > 0 && facts.len() >= limit {
1169 out.push_str(&cap_notice(facts.len(), limit));
1170 }
1171 if facts
1172 .iter()
1173 .any(|f| f.pattern_id.starts_with("flask.route"))
1174 {
1175 out.push_str("Routes as declared in the source. By default Flask also answers HEAD for GET and OPTIONS for every rule, and serves `/static/<path:filename>`; the app or a rule can turn these off.\n");
1176 }
1177 if !literals.is_empty() {
1178 out.push_str(&format!(
1179 "\nMatching literals ({} found):\n",
1180 literals.len()
1181 ));
1182 for l in literals {
1183 out.push_str(&format!(
1184 "- \"{}\" [{}:{}] (kind: {})\n",
1185 l.literal_text, l.path, l.start_line, l.kind
1186 ));
1187 }
1188 if limit > 0 && literals.len() >= limit {
1189 out.push_str(&cap_notice(literals.len(), limit));
1190 }
1191 }
1192 out
1193}
1194
1195fn flask_route_details(fact: &crate::models::StructuralFact) -> String {
1198 if !fact.pattern_id.starts_with("flask.route") {
1199 return String::new();
1200 }
1201 let Some(metadata) = fact.metadata.as_ref() else {
1202 return String::new();
1203 };
1204 let text = |key: &str| metadata.get(key).and_then(|v| v.as_str());
1205 let mut out = String::new();
1206 if let Some(endpoint) = text("endpoint") {
1207 out.push_str(&format!(", endpoint: {endpoint}"));
1208 }
1209 if text("api_style") == Some("call_routing") {
1210 match text("view_target") {
1211 Some(view) => out.push_str(&format!(", view: {view}")),
1212 None => out.push_str(", no view function"),
1213 }
1214 }
1215 out
1216}
1217
1218fn qt_property_details(fact: &crate::models::StructuralFact) -> String {
1219 if fact.pattern_id != "cpp.qt_property.v1" {
1220 return String::new();
1221 }
1222 let Some(metadata) = fact.metadata.as_ref() else {
1223 return String::new();
1224 };
1225 [
1226 "property_type",
1227 "read",
1228 "write",
1229 "notify",
1230 "designable",
1231 "scriptable",
1232 "stored",
1233 "user",
1234 "revision",
1235 ]
1236 .into_iter()
1237 .filter_map(|key| metadata.get(key).map(|value| (key, value)))
1238 .map(|(key, value)| {
1239 let value = value
1240 .as_str()
1241 .map(str::to_owned)
1242 .unwrap_or_else(|| value.to_string());
1243 format!(", {key}: {value}")
1244 })
1245 .collect()
1246}
1247
1248pub fn format_search_results(query: &str, results: &[SymbolSearchResult], limit: usize) -> String {
1250 if results.is_empty() {
1251 return format!("No symbols found matching concept \"{query}\".");
1252 }
1253
1254 let mut out = format!(
1255 "Found {} symbols matching concept \"{query}\":\n",
1256 results.len()
1257 );
1258 if let Some(explain) = results.first().and_then(|r| r.explain.as_ref()) {
1259 out.push_str(&format!(
1260 "rerank: {} candidates in {} µs",
1261 explain.candidates, explain.rerank_us
1262 ));
1263 if !explain.word_weights.is_empty() {
1264 let words: Vec<String> = explain
1265 .word_weights
1266 .iter()
1267 .map(|(word, weight)| format!("{word} {weight:.2}"))
1268 .collect();
1269 out.push_str(&format!("; words {}", words.join(", ")));
1270 }
1271 out.push('\n');
1272 }
1273 out.push('\n');
1274 for r in results {
1275 let s = &r.symbol;
1276 let sig = s.signature.as_deref().unwrap_or(&s.name);
1277 out.push_str(&format!(
1278 "- {} `{}` [{}:{}-{}] (score: {:.2}) id={}\n",
1279 display_kind(s),
1280 s.name,
1281 s.path,
1282 s.start_line,
1283 s.end_line,
1284 r.score,
1285 s.symbol_id
1286 ));
1287 out.push_str(&format!(" Signature: {sig}\n"));
1288 if let Some(line) = r.snippet.as_deref().and_then(|m| match_line(m, sig)) {
1289 out.push_str(&format!(" Match: {line}\n"));
1290 } else if let Some(doc) = s.doc_comment.as_deref().and_then(doc_summary) {
1291 out.push_str(&format!(" Doc: {doc}\n"));
1292 }
1293 if let Some(explain) = &r.explain {
1294 out.push_str(&format!(" explain: {}\n", explain_line(r.score, explain)));
1295 }
1296 }
1297
1298 if results.len() >= limit {
1299 out.push_str(&cap_notice(results.len(), limit));
1300 }
1301
1302 out
1303}
1304
1305fn explain_line(score: f64, e: &SearchExplain) -> String {
1306 let mut line = format!(
1307 "score {score:.1} = terms {:.1} + name {}({}) {:.1} + kind {:.1} + path {:.1}",
1308 e.term_score, e.name_tier, e.name_strength, e.name_bonus, e.kind_prior, e.path_role,
1309 );
1310 if e.documentation != 0.0 {
1311 line.push_str(&format!(" + doc {:.1}", e.documentation));
1312 }
1313 if e.test_intent != 0.0 {
1314 line.push_str(&format!(" + test {:.1}", e.test_intent));
1315 }
1316 if e.nested != 0.0 {
1317 line.push_str(&format!(" + nested {:.1}", e.nested));
1318 }
1319 line.push_str(&format!(" [{}]", e.branches.join(",")));
1320 if let Some(bm25) = e.bm25 {
1321 line.push_str(&format!(" bm25 {bm25:.2}"));
1322 }
1323 if !e.terms.is_empty() {
1324 let terms: Vec<String> = e
1325 .terms
1326 .iter()
1327 .map(|(term, field, credit)| format!("{term}={field}:{credit}"))
1328 .collect();
1329 line.push_str(&format!(" terms {}", terms.join(" ")));
1330 }
1331 line
1332}
1333
1334pub fn format_blast_radius(result: &BlastRadiusResult) -> String {
1336 if result.seed_type == "none" {
1337 return "No uncommitted changes detected in git working tree. Pass a 'symbol' or 'file' parameter to analyze blast radius.".to_string();
1338 }
1339
1340 let mut out = String::new();
1341 let seed_label = if result.seed_type == "file" {
1342 format!("Files: {}", result.seeds.join(", "))
1343 } else if result.seed_type == "symbol" {
1344 format!("Symbol: {}", result.seeds.join(", "))
1345 } else {
1346 format!("Seeds: {}", result.seeds.join(", "))
1347 };
1348
1349 out.push_str(&format!("## Blast Radius & Test Impact ({seed_label})\n\n"));
1350
1351 let more = if result.limit_at_maximum {
1352 "limit is at its maximum, so narrow the target to a symbol or fewer files"
1353 } else {
1354 "raise limit to see the rest"
1355 };
1356 let shown_of = |shown: usize, found: usize, noun: &str| {
1357 if found > shown {
1358 format!("Showing {shown} of {found} {noun}; {more}.\n\n")
1359 } else {
1360 format!("Requested limit hid additional {noun}; {more}.\n\n")
1361 }
1362 };
1363 if result.likely_tests_truncated {
1364 out.push_str(&shown_of(
1365 result.likely_tests.len(),
1366 result.likely_tests_found,
1367 "likely tests",
1368 ));
1369 }
1370 if result.impacted_symbols_truncated {
1371 out.push_str(&shown_of(
1372 result.impacted_symbols.len(),
1373 result.impacted_symbols_found,
1374 "impacted symbols",
1375 ));
1376 }
1377 if result.traversal_ceiling_reached {
1378 out.push_str("Traversal stopped at the 200-row discovery ceiling; narrow the target because increasing limit cannot raise this ceiling.\n\n");
1379 }
1380 if result.test_file_ceiling_reached {
1381 out.push_str("Name-matched test discovery hit its fixed ceiling; narrow the target because increasing limit cannot raise it.\n\n");
1382 }
1383
1384 if !result.likely_tests.is_empty() {
1385 let total = result.likely_tests.len();
1386 out.push_str(&format!("### Likely Tests to Run ({} returned)\n", total));
1387
1388 let mut tests_by_file: std::collections::BTreeMap<&str, Vec<&TestTarget>> =
1389 std::collections::BTreeMap::new();
1390 let mut file_order = Vec::new();
1391 for t in &result.likely_tests {
1392 if !tests_by_file.contains_key(t.path.as_str()) {
1393 file_order.push(t.path.as_str());
1394 }
1395 tests_by_file.entry(t.path.as_str()).or_default().push(t);
1396 }
1397
1398 for path in file_order {
1399 out.push_str(&format!("{path}:\n"));
1400 if let Some(tests) = tests_by_file.get(path) {
1401 for t in tests {
1402 out.push_str(&format!(
1403 " - `{}` [line {}] ({})\n",
1404 t.name, t.line, t.reason
1405 ));
1406 }
1407 }
1408 }
1409
1410 if result
1411 .likely_tests
1412 .iter()
1413 .any(|t| t.reason.starts_with("possible:"))
1414 {
1415 out.push_str("`possible` rows build the class and use a test client, so they reach the target only through a runtime call to `__call__`. The index picks them by shared name words and cannot see whether they send a call that reaches the target; run the whole suite for full coverage.\n");
1416 }
1417 out.push('\n');
1418 } else if result.likely_tests_truncated
1419 || result.traversal_ceiling_reached
1420 || result.test_file_ceiling_reached
1421 {
1422 out.push_str("### Likely Tests to Run (0 returned)\n\n");
1423 } else {
1424 out.push_str(
1425 "### Likely Tests to Run (0 returned)\nNo direct or name-matched tests found.\n\n",
1426 );
1427 }
1428
1429 if !result.impacted_symbols.is_empty() {
1430 let total = result.impacted_symbols.len();
1431 let mut visible = Vec::new();
1432 let mut low_signal_count = 0;
1433 for s in &result.impacted_symbols {
1434 if matches!(s.kind.as_str(), "import" | "module" | "namespace") {
1435 low_signal_count += 1;
1436 } else {
1437 visible.push(s);
1438 }
1439 }
1440
1441 out.push_str(&format!("### Downstream Impact ({} returned)\n", total));
1442
1443 if visible.is_empty() && low_signal_count > 0 {
1444 let row_word = if low_signal_count == 1 {
1445 "row (import/module)"
1446 } else {
1447 "rows (imports/modules)"
1448 };
1449 out.push_str(&format!(
1450 "All impacted symbols are imports/modules; {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
1451 ));
1452 } else {
1453 let mut syms_by_file: std::collections::BTreeMap<&str, Vec<&ImpactedSymbol>> =
1454 std::collections::BTreeMap::new();
1455 let mut file_order = Vec::new();
1456 for s in &visible {
1457 if !syms_by_file.contains_key(s.path.as_str()) {
1458 file_order.push(s.path.as_str());
1459 }
1460 syms_by_file.entry(s.path.as_str()).or_default().push(s);
1461 }
1462
1463 for path in file_order {
1464 out.push_str(&format!("{path}:\n"));
1465 if let Some(syms) = syms_by_file.get(path) {
1466 for s in syms {
1467 out.push_str(&format!(
1468 " - [depth {}] {} `{}` [line {}]\n",
1469 s.depth, s.kind, s.name, s.line
1470 ));
1471 }
1472 }
1473 }
1474
1475 if low_signal_count > 0 {
1476 let row_word = if low_signal_count == 1 {
1477 "row (import/module)"
1478 } else {
1479 "rows (imports/modules)"
1480 };
1481 out.push_str(&format!(
1482 "... {low_signal_count} low-signal {row_word} hidden; available in CLI --json.\n"
1483 ));
1484 }
1485 }
1486 } else if result.impacted_symbols_truncated || result.traversal_ceiling_reached {
1487 out.push_str("### Downstream Impact (0 returned)\n");
1488 } else {
1489 out.push_str(
1490 "### Downstream Impact (0 returned)\nNo downstream callers found within depth.\n",
1491 );
1492 }
1493
1494 out
1495}
1496
1497#[cfg(test)]
1498mod tests {
1499 use super::*;
1500 use crate::models::{ImpactedSymbol, TestTarget};
1501
1502 fn structural_fact(key: Option<&str>) -> crate::models::StructuralFact {
1503 crate::models::StructuralFact {
1504 structural_fact_id: "sf1".into(),
1505 path: ".codex/config.toml".into(),
1506 language: "toml".into(),
1507 pattern_id: "toml.key_value.v1".into(),
1508 capture_name: "key_value".into(),
1509 node_kind: "table".into(),
1510 key: key.map(str::to_string),
1511 metadata: None,
1512 containing_symbol_name: None,
1513 start_line: 2,
1514 end_line: 2,
1515 confidence: 1.0,
1516 }
1517 }
1518
1519 #[test]
1520 fn format_structural_facts_prints_key_and_falls_back_to_capture_name() {
1521 let with_key = format_structural_facts(
1522 &[structural_fact(Some("mcp_servers.code-kb.command"))],
1523 &[],
1524 "config",
1525 30,
1526 );
1527 assert!(with_key.contains(
1528 "- mcp_servers.code-kb.command [.codex/config.toml:2] (pattern: toml.key_value.v1)"
1529 ));
1530
1531 let without_key = format_structural_facts(&[structural_fact(None)], &[], "config", 30);
1532 assert!(
1533 without_key.contains("- key_value [.codex/config.toml:2] (pattern: toml.key_value.v1)")
1534 );
1535 }
1536
1537 #[test]
1538 fn format_structural_facts_renders_selected_qt_property_metadata() {
1539 let mut fact = structural_fact(Some("index"));
1540 fact.pattern_id = "cpp.qt_property.v1".into();
1541 fact.metadata = Some(serde_json::json!({
1542 "property_type": "int",
1543 "designable": false,
1544 "scriptable": true,
1545 "stored": false,
1546 "user": true,
1547 "revision": 2,
1548 }));
1549
1550 let output = format_structural_facts(&[fact], &[], "property", 30);
1551
1552 assert!(output.contains(
1553 "property_type: int, designable: false, scriptable: true, stored: false, user: true, revision: 2"
1554 ));
1555 }
1556
1557 #[test]
1558 fn format_structural_facts_names_the_endpoint_and_view_of_a_flask_route() {
1559 let route = |metadata| crate::models::StructuralFact {
1560 pattern_id: "flask.route.v1".into(),
1561 metadata: Some(metadata),
1562 ..structural_fact(Some("GET /"))
1563 };
1564 let alias = route(serde_json::json!({"api_style": "call_routing", "endpoint": "index"}));
1565 let rule = route(serde_json::json!({"api_style": "call_routing", "view_target": "ping"}));
1566 let decorated = route(serde_json::json!({"api_style": "decorator_routing"}));
1567
1568 let output = format_structural_facts(&[alias, rule, decorated], &[], "route", 30);
1569
1570 assert!(
1571 output.contains("(pattern: flask.route.v1, endpoint: index, no view function)"),
1572 "{output}"
1573 );
1574 assert!(
1575 output.contains("(pattern: flask.route.v1, view: ping)"),
1576 "{output}"
1577 );
1578 assert!(output.contains("(pattern: flask.route.v1)"), "{output}");
1579 }
1580
1581 #[test]
1582 fn doc_summary_ends_at_the_first_sentence_of_the_first_paragraph() {
1583 assert_eq!(
1584 doc_summary(
1585 "The actual WSGI application. This is not implemented in\n:meth:`__call__`."
1586 )
1587 .as_deref(),
1588 Some("The actual WSGI application.")
1589 );
1590 assert_eq!(
1591 doc_summary("\nCreate a runner\nfor tests\n\nMore.").as_deref(),
1592 Some("Create a runner for tests")
1593 );
1594 assert_eq!(
1595 doc_summary("Find facts by category (e.g. route, query). More.").as_deref(),
1596 Some("Find facts by category (e.g. route, query).")
1597 );
1598 assert_eq!(
1599 doc_summary("Use a name, e.g. foo. Then more.").as_deref(),
1600 Some("Use a name, e.g. foo.")
1601 );
1602 assert_eq!(
1603 doc_summary("/// <summary>\n/// Goes to previous page.\n/// </summary>").as_deref(),
1604 Some("Goes to previous page.")
1605 );
1606 assert_eq!(
1607 doc_summary("/**\n * Render the view.\n *\n * @param x\n */").as_deref(),
1608 Some("Render the view.")
1609 );
1610 assert_eq!(
1611 doc_summary("# Given a +hash+ returns the settings\n# for the environment.").as_deref(),
1612 Some("Given a +hash+ returns the settings for the environment.")
1613 );
1614 assert_eq!(
1615 doc_summary("#' A person record.").as_deref(),
1616 Some("A person record.")
1617 );
1618 assert_eq!(doc_summary(" \n"), None);
1619 assert!(doc_summary(&"word ".repeat(60)).unwrap().ends_with('…'));
1620 }
1621
1622 #[test]
1623 fn format_references_reports_the_occurrence_count_of_a_grouped_row() {
1624 let site = |occurrences| ReferenceSite {
1625 from_symbol_name: "Button".into(),
1626 from_symbol_id: "s1".into(),
1627 to_symbol_name: "background".into(),
1628 kind: "member_access".into(),
1629 path: "Ui/Button.qml".into(),
1630 start_line: Some(5),
1631 start_column: Some(4),
1632 occurrences,
1633 target: None,
1634 };
1635
1636 let grouped = format_references("Color", &[site(Some(6))], "callers", 30);
1637 assert!(
1638 grouped.contains("- `Button` [Ui/Button.qml:5] (kind: member_access, 6 in file)"),
1639 "{grouped}"
1640 );
1641
1642 let single = format_references("Color", &[site(None)], "callers", 30);
1643 assert!(
1644 single.contains("- `Button` [Ui/Button.qml:5] (kind: member_access)"),
1645 "{single}"
1646 );
1647 }
1648
1649 #[test]
1650 fn a_match_snippet_joins_its_lines_and_is_dropped_when_it_repeats_the_signature() {
1651 assert_eq!(
1652 match_line("...path up to\n the [root] (the [root] excluded)", "fn f()"),
1653 Some("...path up to the [root] (the [root] excluded)".into())
1654 );
1655 assert_eq!(
1656 match_line("// [HelpFunc] returns the\n// [function] set", "fn f()"),
1657 Some("// [HelpFunc] returns the [function] set".into())
1658 );
1659 assert_eq!(
1660 match_line(
1661 "fn [index]_facts(workspace_[root]: &Path) -> Option<[IndexFacts]>",
1662 "fn index_facts(workspace_root: &Path) -> Option<IndexFacts>"
1663 ),
1664 None
1665 );
1666 assert_eq!(
1667 match_line(
1668 "...[root]: &[PathBuf]) -> bool",
1669 "fn f(root: &[PathBuf]) -> bool"
1670 ),
1671 None
1672 );
1673 }
1674
1675 #[test]
1676 fn a_long_unresolved_call_chain_shows_only_its_last_call() {
1677 assert_eq!(
1678 callee_name(
1679 "[\"a\", \"b\"]\n .into_iter()\n .find_map(|key| args.get(key)).ok_or_else"
1680 ),
1681 "….ok_or_else"
1682 );
1683 assert_eq!(
1684 callee_name("workspace.resolve_path"),
1685 "workspace.resolve_path"
1686 );
1687 let selector = "html.dash .header, html.dash .breadcrumbs, html.dash .navigation";
1688 assert_eq!(callee_name(selector), selector);
1689 }
1690
1691 #[test]
1692 fn file_skeleton_reports_parse_errors() {
1693 let two = format_file_skeleton("src/lib.rs", &[], Some(35), 2);
1694 assert!(two.contains("// 2 parse errors: symbols may be incomplete"));
1695
1696 let one = format_file_skeleton("src/lib.rs", &[], Some(35), 1);
1697 assert!(one.contains("// 1 parse error: symbols may be incomplete"));
1698
1699 let none = format_file_skeleton("src/lib.rs", &[], Some(35), 0);
1700 assert!(!none.contains("parse error"));
1701 }
1702
1703 #[test]
1704 fn test_format_file_skeleton() {
1705 let syms = vec![Symbol {
1706 symbol_id: "s1".into(),
1707 file_id: "f1".into(),
1708 path: "src/lib.rs".into(),
1709 language: "rust".into(),
1710 name: "do_work".into(),
1711 kind: "function".into(),
1712 signature: Some("pub fn do_work() -> Result<()>".into()),
1713 doc_comment: Some("Performs core work.".into()),
1714 visibility: Some("pub".into()),
1715 parent_symbol_id: None,
1716 start_line: 10,
1717 start_column: 0,
1718 end_line: 30,
1719 end_column: 1,
1720 start_byte: 100,
1721 end_byte: 300,
1722 body_start_line: Some(11),
1723 body_start_column: Some(0),
1724 body_end_line: Some(29),
1725 body_end_column: Some(1),
1726 body_start_byte: Some(130),
1727 body_end_byte: Some(298),
1728 body_hash: None,
1729 semantic_group: None,
1730 is_test: false,
1731 test_container: false,
1732 }];
1733
1734 let skeleton = format_file_skeleton("src/lib.rs", &syms, Some(35), 0);
1735 assert!(skeleton.contains("/// Performs core work."));
1736
1737 let mut commented = syms.clone();
1738 commented[0].doc_comment = Some("/**\n * Performs core work.\n */".into());
1739 let skeleton = format_file_skeleton("src/lib.rs", &commented, Some(35), 0);
1740 assert!(skeleton.contains("/// Performs core work.\n"), "{skeleton}");
1741 assert!(!skeleton.contains("/// /**"), "{skeleton}");
1742 assert!(skeleton.contains("19 lines hidden: L11-L29"));
1743 }
1744
1745 #[test]
1746 fn format_symbol_body_prints_the_source_under_its_location() {
1747 let mut symbol = sample_symbol("plain");
1748 symbol.signature = Some("pub fn plain()".into());
1749
1750 assert_eq!(
1751 format_symbol_body(&symbol, "pub fn plain() {\n 1\n}"),
1752 "// src/lib.rs:1-10 (plain)\npub fn plain() {\n 1\n}\n"
1753 );
1754 }
1755
1756 #[test]
1757 fn test_format_search_results() {
1758 let results = vec![SymbolSearchResult {
1759 symbol: Symbol {
1760 symbol_id: "s1".into(),
1761 file_id: "f1".into(),
1762 path: "src/parser.rs".into(),
1763 language: "rust".into(),
1764 name: "parse_tokens".into(),
1765 kind: "function".into(),
1766 signature: Some("pub fn parse_tokens()".into()),
1767 doc_comment: Some("Parses tokens from stream.".into()),
1768 visibility: Some("pub".into()),
1769 parent_symbol_id: None,
1770 start_line: 15,
1771 start_column: 0,
1772 end_line: 25,
1773 end_column: 1,
1774 start_byte: 100,
1775 end_byte: 250,
1776 body_start_line: None,
1777 body_start_column: None,
1778 body_end_line: None,
1779 body_end_column: None,
1780 body_start_byte: None,
1781 body_end_byte: None,
1782 body_hash: None,
1783 semantic_group: None,
1784 is_test: false,
1785 test_container: false,
1786 },
1787 score: -1.85,
1788 snippet: Some("Parses [tokens] from stream.".into()),
1789 explain: None,
1790 }];
1791
1792 let formatted = format_search_results("tokens", &results, 20);
1793 assert!(formatted.contains("Found 1 symbols matching concept \"tokens\":\n\n- "));
1794 assert!(
1795 formatted.contains("- function `parse_tokens` [src/parser.rs:15-25] (score: -1.85)")
1796 );
1797 assert!(formatted.contains("Match: Parses [tokens] from stream."));
1798 assert!(!formatted.contains("explain"));
1799 assert!(!formatted.contains("rerank"));
1800 }
1801
1802 #[test]
1803 fn exact_lookup_folds_import_rows_into_one_line_when_a_definition_exists() {
1804 let class = Symbol {
1805 kind: "class".into(),
1806 path: "src/flask/app.py".into(),
1807 ..sample_symbol("Flask")
1808 };
1809 let import = |path: &str, line: usize| Symbol {
1810 kind: "import".into(),
1811 path: path.into(),
1812 start_line: line,
1813 symbol_id: format!("id_{path}"),
1814 ..sample_symbol("Flask")
1815 };
1816 let rows = vec![
1817 class,
1818 import("src/flask/cli.py", 34),
1819 import("src/flask/ctx.py", 21),
1820 import("tests/conftest.py", 6),
1821 import("examples/app.py", 1),
1822 ];
1823
1824 let folded = format_find_symbol_results("Flask", &rows, &[], 20);
1825
1826 assert!(
1827 folded.contains("- class `Flask` [src/flask/app.py:"),
1828 "{folded}"
1829 );
1830 assert!(
1831 folded.contains(
1832 "- 4 imports of `Flask`: src/flask/cli.py:34, src/flask/ctx.py:21, tests/conftest.py:6, … (lookup_symbol with kind=\"import\" lists them)"
1833 ),
1834 "{folded}"
1835 );
1836 assert!(!folded.contains("- import `Flask`"), "{folded}");
1837
1838 let capped = format_find_symbol_results("Flask", &rows, &[], 1);
1839 assert!(
1840 capped.contains("- at least 4 imports of `Flask`"),
1841 "{capped}"
1842 );
1843
1844 let mut with_prefix_rows = rows.clone();
1845 with_prefix_rows.push(Symbol {
1846 kind: "class".into(),
1847 ..sample_symbol("FlaskGroup")
1848 });
1849 let cut_after_exact = format_find_symbol_results("Flask", &with_prefix_rows, &[], 6);
1850 assert!(
1851 cut_after_exact.contains("- 4 imports of `Flask`"),
1852 "{cut_after_exact}"
1853 );
1854
1855 let imports_only = format_find_symbol_results("Flask", &rows[1..], &[], 20);
1856 assert_eq!(imports_only.matches("- import `Flask`").count(), 4);
1857 }
1858
1859 #[test]
1860 fn skeleton_shows_python_class_and_module_variables_with_one_line_values() {
1861 let leaf = |name: &str, kind: &str, line: usize, sig: &str| Symbol {
1862 kind: kind.into(),
1863 language: "python".into(),
1864 path: "app.py".into(),
1865 parent_symbol_id: Some("id_App".into()),
1866 start_line: line,
1867 end_line: line,
1868 body_start_line: None,
1869 body_end_line: None,
1870 signature: Some(sig.into()),
1871 ..sample_symbol(name)
1872 };
1873 let class = Symbol {
1874 kind: "class".into(),
1875 language: "python".into(),
1876 path: "app.py".into(),
1877 start_line: 1,
1878 end_line: 20,
1879 body_start_line: None,
1880 body_end_line: None,
1881 signature: Some("class App".into()),
1882 ..sample_symbol("App")
1883 };
1884 let module_variable = Symbol {
1885 kind: "variable".into(),
1886 language: "python".into(),
1887 path: "app.py".into(),
1888 start_line: 30,
1889 end_line: 30,
1890 body_start_line: None,
1891 body_end_line: None,
1892 signature: Some("app = App()".into()),
1893 ..sample_symbol("app")
1894 };
1895 let symbols = vec![
1896 class,
1897 leaf(
1898 "request_class",
1899 "variable",
1900 2,
1901 "request_class: type[Request] = Request",
1902 ),
1903 leaf(
1904 "default_config",
1905 "variable",
1906 3,
1907 "default_config = ImmutableDict(\n {\n \"DEBUG\": None,\n }\n)",
1908 ),
1909 leaf(
1910 "blueprints",
1911 "property",
1912 5,
1913 "self.blueprints: dict[str, Blueprint] = {}",
1914 ),
1915 leaf(
1916 "error_handler_spec",
1917 "property",
1918 7,
1919 "self.error_handler_spec: dict[\n ft.AppOrBlueprintKey,\n dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]],\n] = defaultdict(lambda: defaultdict(dict), default_factory_argument_that_is_long) # type: ignore",
1920 ),
1921 module_variable,
1922 ];
1923
1924 let out = format_file_skeleton("app.py", &symbols, None, 0);
1925
1926 assert!(
1927 out.contains(" request_class: type[Request] = Request; // L2-2"),
1928 "{out}"
1929 );
1930 assert!(
1931 out.contains(" default_config = ImmutableDict({\"DEBUG\": None}); // L3-3"),
1932 "{out}"
1933 );
1934 assert!(
1935 out.contains(" self.error_handler_spec: dict[ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]]] = defaultdict(lambda: defaultdict(dict)…; // L7-7"),
1936 "{out}"
1937 );
1938 assert!(
1939 out.contains(" self.blueprints: dict[str, Blueprint] = {}; // L5-5"),
1940 "{out}"
1941 );
1942 assert!(out.contains("app = App(); // L30-30"), "{out}");
1943 }
1944
1945 #[test]
1946 fn skeleton_names_the_method_that_assigns_an_attribute() {
1947 let member = |name: &str, kind: &str, start: usize, end: usize, sig: &str| Symbol {
1948 kind: kind.into(),
1949 language: "python".into(),
1950 parent_symbol_id: Some("id_Flask".into()),
1951 start_line: start,
1952 end_line: end,
1953 body_start_line: None,
1954 body_end_line: None,
1955 signature: Some(sig.into()),
1956 ..sample_symbol(name)
1957 };
1958 let class = Symbol {
1959 kind: "class".into(),
1960 language: "python".into(),
1961 start_line: 1,
1962 end_line: 30,
1963 body_start_line: None,
1964 body_end_line: None,
1965 signature: Some("class Flask(App)".into()),
1966 ..sample_symbol("Flask")
1967 };
1968 let symbols = vec![
1969 class,
1970 member("__init__", "method", 2, 10, "def __init__(self)"),
1971 member("cli", "property", 3, 3, "self.cli = cli.AppGroup()"),
1972 member("run", "method", 12, 20, "def run(self)"),
1973 member("debug", "property", 14, 14, "self.debug = get_debug_flag()"),
1974 ];
1975
1976 let out = format_file_skeleton("app.py", &symbols, None, 0);
1977
1978 assert!(
1979 out.contains("self.cli = cli.AppGroup(); // in __init__(), L3-3"),
1980 "{out}"
1981 );
1982 assert!(
1983 out.contains("self.debug = get_debug_flag(); // in run(), L14-14"),
1984 "{out}"
1985 );
1986 }
1987
1988 #[test]
1989 fn skeleton_hides_variables_that_are_not_python_class_attributes() {
1990 let parent = |name: &str, kind: &str, language: &str| Symbol {
1991 kind: kind.into(),
1992 language: language.into(),
1993 start_line: 1,
1994 end_line: 20,
1995 body_start_line: None,
1996 body_end_line: None,
1997 signature: Some(format!("{kind} {name}")),
1998 ..sample_symbol(name)
1999 };
2000 let child = |name: &str, parent: &str, language: &str, sig: &str| Symbol {
2001 kind: "variable".into(),
2002 language: language.into(),
2003 parent_symbol_id: Some(format!("id_{parent}")),
2004 start_line: 2,
2005 end_line: 2,
2006 body_start_line: None,
2007 body_end_line: None,
2008 signature: Some(sig.into()),
2009 ..sample_symbol(name)
2010 };
2011 let symbols = vec![
2012 parent("Adapters", "class", "java"),
2013 child(
2014 "accessible",
2015 "Adapters",
2016 "java",
2017 "boolean accessible = false",
2018 ),
2019 parent("body", "class", "html"),
2020 child(
2021 "img",
2022 "body",
2023 "html",
2024 "<img class=\"carat\" src=\"carat.png\" alt>",
2025 ),
2026 parent("section", "module", "yaml"),
2027 child("title", "section", "yaml", "title: Invoking jq"),
2028 ];
2029
2030 let out = format_file_skeleton("mixed", &symbols, None, 0);
2031
2032 for hidden in ["accessible", "<img", "title:"] {
2033 assert!(!out.contains(hidden), "{out}");
2034 }
2035 }
2036
2037 #[test]
2038 fn a_multi_line_macro_row_drops_its_line_continuations_and_is_cut_to_one_line() {
2039 let short = "#define PAIR(a, b) \\\n a, \\\n b";
2040 assert_eq!(value_row_signature(short), "#define PAIR(a, b) a, b");
2041
2042 let long = format!(
2043 "#define WIDE(x) \\\n{}",
2044 " x + x + x + x + x + x + x + x \\\n".repeat(8)
2045 );
2046 let row = value_row_signature(&long);
2047 assert!(row.starts_with("#define WIDE(x) x + x"), "{row}");
2048 assert!(row.ends_with('…'), "{row}");
2049 assert!(!row.contains('\\'), "{row}");
2050 assert!(row.chars().count() <= 120, "{row}");
2051 }
2052
2053 #[test]
2054 fn skeleton_keeps_values_only_for_real_assignments() {
2055 let row =
2056 |name: &str, kind: &str, line: usize, sig: &str, body: Option<(usize, usize)>| Symbol {
2057 kind: kind.into(),
2058 start_line: line,
2059 end_line: body.map_or(line, |(_, end)| end),
2060 body_start_line: body.map(|(start, _)| start),
2061 body_end_line: body.map(|(_, end)| end),
2062 signature: Some(sig.into()),
2063 ..sample_symbol(name)
2064 };
2065 let symbols = vec![
2066 row(
2067 "img",
2068 "property",
2069 1,
2070 "[class^=rz-] img,[class^=rz-] svg { vertical-align:middle }",
2071 None,
2072 ),
2073 row(
2074 "Coordinates",
2075 "property",
2076 2,
2077 "[JsonProperty(ItemConverterType = typeof(IntToFloatConverter))] public int[,,] Coordinates { get; set; }",
2078 None,
2079 ),
2080 row(
2081 "VERSION_CHECK",
2082 "constant",
2083 3,
2084 "#define VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))\n",
2085 None,
2086 ),
2087 row(
2088 "TABLE",
2089 "constant",
2090 4,
2091 "TABLE = {\n '\"' => '%22',\n '\\r' => '%0D',\n}.freeze",
2092 Some((4, 8)),
2093 ),
2094 row(
2095 "LIMIT",
2096 "field",
2097 10,
2098 "private static final int LIMIT = 5;",
2099 None,
2100 ),
2101 ];
2102
2103 let out = format_file_skeleton("mixed", &symbols, None, 0);
2104
2105 assert!(
2106 out.contains("[class^=rz-] img,[class^=rz-] svg; // L1-1"),
2107 "{out}"
2108 );
2109 assert!(out.contains("public int[,,] Coordinates; // L2-2"), "{out}");
2110 assert!(
2111 out.contains(
2112 "#define VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))); // L3-3\n"
2113 ),
2114 "{out}"
2115 );
2116 assert!(
2117 out.contains("TABLE = { /* 5 lines hidden: L4-L8 */ }"),
2118 "{out}"
2119 );
2120 assert!(
2121 out.contains("private static final int LIMIT = 5; // L10-10"),
2122 "{out}"
2123 );
2124 }
2125
2126 #[test]
2127 fn skeleton_cuts_a_field_with_members_at_its_brace() {
2128 let field = Symbol {
2129 kind: "field".into(),
2130 language: "java".into(),
2131 start_line: 1,
2132 end_line: 9,
2133 body_start_line: None,
2134 body_end_line: None,
2135 signature: Some(
2136 "public static final TypeAdapter<Class> CLASS = new TypeAdapter<Class>() {\n @Override\n}"
2137 .into(),
2138 ),
2139 ..sample_symbol("CLASS")
2140 };
2141 let member = Symbol {
2142 kind: "method".into(),
2143 language: "java".into(),
2144 parent_symbol_id: Some("id_CLASS".into()),
2145 start_line: 2,
2146 end_line: 4,
2147 signature: Some("public void write(JsonWriter out, Class value)".into()),
2148 ..sample_symbol("write")
2149 };
2150
2151 let out = format_file_skeleton("TypeAdapters.java", &[field, member], None, 0);
2152
2153 assert!(
2154 out.contains(
2155 "public static final TypeAdapter<Class> CLASS = new TypeAdapter<Class>() {\n"
2156 ),
2157 "{out}"
2158 );
2159 assert!(!out.contains('…'), "{out}");
2160 }
2161
2162 #[test]
2163 fn import_summary_counts_sites_and_files_and_lists_three() {
2164 let sites = vec![
2165 ("src/flask/__init__.py".to_string(), 2),
2166 ("src/flask/cli.py".to_string(), 34),
2167 ("src/flask/cli.py".to_string(), 45),
2168 ("tests/conftest.py".to_string(), 6),
2169 ];
2170
2171 assert_eq!(
2172 format_import_summary(&sites),
2173 "Imported 4 times in 3 files: src/flask/__init__.py:2, src/flask/cli.py:34, src/flask/cli.py:45, … (lookup_symbol with kind=\"import\" lists them)\n"
2174 );
2175 assert_eq!(format_import_summary(&[]), "");
2176 }
2177
2178 #[test]
2179 fn no_facts_for_an_alias_points_imports_at_lookup_and_skips_the_raw_list() {
2180 let categories = vec![("flask.route.v1".to_string(), 3)];
2181
2182 let imports = format_no_facts("import", None, &categories);
2183 let unknown = format_no_facts("widgets", None, &categories);
2184
2185 assert!(
2186 imports.contains("lookup_symbol with kind=\"import\""),
2187 "{imports}"
2188 );
2189 assert!(!imports.contains("`flask.route.v1`"), "{imports}");
2190 assert!(unknown.contains("`flask.route.v1` (3 facts)"), "{unknown}");
2191 }
2192
2193 #[test]
2194 fn markup_and_data_rows_show_their_own_kind_words() {
2195 let row = |language: &str, kind: &str| Symbol {
2196 language: language.into(),
2197 kind: kind.into(),
2198 ..sample_symbol("x")
2199 };
2200 assert_eq!(display_kind(&row("html", "class")), "element");
2201 assert_eq!(display_kind(&row("sql", "class")), "table");
2202 assert_eq!(display_kind(&row("markdown", "module")), "section");
2203 assert_eq!(display_kind(&row("markdown", "import")), "link");
2204 let attribute = Symbol {
2205 kind: "property".into(),
2206 signature: Some("self.extensions = {}".into()),
2207 ..sample_symbol("extensions")
2208 };
2209 assert_eq!(display_kind(&attribute), "attribute");
2210 let fsharp_member = Symbol {
2211 language: "fsharp".into(),
2212 signature: Some("this.Total = decimal this.Qty * this.Price".into()),
2213 ..attribute
2214 };
2215 assert_eq!(display_kind(&fsharp_member), "property");
2216 assert_eq!(display_kind(&row("python", "class")), "class");
2217 }
2218
2219 #[test]
2220 fn no_facts_heading_names_the_path_filter() {
2221 assert_eq!(
2222 no_facts_heading("config", Some("src/flask")),
2223 "No facts match 'config' under `src/flask`."
2224 );
2225 assert_eq!(
2226 no_facts_heading("config", None),
2227 "No facts match 'config' in this repository."
2228 );
2229 }
2230
2231 #[test]
2232 fn outline_says_how_many_definitions_it_left_out_and_counts_tests() {
2233 let mut root = OutlineNode::default();
2234 let symbol = |name: &str, is_test: bool| Symbol {
2235 kind: "function".into(),
2236 path: "tests/test_basic.py".into(),
2237 is_test,
2238 ..sample_symbol(name)
2239 };
2240 let symbols = HashMap::from([(
2241 "tests/test_basic.py".to_string(),
2242 vec![symbol("helper", false), symbol("test_one", true)],
2243 )]);
2244 let counts = HashMap::from([(
2245 "tests/test_basic.py".to_string(),
2246 crate::queries::OutlineCounts {
2247 definitions: 3,
2248 tests: 90,
2249 fixtures: 2,
2250 },
2251 )]);
2252 add_path_to_outline(&mut root, "tests/test_basic.py", &symbols, &counts, 3, "");
2253
2254 let mut out = String::new();
2255 render_outline_tree(&mut out, &root, "", 0, 3);
2256
2257 assert!(
2258 out.contains("test_basic.py [function helper, +2 more, 90 tests, 2 fixtures]"),
2259 "{out}"
2260 );
2261 }
2262
2263 #[test]
2264 fn outline_counts_the_files_below_the_depth_limit() {
2265 let mut root = OutlineNode::default();
2266 let no_symbols = HashMap::new();
2267 for path in [
2268 "src/flask/app.py",
2269 "src/flask/json/tag.py",
2270 "src/flask/cli.py",
2271 "tests/conftest.py",
2272 ] {
2273 add_path_to_outline(&mut root, path, &no_symbols, &HashMap::new(), 2, "");
2274 }
2275
2276 let mut out = String::new();
2277 render_outline_tree(&mut out, &root, "", 0, 2);
2278
2279 assert!(out.contains("└── flask/ (3 indexed files)"), "{out}");
2280 assert!(!out.contains("tests/ ("), "{out}");
2281 }
2282
2283 #[test]
2284 fn a_lookup_qualified_with_double_colons_names_the_member_exactly() {
2285 let rows = vec![sample_symbol("Flask.handle_user_exception")];
2286
2287 let out = format_find_symbol_results("Flask::handle_user_exception", &rows, &[], 20);
2288
2289 assert!(!out.contains("named exactly"), "{out}");
2290 }
2291
2292 #[test]
2293 fn exact_lookup_folds_only_imports_named_exactly_like_the_query() {
2294 let rows = vec![
2295 Symbol {
2296 kind: "function".into(),
2297 ..sample_symbol("read")
2298 },
2299 Symbol {
2300 kind: "import".into(),
2301 path: "src/flask/cli.py".into(),
2302 start_line: 1034,
2303 ..sample_symbol("readline")
2304 },
2305 Symbol {
2306 kind: "import".into(),
2307 path: "src/Types.kt".into(),
2308 start_line: 18,
2309 ..sample_symbol("com.example.internal.read")
2310 },
2311 ];
2312
2313 let out = format_find_symbol_results("read", &rows, &[], 20);
2314
2315 assert!(
2316 out.contains(
2317 "- 1 other row starts with or contains `read`, ignoring case: `readline` (import) (lookup_symbol"
2318 ),
2319 "{out}"
2320 );
2321 assert!(
2322 out.contains(
2323 "- 1 import of `read`: src/Types.kt:18 (lookup_symbol with kind=\"import\" lists them)"
2324 ),
2325 "{out}"
2326 );
2327 }
2328
2329 #[test]
2330 fn discovery_formatters_append_ids_to_metadata_rows() {
2331 let exact = vec![sample_symbol("exact")];
2332 let fallback = vec![SymbolSearchResult {
2333 symbol: sample_symbol("fallback"),
2334 score: 1.0,
2335 snippet: None,
2336 explain: None,
2337 }];
2338
2339 let outputs = [
2340 (
2341 format_find_symbol_results("exact", &exact, &[], 20),
2342 "id_exact",
2343 ),
2344 (
2345 format_find_symbol_results("fallback query", &[], &fallback, 20),
2346 "id_fallback",
2347 ),
2348 (
2349 format_search_results("fallback", &fallback, 20),
2350 "id_fallback",
2351 ),
2352 ];
2353
2354 for (formatted, id) in outputs {
2355 assert!(
2356 formatted
2357 .lines()
2358 .any(|line| line.starts_with("- ") && line.contains(&format!("id={id}"))),
2359 "{formatted}"
2360 );
2361 assert!(!formatted.contains("\n id="), "{formatted}");
2362 }
2363 }
2364
2365 #[test]
2366 fn every_printed_part_of_the_explain_line_sums_to_the_score() {
2367 let e = SearchExplain {
2368 bm25: Some(-3.21),
2369 branches: vec!["word".into()],
2370 name_tier: "all".into(),
2371 name_strength: 6,
2372 term_score: 24.5,
2373 name_bonus: 60.0,
2374 kind_prior: 4.0,
2375 path_role: -10.0,
2376 documentation: -200.0,
2377 test_intent: 5.0,
2378 nested: 0.0,
2379 terms: vec![("sha".into(), "name".into(), 3.0)],
2380 word_weights: vec![("sha".into(), 2.6)],
2381 candidates: 1,
2382 rerank_us: 1,
2383 };
2384 let score = e.term_score
2385 + e.name_bonus
2386 + e.kind_prior
2387 + e.path_role
2388 + e.documentation
2389 + e.test_intent;
2390
2391 let line = explain_line(score, &e);
2392 let parts: f64 = line
2393 .split(" = ")
2394 .nth(1)
2395 .unwrap()
2396 .split(" [")
2397 .next()
2398 .unwrap()
2399 .split(" + ")
2400 .map(|part| part.rsplit(' ').next().unwrap().parse::<f64>().unwrap())
2401 .sum();
2402
2403 assert!(line.starts_with(&format!(
2404 "score {score:.1} = terms 24.5 + name all(6) 60.0 "
2405 )));
2406 assert_eq!(format!("{parts:.1}"), format!("{score:.1}"));
2407 }
2408
2409 #[test]
2410 fn test_format_search_results_prints_the_explain_breakdown_when_present() {
2411 let mut result = SymbolSearchResult {
2412 symbol: sample_symbol("parseSha256Sidecar"),
2413 score: 71.6,
2414 snippet: Some("parse[Sha256]Sidecar".into()),
2415 explain: Some(SearchExplain {
2416 bm25: Some(-3.21),
2417 branches: vec!["word".into(), "name".into()],
2418 name_tier: "all".into(),
2419 name_strength: 6,
2420 terms: vec![
2421 ("sha".into(), "name".into(), 3.0),
2422 ("256".into(), "name".into(), 3.0),
2423 ],
2424 term_score: 12.6,
2425 name_bonus: 60.0,
2426 kind_prior: 4.0,
2427 path_role: -10.0,
2428 documentation: 0.0,
2429 test_intent: 5.0,
2430 nested: 0.0,
2431 word_weights: vec![("sha".into(), 2.6), ("256".into(), 0.97)],
2432 candidates: 37,
2433 rerank_us: 180,
2434 }),
2435 };
2436
2437 let formatted = format_search_results("sha256", std::slice::from_ref(&result), 20);
2438 assert!(formatted.contains(
2439 "Found 1 symbols matching concept \"sha256\":\nrerank: 37 candidates in 180 µs; words sha 2.60, 256 0.97\n\n- "
2440 ));
2441 assert!(formatted.contains(
2442 " explain: score 71.6 = terms 12.6 + name all(6) 60.0 + kind 4.0 + path -10.0 + test 5.0 [word,name] bm25 -3.21 terms sha=name:3 256=name:3\n"
2443 ));
2444
2445 result.explain = None;
2446 let silent = format_search_results("sha256", std::slice::from_ref(&result), 20);
2447 assert!(!silent.contains("explain"));
2448 assert!(!silent.contains("rerank"));
2449 }
2450
2451 #[test]
2452 fn test_format_search_results_discloses_a_reached_limit() {
2453 let results = vec![SymbolSearchResult {
2454 symbol: sample_symbol("parse_tokens"),
2455 score: 0.0,
2456 snippet: None,
2457 explain: None,
2458 }];
2459
2460 let formatted = format_search_results("tokens", &results, 1);
2461 assert!(
2462 formatted.contains("[Showing 1 results (limit reached); increase limit to see more.]")
2463 );
2464
2465 let at_ceiling =
2466 format_search_results("tokens", &results, crate::queries::MAX_RESULT_LIMIT);
2467 assert!(!at_ceiling.contains("limit reached"));
2468
2469 let full: Vec<SymbolSearchResult> = (0..crate::queries::MAX_RESULT_LIMIT)
2470 .map(|_| SymbolSearchResult {
2471 symbol: sample_symbol("parse_tokens"),
2472 score: 0.0,
2473 snippet: None,
2474 explain: None,
2475 })
2476 .collect();
2477 let capped = format_search_results("tokens", &full, crate::queries::MAX_RESULT_LIMIT);
2478 assert!(capped.contains("(limit reached); narrow the query to see more.]"));
2479 }
2480
2481 #[test]
2482 fn test_format_blast_radius() {
2483 let res = BlastRadiusResult {
2484 seed_type: "symbol".into(),
2485 seeds: vec!["do_work".into()],
2486 likely_tests: vec![TestTarget {
2487 name: "test_do_work".into(),
2488 path: "tests/work_test.rs".into(),
2489 line: 15,
2490 reason: "direct caller".into(),
2491 }],
2492 impacted_symbols: vec![ImpactedSymbol {
2493 name: "caller_fn".into(),
2494 kind: "function".into(),
2495 path: "src/caller.rs".into(),
2496 line: 42,
2497 depth: 1,
2498 }],
2499 traversal_ceiling_reached: false,
2500 likely_tests_truncated: false,
2501 impacted_symbols_truncated: false,
2502 test_file_ceiling_reached: false,
2503 limit_at_maximum: false,
2504 likely_tests_found: 0,
2505 impacted_symbols_found: 0,
2506 };
2507
2508 let formatted = format_blast_radius(&res);
2509 assert!(formatted.contains("## Blast Radius & Test Impact (Symbol: do_work)"));
2510 assert!(formatted.contains("### Likely Tests to Run (1 returned)"));
2511 assert!(
2512 formatted.contains("tests/work_test.rs:\n - `test_do_work` [line 15] (direct caller)")
2513 );
2514 assert!(formatted.contains("src/caller.rs:\n - [depth 1] function `caller_fn` [line 42]"));
2515 }
2516
2517 #[test]
2518 fn format_blast_radius_groups_every_returned_test_by_file() {
2519 let mut likely_tests = Vec::new();
2520 for i in 1..=25 {
2521 likely_tests.push(TestTarget {
2522 name: format!("test_{i}"),
2523 path: format!("tests/test_{}.rs", (i % 3) + 1),
2524 line: i * 10,
2525 reason: "direct caller".into(),
2526 });
2527 }
2528
2529 let impacted_symbols = vec![
2530 ImpactedSymbol {
2531 name: "use_foo".into(),
2532 kind: "import".into(),
2533 path: "src/service.rs".into(),
2534 line: 1,
2535 depth: 1,
2536 },
2537 ImpactedSymbol {
2538 name: "service_fn".into(),
2539 kind: "function".into(),
2540 path: "src/service.rs".into(),
2541 line: 20,
2542 depth: 1,
2543 },
2544 ImpactedSymbol {
2545 name: "api_handler".into(),
2546 kind: "function".into(),
2547 path: "src/api.rs".into(),
2548 line: 45,
2549 depth: 2,
2550 },
2551 ];
2552
2553 let res = BlastRadiusResult {
2554 seed_type: "file".into(),
2555 seeds: vec!["src/lib.rs".into()],
2556 likely_tests,
2557 impacted_symbols,
2558 traversal_ceiling_reached: false,
2559 likely_tests_truncated: false,
2560 impacted_symbols_truncated: false,
2561 test_file_ceiling_reached: false,
2562 limit_at_maximum: false,
2563 likely_tests_found: 0,
2564 impacted_symbols_found: 0,
2565 };
2566
2567 let formatted = format_blast_radius(&res);
2568
2569 assert!(formatted.contains("### Likely Tests to Run (25 returned)"));
2570 assert!(
2571 formatted.contains(" - `test_25` [line 250]"),
2572 "{formatted}"
2573 );
2574 assert!(!formatted.contains("hidden by the compact"));
2575
2576 assert!(formatted.contains("tests/test_1.rs:\n"));
2577 assert!(formatted.contains(" - `test_"));
2578
2579 assert!(!formatted.contains("use_foo"));
2580 assert!(
2581 formatted
2582 .contains("... 1 low-signal row (import/module) hidden; available in CLI --json.")
2583 );
2584 assert!(formatted.contains("src/service.rs:\n"));
2585 assert!(formatted.contains(" - [depth 1] function `service_fn` [line 20]"));
2586 }
2587
2588 fn sample_symbol(name: &str) -> Symbol {
2589 Symbol {
2590 symbol_id: format!("id_{name}"),
2591 file_id: "f1".into(),
2592 path: "src/lib.rs".into(),
2593 language: "rust".into(),
2594 name: name.into(),
2595 kind: "function".into(),
2596 signature: Some(format!("pub fn {name}()")),
2597 doc_comment: None,
2598 visibility: Some("pub".into()),
2599 parent_symbol_id: None,
2600 start_line: 1,
2601 start_column: 0,
2602 end_line: 10,
2603 end_column: 1,
2604 start_byte: 0,
2605 end_byte: 100,
2606 body_start_line: Some(2),
2607 body_start_column: Some(0),
2608 body_end_line: Some(9),
2609 body_end_column: Some(1),
2610 body_start_byte: Some(10),
2611 body_end_byte: Some(99),
2612 body_hash: None,
2613 semantic_group: None,
2614 is_test: false,
2615 test_container: false,
2616 }
2617 }
2618
2619 fn sample_context_slice() -> ContextSlice {
2620 ContextSlice {
2621 target_symbol: sample_symbol("target_fn"),
2622 target_body: " println!(\"hello\");\n".into(),
2623 callee_signatures: Vec::new(),
2624 related_types: Vec::new(),
2625 related_tests: Vec::new(),
2626 }
2627 }
2628
2629 #[test]
2630 fn format_context_slice_does_not_repeat_expression_already_in_signature() {
2631 let body = "=>\n transport.SendAsync<Response>(\n HttpMethod.Get,\n $\"items/{id}\",\n cancellationToken: cancellationToken)";
2632 let mut slice = sample_context_slice();
2633 slice.target_symbol.language = "csharp".into();
2634 slice.target_symbol.signature = Some(format!(
2635 "public static Task<Response?> GetByIdAsync(\n int id,\n CancellationToken cancellationToken = default){body}"
2636 ));
2637 slice.target_body = body.into();
2638
2639 let formatted = format_context_slice(&slice);
2640
2641 assert_eq!(
2642 formatted.matches("transport.SendAsync").count(),
2643 1,
2644 "{formatted}"
2645 );
2646 }
2647
2648 #[test]
2649 fn context_slice_leaves_out_a_signature_that_the_body_already_holds() {
2650 let mut slice = sample_context_slice();
2651 slice.target_symbol.signature = Some("type Person = { Name: string; Age: int }".into());
2652 slice.target_body = "type Person = { Name: string; Age: int }\n".into();
2653
2654 let text = format_context_slice(&slice);
2655
2656 assert!(!text.contains("Signature:"), "{text}");
2657 assert_eq!(text.matches("type Person").count(), 1, "{text}");
2658 }
2659
2660 #[test]
2661 fn context_slice_says_when_no_test_was_found() {
2662 let text = format_context_slice(&sample_context_slice());
2663
2664 assert!(
2665 text.ends_with("### Related Tests:\nNo test calls, uses, or names this symbol; blast_radius lists tests that can reach it through callers.\n"),
2666 "{text}"
2667 );
2668 }
2669
2670 #[test]
2671 fn test_context_slice_shows_truncation_notice_when_caps_hit() {
2672 let mut slice = sample_context_slice();
2673 slice.callee_signatures = (1..=10).map(|i| format!("fn callee_{i}()")).collect();
2674 let text = format_context_slice(&slice);
2675 assert!(text.contains("[Showing 10 dependencies (limit reached)]"));
2676
2677 let mut slice_tests = sample_context_slice();
2678 slice_tests.related_tests = (1..=5)
2679 .map(|i| {
2680 let mut sym = sample_symbol(&format!("test_fn_{i}"));
2681 sym.path = format!("tests/test_{i}.rs");
2682 sym.is_test = true;
2683 sym
2684 })
2685 .collect();
2686 let text_tests = format_context_slice(&slice_tests);
2687 assert!(text_tests.contains("[Showing 5 tests (limit reached)]"));
2688 }
2689
2690 #[test]
2691 fn test_blast_radius_shows_traversal_ceiling_at_200_symbols() {
2692 let impacted_symbols = (1..=200)
2693 .map(|i| ImpactedSymbol {
2694 name: format!("sym_{i}"),
2695 kind: "function".into(),
2696 path: format!("src/mod_{}.rs", i % 10),
2697 line: i,
2698 depth: 1,
2699 })
2700 .collect();
2701
2702 let res = BlastRadiusResult {
2703 seed_type: "symbol".into(),
2704 seeds: vec!["root_fn".into()],
2705 likely_tests: Vec::new(),
2706 impacted_symbols,
2707 traversal_ceiling_reached: true,
2708 likely_tests_truncated: false,
2709 impacted_symbols_truncated: false,
2710 test_file_ceiling_reached: false,
2711 limit_at_maximum: false,
2712 likely_tests_found: 0,
2713 impacted_symbols_found: 0,
2714 };
2715
2716 let formatted = format_blast_radius(&res);
2717 assert!(formatted.contains("### Downstream Impact (200 returned)\n"));
2718 }
2719
2720 #[test]
2721 fn blast_radius_does_not_claim_no_results_after_discovery_ceiling() {
2722 let res = BlastRadiusResult {
2723 seed_type: "file".into(),
2724 seeds: vec!["src/widget.rs".into()],
2725 likely_tests: Vec::new(),
2726 impacted_symbols: Vec::new(),
2727 likely_tests_truncated: false,
2728 impacted_symbols_truncated: false,
2729 traversal_ceiling_reached: true,
2730 test_file_ceiling_reached: true,
2731 limit_at_maximum: false,
2732 likely_tests_found: 0,
2733 impacted_symbols_found: 0,
2734 };
2735
2736 let formatted = format_blast_radius(&res);
2737 assert!(formatted.contains("Likely Tests to Run (0 returned)"));
2738 assert!(formatted.contains("Downstream Impact (0 returned)"));
2739 assert!(formatted.contains("Name-matched test discovery hit its fixed ceiling"));
2740 assert!(!formatted.contains("No direct or name-matched tests found"));
2741 assert!(!formatted.contains("No downstream callers found within depth"));
2742
2743 let no_ceiling = BlastRadiusResult {
2744 traversal_ceiling_reached: false,
2745 test_file_ceiling_reached: false,
2746 limit_at_maximum: false,
2747 ..res.clone()
2748 };
2749 assert!(format_blast_radius(&no_ceiling).contains("No direct or name-matched tests found"));
2750
2751 let traversal_only = BlastRadiusResult {
2752 traversal_ceiling_reached: true,
2753 test_file_ceiling_reached: false,
2754 limit_at_maximum: false,
2755 ..res
2756 };
2757 let traversal_only_text = format_blast_radius(&traversal_only);
2758 assert!(!traversal_only_text.contains("No direct or name-matched tests found"));
2759 }
2760
2761 fn skeleton_row(
2762 id: &str,
2763 parent: Option<&str>,
2764 kind: &str,
2765 name: &str,
2766 signature: &str,
2767 lines: (usize, usize),
2768 body: Option<(usize, usize)>,
2769 ) -> Symbol {
2770 Symbol {
2771 symbol_id: id.into(),
2772 file_id: "f1".into(),
2773 path: "src/lib.rs".into(),
2774 language: "rust".into(),
2775 name: name.into(),
2776 kind: kind.into(),
2777 signature: Some(signature.into()),
2778 doc_comment: None,
2779 visibility: None,
2780 parent_symbol_id: parent.map(str::to_string),
2781 start_line: lines.0,
2782 start_column: 0,
2783 end_line: lines.1,
2784 end_column: 1,
2785 start_byte: 0,
2786 end_byte: 0,
2787 body_start_line: body.map(|b| b.0),
2788 body_start_column: None,
2789 body_end_line: body.map(|b| b.1),
2790 body_end_column: None,
2791 body_start_byte: None,
2792 body_end_byte: None,
2793 body_hash: None,
2794 semantic_group: None,
2795 is_test: false,
2796 test_container: false,
2797 }
2798 }
2799
2800 #[test]
2801 fn skeleton_nests_an_object_under_the_field_that_declares_it() {
2802 let syms = vec![
2803 skeleton_row(
2804 "root",
2805 None,
2806 "class",
2807 "shell",
2808 "extends ShellRoot",
2809 (1, 8),
2810 None,
2811 ),
2812 skeleton_row(
2813 "timer",
2814 Some("root"),
2815 "field",
2816 "localPluginReloadTimer",
2817 "localPluginReloadTimer: Timer",
2818 (2, 7),
2819 Some((2, 7)),
2820 ),
2821 skeleton_row(
2822 "interval",
2823 Some("timer"),
2824 "property",
2825 "interval",
2826 "interval: 150",
2827 (3, 3),
2828 None,
2829 ),
2830 skeleton_row(
2831 "fire",
2832 Some("timer"),
2833 "function",
2834 "fire",
2835 "function fire()",
2836 (5, 7),
2837 Some((6, 7)),
2838 ),
2839 ];
2840
2841 assert_eq!(
2842 format_file_skeleton("shell/shell.qml", &syms, Some(8), 0),
2843 "// File: shell/shell.qml (Lines 1-8)\n\
2844 \n\
2845 extends ShellRoot {\n\
2846 \x20 localPluginReloadTimer: Timer {\n\
2847 \x20 interval: 150; // L3-3\n\
2848 \x20 function fire() { /* 2 lines hidden: L6-L7 */ }\n\
2849 \x20 } // L2-7\n\
2850 \n\
2851 } // L1-8\n\
2852 \n"
2853 );
2854 }
2855
2856 #[test]
2857 fn skeleton_renders_a_single_line_symbol_with_children_as_a_leaf() {
2858 let syms = vec![
2859 skeleton_row(
2860 "rusqlite",
2861 None,
2862 "field",
2863 "rusqlite",
2864 "rusqlite = { workspace = true }",
2865 (15, 15),
2866 None,
2867 ),
2868 skeleton_row(
2869 "workspace",
2870 Some("rusqlite"),
2871 "property",
2872 "workspace",
2873 "workspace = true",
2874 (15, 15),
2875 None,
2876 ),
2877 ];
2878
2879 assert_eq!(
2880 format_file_skeleton("Cargo.toml", &syms, Some(15), 0),
2881 "// File: Cargo.toml (Lines 1-15)\n\
2882 \n\
2883 rusqlite = { workspace = true }; // L15-15\n"
2884 );
2885 }
2886
2887 #[test]
2888 fn skeleton_renders_members_of_a_single_line_enum() {
2889 let mut syms = vec![
2890 skeleton_row(
2891 "mode",
2892 None,
2893 "enum",
2894 "DispatchMode",
2895 "public enum DispatchMode",
2896 (21, 21),
2897 None,
2898 ),
2899 skeleton_row(
2900 "provision",
2901 Some("mode"),
2902 "enum_member",
2903 "Provision",
2904 "Provision",
2905 (21, 21),
2906 None,
2907 ),
2908 skeleton_row(
2909 "deprovision",
2910 Some("mode"),
2911 "enum_member",
2912 "Deprovision",
2913 "Deprovision",
2914 (21, 21),
2915 None,
2916 ),
2917 skeleton_row(
2918 "extension",
2919 Some("mode"),
2920 "enum_member",
2921 "Extension",
2922 "Extension",
2923 (21, 21),
2924 None,
2925 ),
2926 ];
2927 for symbol in &mut syms {
2928 symbol.language = "csharp".into();
2929 }
2930
2931 let skeleton = format_file_skeleton("DispatchContext.cs", &syms, Some(21), 0);
2932
2933 for member in ["Provision", "Deprovision", "Extension"] {
2934 assert!(skeleton.contains(member), "{skeleton}");
2935 }
2936 }
2937
2938 #[test]
2939 fn a_hidden_body_names_the_functions_defined_inside_it_but_not_lambdas() {
2940 let mut syms = vec![
2941 skeleton_row(
2942 "factory",
2943 None,
2944 "function",
2945 "create_app",
2946 "def create_app()",
2947 (1, 9),
2948 Some((2, 9)),
2949 ),
2950 skeleton_row(
2951 "hello",
2952 Some("factory"),
2953 "function",
2954 "hello",
2955 "def hello()",
2956 (4, 5),
2957 Some((5, 5)),
2958 ),
2959 skeleton_row(
2960 "lambda",
2961 Some("factory"),
2962 "function",
2963 "lambda_7",
2964 "lambda v: v",
2965 (7, 7),
2966 None,
2967 ),
2968 ];
2969 for symbol in &mut syms {
2970 symbol.language = "python".into();
2971 }
2972
2973 let skeleton = format_file_skeleton("app.py", &syms, Some(9), 0);
2974
2975 assert!(
2976 skeleton.contains("def create_app() { /* 8 lines hidden: L2-L9; defines `hello` */ }"),
2977 "{skeleton}"
2978 );
2979
2980 for symbol in &mut syms {
2981 symbol.language = "cpp".into();
2982 }
2983 let cpp = format_file_skeleton("app.cpp", &syms, Some(9), 0);
2984 assert!(!cpp.contains("defines"), "{cpp}");
2985 syms[1].test_container = true;
2986 let cpp_section = format_file_skeleton("app.cpp", &syms, Some(9), 0);
2987 assert!(cpp_section.contains("defines `hello`"), "{cpp_section}");
2988 }
2989
2990 #[test]
2991 fn skeleton_keeps_plain_fields_and_function_locals_unchanged() {
2992 let syms = vec![
2993 skeleton_row(
2994 "cfg",
2995 None,
2996 "struct",
2997 "Config",
2998 "pub struct Config",
2999 (1, 3),
3000 None,
3001 ),
3002 skeleton_row(
3003 "retries",
3004 Some("cfg"),
3005 "field",
3006 "retries",
3007 "pub retries: u32",
3008 (2, 2),
3009 None,
3010 ),
3011 skeleton_row(
3012 "run",
3013 None,
3014 "function",
3015 "run",
3016 "pub fn run()",
3017 (5, 9),
3018 Some((6, 8)),
3019 ),
3020 skeleton_row(
3021 "tmp",
3022 Some("run"),
3023 "variable",
3024 "tmp",
3025 "let tmp",
3026 (7, 7),
3027 None,
3028 ),
3029 ];
3030
3031 assert_eq!(
3032 format_file_skeleton("src/lib.rs", &syms, Some(9), 0),
3033 "// File: src/lib.rs (Lines 1-9)\n\
3034 \n\
3035 pub struct Config {\n\
3036 \x20 pub retries: u32; // L2-2\n\
3037 } // L1-3\n\
3038 \n\
3039 pub fn run() { /* 3 lines hidden: L6-L8 */ }\n"
3040 );
3041 }
3042
3043 #[test]
3044 fn skeleton_marks_an_event_row_whose_signature_does_not_spell_it() {
3045 let syms = vec![
3046 skeleton_row(
3047 "cls",
3048 None,
3049 "class",
3050 "ColumnViewAttached",
3051 "class ColumnViewAttached : public QObject",
3052 (11, 52),
3053 None,
3054 ),
3055 skeleton_row(
3056 "sig",
3057 Some("cls"),
3058 "event",
3059 "indexChanged",
3060 "void indexChanged()",
3061 (47, 47),
3062 None,
3063 ),
3064 skeleton_row(
3065 "qml",
3066 None,
3067 "event",
3068 "clicked",
3069 "signal clicked()",
3070 (60, 60),
3071 None,
3072 ),
3073 ];
3074
3075 assert_eq!(
3076 format_file_skeleton("src/columnview.h", &syms, Some(60), 0),
3077 "// File: src/columnview.h (Lines 1-60)\n\
3078 \n\
3079 class ColumnViewAttached : public QObject {\n\
3080 \x20 void indexChanged(); // event L47-47\n\
3081 } // L11-52\n\
3082 \n\
3083 signal clicked(); // L60-60\n"
3084 );
3085 }
3086}