Skip to main content

lean_ctx_syntax/
signatures.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Signature extraction — **regex fallback** layer.
4//!
5//! IMPORTANT for readers skimming the repo: this file is the *fallback*, not the
6//! primary engine. The default build extracts signatures with **tree-sitter** via
7//! declarative per-language queries in `crate::signatures_ts` (real ASTs,
8//! real multi-line spans, ~27 languages). [`extract_signatures_with_backend`] tries that path
9//! first and only drops to the line-oriented regex extractors here when the
10//! `tree-sitter` feature is off or a parse yields nothing usable for a file.
11//!
12//! The regex extractors are intentionally conservative: single-line declarations,
13//! declaration-line spans only (`end_line == start_line`). Use
14//! [`extract_signatures_with_backend`] when you need to know — and surface —
15//! which backend actually produced a result (gitlab #981).
16
17use regex::Regex;
18
19macro_rules! static_regex {
20    ($pattern:expr_2021) => {{
21        static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
22        RE.get_or_init(|| {
23            regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
24        })
25    }};
26}
27
28#[derive(Debug, Clone)]
29pub struct Signature {
30    pub kind: &'static str,
31    pub name: String,
32    pub params: String,
33    pub return_type: String,
34    pub is_async: bool,
35    pub is_exported: bool,
36    pub indent: usize,
37    pub start_line: Option<usize>,
38    pub end_line: Option<usize>,
39}
40
41/// Exports not already named by `key_sigs`. Map-mode renderers list the API
42/// with full signatures + line ranges; repeating those same names in an
43/// `exports:` line is pure redundancy. Callers surface only the exports the API
44/// does not already cover (e.g. re-exports or const/type aliases that aren't
45/// captured as signatures), keeping map lossless while dropping duplicates
46/// (#361). Shared by the MCP, CLI, and benchmark map renderers.
47#[must_use]
48pub fn exports_not_in_signatures<'a>(
49    exports: &'a [String],
50    key_sigs: &[&Signature],
51) -> Vec<&'a str> {
52    let api_names: std::collections::HashSet<&str> =
53        key_sigs.iter().map(|s| s.name.as_str()).collect();
54    exports
55        .iter()
56        .map(String::as_str)
57        .filter(|e| !api_names.contains(e))
58        .collect()
59}
60
61impl Signature {
62    pub fn no_span() -> Self {
63        Self {
64            kind: "",
65            name: String::new(),
66            params: String::new(),
67            return_type: String::new(),
68            is_async: false,
69            is_exported: false,
70            indent: 0,
71            start_line: None,
72            end_line: None,
73        }
74    }
75
76    /// Plain, self-describing notation (GL #580): real keywords (`class`,
77    /// `trait`, `pub`) instead of abbreviations, so a vanilla agent without
78    /// injected rules reads the output correctly. Keyword tokens cost the
79    /// same as (or less than) the old `cl`/`⊛` forms.
80    pub fn to_compact(&self) -> String {
81        let export = if self.is_exported { "pub " } else { "" };
82        let async_prefix = if self.is_async { "async " } else { "" };
83
84        match self.kind {
85            "fn" | "method" => {
86                let ret = if self.return_type.is_empty() {
87                    String::new()
88                } else {
89                    format!(" → {}", self.return_type)
90                };
91                let indent = " ".repeat(self.indent);
92                format!(
93                    "{indent}fn {async_prefix}{export}{}({}){}",
94                    self.name, self.params, ret
95                )
96            }
97            "const" | "let" | "var" => {
98                let ty = if self.return_type.is_empty() {
99                    String::new()
100                } else {
101                    format!(":{}", self.return_type)
102                };
103                format!("{} {export}{}{ty}", self.kind, self.name)
104            }
105            // `kind` is already the source-language keyword (class, struct,
106            // interface, trait, type, enum) — use it verbatim.
107            _ => format!("{} {export}{}", self.kind, self.name),
108        }
109    }
110
111    pub fn to_tdd(&self) -> String {
112        let vis = if self.is_exported { "+" } else { "-" };
113        let a = if self.is_async { "~" } else { "" };
114
115        match self.kind {
116            "fn" | "method" => {
117                let ret = if self.return_type.is_empty() {
118                    String::new()
119                } else {
120                    format!("→{}", compact_type(&self.return_type))
121                };
122                let params = tdd_params(&self.params);
123                let indent = if self.indent > 0 { " " } else { "" };
124                format!("{indent}{a}λ{vis}{}({params}){ret}", self.name)
125            }
126            "class" | "struct" => format!("§{vis}{}", self.name),
127            "interface" | "trait" => format!("∂{vis}{}", self.name),
128            "type" => format!("τ{vis}{}", self.name),
129            "enum" => format!("ε{vis}{}", self.name),
130            "const" | "let" | "var" => {
131                let ty = if self.return_type.is_empty() {
132                    String::new()
133                } else {
134                    format!(":{}", compact_type(&self.return_type))
135                };
136                format!("ν{vis}{}{ty}", self.name)
137            }
138            _ => format!(
139                "{}{vis}{}",
140                self.kind.chars().next().unwrap_or('?'),
141                self.name
142            ),
143        }
144    }
145
146    /// Compact ` @Lstart[-end]` suffix for navigation-focused modes.
147    /// Returns an empty string when the span is unknown, so compression-first
148    /// modes that render the base `to_compact`/`to_tdd` stay byte-identical.
149    pub fn line_suffix(&self) -> String {
150        match (self.start_line, self.end_line) {
151            (Some(start), Some(end)) if start > 0 && end > start => format!(" @L{start}-{end}"),
152            (Some(start), _) if start > 0 => format!(" @L{start}"),
153            _ => String::new(),
154        }
155    }
156
157    /// `to_compact` plus a line-span suffix. Reserved for navigation modes
158    /// (`map`/`signatures`) where locating code outweighs the few extra tokens.
159    pub fn to_compact_located(&self) -> String {
160        format!("{}{}", self.to_compact(), self.line_suffix())
161    }
162
163    /// `to_tdd` plus a line-span suffix. Reserved for navigation modes.
164    pub fn to_tdd_located(&self) -> String {
165        format!("{}{}", self.to_tdd(), self.line_suffix())
166    }
167}
168
169/// One-line legend for TDD symbol notation (GL #580): outputs must be
170/// self-describing for vanilla agents without injected rules. Only the
171/// symbols actually present in `sigs` are explained, keeping the line well
172/// under the 15-token budget for typical files. Empty when nothing applies.
173pub fn tdd_legend<'a>(sigs: &[&'a Signature]) -> String {
174    if sigs.is_empty() {
175        return String::new();
176    }
177    let mut parts: Vec<&str> = Vec::new();
178    let has = |pred: &dyn Fn(&'a Signature) -> bool| sigs.iter().any(|s| pred(s));
179
180    if has(&|s| matches!(s.kind, "fn" | "method")) {
181        parts.push("λ=fn");
182    }
183    if has(&|s| matches!(s.kind, "class" | "struct")) {
184        parts.push("§=class");
185    }
186    if has(&|s| matches!(s.kind, "interface" | "trait")) {
187        parts.push("∂=trait");
188    }
189    if has(&|s| s.kind == "type") {
190        parts.push("τ=type");
191    }
192    if has(&|s| s.kind == "enum") {
193        parts.push("ε=enum");
194    }
195    if has(&|s| matches!(s.kind, "const" | "let" | "var")) {
196        parts.push("ν=val");
197    }
198    if has(&|s| s.is_exported) {
199        parts.push("+=pub");
200    }
201    if has(&|s| s.is_async) {
202        parts.push("~=async");
203    }
204    if parts.is_empty() {
205        String::new()
206    } else {
207        format!("[{}]", parts.join(" "))
208    }
209}
210
211fn fn_re() -> &'static Regex {
212    static_regex!(
213        r"^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*(?:<[^>]*>)?\s*\(([^)]*)\)(?:\s*:\s*([^\{]+))?\s*\{?"
214    )
215}
216
217fn class_re() -> &'static Regex {
218    static_regex!(r"^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)")
219}
220
221fn iface_re() -> &'static Regex {
222    static_regex!(r"^(\s*)(export\s+)?interface\s+(\w+)")
223}
224
225fn type_re() -> &'static Regex {
226    static_regex!(r"^(\s*)(export\s+)?type\s+(\w+)")
227}
228
229fn const_re() -> &'static Regex {
230    static_regex!(r"^(\s*)(export\s+)?(const|let|var)\s+(\w+)(?:\s*:\s*(\w+))?")
231}
232
233fn rust_fn_re() -> &'static Regex {
234    static_regex!(
235        r"^(\s*)(pub\s+)?(async\s+)?fn\s+(\w+)\s*(?:<[^>]*>)?\s*\(([^)]*)\)(?:\s*->\s*([^\{]+))?\s*\{?"
236    )
237}
238
239fn rust_struct_re() -> &'static Regex {
240    static_regex!(r"^(\s*)(pub\s+)?struct\s+(\w+)")
241}
242
243fn rust_enum_re() -> &'static Regex {
244    static_regex!(r"^(\s*)(pub\s+)?enum\s+(\w+)")
245}
246
247fn rust_trait_re() -> &'static Regex {
248    static_regex!(r"^(\s*)(pub\s+)?trait\s+(\w+)")
249}
250
251fn rust_impl_re() -> &'static Regex {
252    static_regex!(r"^(\s*)impl\s+(?:(\w+)\s+for\s+)?(\w+)")
253}
254
255use std::sync::atomic::{AtomicU64, Ordering};
256
257static TREE_SITTER_HITS: AtomicU64 = AtomicU64::new(0);
258static REGEX_FALLBACK_HITS: AtomicU64 = AtomicU64::new(0);
259
260/// Returns (tree_sitter_hits, regex_fallback_hits) since process start.
261pub fn signature_backend_stats() -> (u64, u64) {
262    (
263        TREE_SITTER_HITS.load(Ordering::Relaxed),
264        REGEX_FALLBACK_HITS.load(Ordering::Relaxed),
265    )
266}
267
268/// Which extractor produced a signature set: the primary tree-sitter AST path
269/// (`crate::signatures_ts`) or the line-oriented regex fallback in this
270/// module. Surfaced so navigation output (`ctx_outline`) can label its backend
271/// honestly and verifiably instead of merely *claiming* "via tree-sitter"
272/// (gitlab #981).
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub enum SigBackend {
275    TreeSitter,
276    Regex,
277}
278
279impl SigBackend {
280    #[must_use]
281    pub fn as_str(self) -> &'static str {
282        match self {
283            SigBackend::TreeSitter => "tree-sitter",
284            SigBackend::Regex => "regex",
285        }
286    }
287}
288
289/// Per-session blocklist for tree-sitter languages that panicked during parsing.
290/// Once a language panics, all subsequent calls for that extension skip straight
291/// to the regex fallback — no repeated catch_unwind overhead.
292#[cfg(feature = "tree-sitter")]
293mod ts_blocklist {
294    use std::collections::HashSet;
295    use std::sync::Mutex;
296
297    static BLOCKED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
298
299    fn lock() -> std::sync::MutexGuard<'static, Option<HashSet<String>>> {
300        match BLOCKED.lock() {
301            Ok(g) => g,
302            Err(poisoned) => poisoned.into_inner(),
303        }
304    }
305
306    pub(super) fn is_blocked(ext: &str) -> bool {
307        lock().as_ref().is_some_and(|set| set.contains(ext))
308    }
309
310    pub(super) fn block(ext: &str) {
311        lock()
312            .get_or_insert_with(HashSet::new)
313            .insert(ext.to_string());
314    }
315}
316
317#[cfg(feature = "tree-sitter")]
318use ts_blocklist::{block as block_ts_language, is_blocked as is_ts_language_blocked};
319
320/// Whether tree-sitter is blocklisted for `file_ext` in this process after a
321/// parser panic. Signatures for such a language come from the regex fallback,
322/// so a cache of parser output must neither store nor serve them.
323#[must_use]
324pub fn tree_sitter_language_blocked(file_ext: &str) -> bool {
325    #[cfg(feature = "tree-sitter")]
326    {
327        is_ts_language_blocked(file_ext)
328    }
329    #[cfg(not(feature = "tree-sitter"))]
330    {
331        let _ = file_ext;
332        false
333    }
334}
335
336/// Blocklist `file_ext` as if its parser had panicked (tests of callers that
337/// must not persist fallback output).
338#[doc(hidden)]
339pub fn block_tree_sitter_language_for_tests(file_ext: &str) {
340    #[cfg(feature = "tree-sitter")]
341    block_ts_language(file_ext);
342    #[cfg(not(feature = "tree-sitter"))]
343    let _ = file_ext;
344}
345
346/// Extract signatures and count the producing backend in the process-lifetime
347/// [`signature_backend_stats`]. Returns the backend as well, so the engine's
348/// `extract_signatures` can add its persistent per-extension telemetry.
349pub fn extract_signatures_counted(content: &str, file_ext: &str) -> (Vec<Signature>, SigBackend) {
350    let (sigs, backend) = extract_signatures_with_backend(content, file_ext);
351    count_signature_backend(backend);
352    (sigs, backend)
353}
354
355/// Count one extraction by `backend` in [`signature_backend_stats`] — for
356/// callers that serve a previously counted extraction from a cache, so the
357/// stats keep counting every file whose signatures were delivered.
358pub fn count_signature_backend(backend: SigBackend) {
359    match backend {
360        SigBackend::TreeSitter => TREE_SITTER_HITS.fetch_add(1, Ordering::Relaxed),
361        SigBackend::Regex => REGEX_FALLBACK_HITS.fetch_add(1, Ordering::Relaxed),
362    };
363}
364
365/// Like [`extract_signatures_counted`] but does **not** touch the global
366/// backend counters, so callers that only want the label (e.g. per-file JSON
367/// outline) don't distort [`signature_backend_stats`]; the counted path stays
368/// [`extract_signatures_counted`].
369pub fn extract_signatures_with_backend(
370    content: &str,
371    file_ext: &str,
372) -> (Vec<Signature>, SigBackend) {
373    #[cfg(feature = "tree-sitter")]
374    {
375        // A successful parse that yields no signatures (`Some(vec![])`) means the
376        // tree-sitter query set has a gap for this file's constructs. Fall through
377        // to the regex extractors instead of returning the empty result, which
378        // would otherwise suppress signatures the regex fallback can still
379        // recover (e.g. constructs the query does not capture).
380        //
381        // Wrapped in catch_unwind: tree-sitter grammars can panic on certain
382        // files (e.g. "range start index N out of range for slice of length 0").
383        // A single panic must not cascade — it falls through to the regex
384        // extractor, and the language is blocklisted for the rest of the session.
385        if !is_ts_language_blocked(file_ext) {
386            match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
387                super::signatures_ts::extract_signatures_ts(content, file_ext)
388            })) {
389                Ok(Some(sigs)) if !sigs.is_empty() => {
390                    return (sigs, SigBackend::TreeSitter);
391                }
392                Err(_) => {
393                    block_ts_language(file_ext);
394                    eprintln!(
395                        "[lean-ctx] tree-sitter panicked for .{file_ext} — using regex fallback"
396                    );
397                }
398                _ => {}
399            }
400        }
401    }
402
403    let sigs = match file_ext {
404        "rs" => extract_rust_signatures(content),
405        "ts" | "tsx" | "js" | "jsx" | "svelte" | "vue" => extract_ts_signatures(content),
406        "py" => extract_python_signatures(content),
407        "go" => extract_go_signatures(content),
408        _ => extract_generic_signatures(content),
409    };
410    (sigs, SigBackend::Regex)
411}
412
413fn extract_ts_signatures(content: &str) -> Vec<Signature> {
414    let mut sigs = Vec::new();
415
416    for (line_idx, line) in content.lines().enumerate() {
417        let line_no = line_idx + 1;
418        let trimmed = line.trim();
419        if trimmed.starts_with("//") || trimmed.starts_with("/*") || trimmed.starts_with('*') {
420            continue;
421        }
422
423        if let Some(caps) = fn_re().captures(line) {
424            let indent = caps.get(1).map_or(0, |m| m.as_str().len());
425            sigs.push(Signature {
426                kind: if indent > 0 { "method" } else { "fn" },
427                name: caps[4].to_string(),
428                params: compact_params(&caps[5]),
429                return_type: caps
430                    .get(6)
431                    .map_or(String::new(), |m| m.as_str().trim().to_string()),
432                is_async: caps.get(3).is_some(),
433                is_exported: caps.get(2).is_some(),
434                indent: if indent > 0 { 2 } else { 0 },
435                start_line: Some(line_no),
436                end_line: Some(line_no),
437            });
438        } else if let Some(caps) = class_re().captures(line) {
439            sigs.push(Signature {
440                kind: "class",
441                name: caps[4].to_string(),
442                params: String::new(),
443                return_type: String::new(),
444                is_async: false,
445                is_exported: caps.get(2).is_some(),
446                indent: 0,
447                start_line: Some(line_no),
448                end_line: Some(line_no),
449            });
450        } else if let Some(caps) = iface_re().captures(line) {
451            sigs.push(Signature {
452                kind: "interface",
453                name: caps[3].to_string(),
454                params: String::new(),
455                return_type: String::new(),
456                is_async: false,
457                is_exported: caps.get(2).is_some(),
458                indent: 0,
459                start_line: Some(line_no),
460                end_line: Some(line_no),
461            });
462        } else if let Some(caps) = type_re().captures(line) {
463            sigs.push(Signature {
464                kind: "type",
465                name: caps[3].to_string(),
466                params: String::new(),
467                return_type: String::new(),
468                is_async: false,
469                is_exported: caps.get(2).is_some(),
470                indent: 0,
471                start_line: Some(line_no),
472                end_line: Some(line_no),
473            });
474        } else if let Some(caps) = const_re().captures(line)
475            && caps.get(2).is_some()
476        {
477            sigs.push(Signature {
478                kind: "const",
479                name: caps[4].to_string(),
480                params: String::new(),
481                return_type: caps
482                    .get(5)
483                    .map_or(String::new(), |m| m.as_str().to_string()),
484                is_async: false,
485                is_exported: true,
486                indent: 0,
487                start_line: Some(line_no),
488                end_line: Some(line_no),
489            });
490        }
491    }
492
493    sigs
494}
495
496fn extract_rust_signatures(content: &str) -> Vec<Signature> {
497    let mut sigs = Vec::new();
498
499    for (line_idx, line) in content.lines().enumerate() {
500        let line_no = line_idx + 1;
501        let trimmed = line.trim();
502        if trimmed.starts_with("//") || trimmed.starts_with("///") {
503            continue;
504        }
505
506        if let Some(caps) = rust_fn_re().captures(line) {
507            let indent = caps.get(1).map_or(0, |m| m.as_str().len());
508            sigs.push(Signature {
509                kind: if indent > 0 { "method" } else { "fn" },
510                name: caps[4].to_string(),
511                params: compact_params(&caps[5]),
512                return_type: caps
513                    .get(6)
514                    .map_or(String::new(), |m| m.as_str().trim().to_string()),
515                is_async: caps.get(3).is_some(),
516                is_exported: caps.get(2).is_some(),
517                indent: if indent > 0 { 2 } else { 0 },
518                start_line: Some(line_no),
519                end_line: Some(line_no),
520            });
521        } else if let Some(caps) = rust_struct_re().captures(line) {
522            sigs.push(Signature {
523                kind: "struct",
524                name: caps[3].to_string(),
525                params: String::new(),
526                return_type: String::new(),
527                is_async: false,
528                is_exported: caps.get(2).is_some(),
529                indent: 0,
530                start_line: Some(line_no),
531                end_line: Some(line_no),
532            });
533        } else if let Some(caps) = rust_enum_re().captures(line) {
534            sigs.push(Signature {
535                kind: "enum",
536                name: caps[3].to_string(),
537                params: String::new(),
538                return_type: String::new(),
539                is_async: false,
540                is_exported: caps.get(2).is_some(),
541                indent: 0,
542                start_line: Some(line_no),
543                end_line: Some(line_no),
544            });
545        } else if let Some(caps) = rust_trait_re().captures(line) {
546            sigs.push(Signature {
547                kind: "trait",
548                name: caps[3].to_string(),
549                params: String::new(),
550                return_type: String::new(),
551                is_async: false,
552                is_exported: caps.get(2).is_some(),
553                indent: 0,
554                start_line: Some(line_no),
555                end_line: Some(line_no),
556            });
557        } else if let Some(caps) = rust_impl_re().captures(line) {
558            let trait_name = caps.get(2).map(|m| m.as_str());
559            let type_name = &caps[3];
560            let name = if let Some(t) = trait_name {
561                format!("{t} for {type_name}")
562            } else {
563                type_name.to_string()
564            };
565            sigs.push(Signature {
566                kind: "impl",
567                name,
568                params: String::new(),
569                return_type: String::new(),
570                is_async: false,
571                is_exported: false,
572                indent: 0,
573                start_line: Some(line_no),
574                end_line: Some(line_no),
575            });
576        }
577    }
578
579    sigs
580}
581
582fn extract_python_signatures(content: &str) -> Vec<Signature> {
583    let mut sigs = Vec::new();
584    let py_fn = static_regex!(r"^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*(\w+))?");
585    let py_class = static_regex!(r"^(\s*)class\s+(\w+)");
586
587    for (line_idx, line) in content.lines().enumerate() {
588        let line_no = line_idx + 1;
589        if let Some(caps) = py_fn.captures(line) {
590            let indent = caps.get(1).map_or(0, |m| m.as_str().len());
591            sigs.push(Signature {
592                kind: if indent > 0 { "method" } else { "fn" },
593                name: caps[3].to_string(),
594                params: compact_params(&caps[4]),
595                return_type: caps
596                    .get(5)
597                    .map_or(String::new(), |m| m.as_str().to_string()),
598                is_async: caps.get(2).is_some(),
599                is_exported: !caps[3].starts_with('_'),
600                indent: if indent > 0 { 2 } else { 0 },
601                start_line: Some(line_no),
602                end_line: Some(line_no),
603            });
604        } else if let Some(caps) = py_class.captures(line) {
605            sigs.push(Signature {
606                kind: "class",
607                name: caps[2].to_string(),
608                params: String::new(),
609                return_type: String::new(),
610                is_async: false,
611                is_exported: !caps[2].starts_with('_'),
612                indent: 0,
613                start_line: Some(line_no),
614                end_line: Some(line_no),
615            });
616        }
617    }
618
619    sigs
620}
621
622fn extract_go_signatures(content: &str) -> Vec<Signature> {
623    let mut sigs = Vec::new();
624    let go_fn = static_regex!(
625        r"^func\s+(?:\((\w+)\s+\*?(\w+)\)\s+)?(\w+)\s*\(([^)]*)\)(?:\s*(?:\(([^)]*)\)|(\w+)))?\s*\{"
626    );
627    let go_type = static_regex!(r"^type\s+(\w+)\s+(struct|interface)");
628
629    for (line_idx, line) in content.lines().enumerate() {
630        let line_no = line_idx + 1;
631        if let Some(caps) = go_fn.captures(line) {
632            let is_method = caps.get(2).is_some();
633            sigs.push(Signature {
634                kind: if is_method { "method" } else { "fn" },
635                name: caps[3].to_string(),
636                params: compact_params(&caps[4]),
637                return_type: caps
638                    .get(5)
639                    .or(caps.get(6))
640                    .map_or(String::new(), |m| m.as_str().to_string()),
641                is_async: false,
642                is_exported: caps[3].starts_with(char::is_uppercase),
643                indent: if is_method { 2 } else { 0 },
644                start_line: Some(line_no),
645                end_line: Some(line_no),
646            });
647        } else if let Some(caps) = go_type.captures(line) {
648            sigs.push(Signature {
649                kind: if &caps[2] == "struct" {
650                    "struct"
651                } else {
652                    "interface"
653                },
654                name: caps[1].to_string(),
655                params: String::new(),
656                return_type: String::new(),
657                is_async: false,
658                is_exported: caps[1].starts_with(char::is_uppercase),
659                indent: 0,
660                start_line: Some(line_no),
661                end_line: Some(line_no),
662            });
663        }
664    }
665
666    sigs
667}
668
669/// Normalise a parameter list to `name:Type` pairs. Types stay verbatim: the
670/// plain notation is read by agents without a legend, so `i32` vs `u64` or
671/// `&str` vs `String` must survive. The TDD renderer abbreviates on its own
672/// (`tdd_params` → `compact_type`).
673pub(crate) fn compact_params(params: &str) -> String {
674    if params.trim().is_empty() {
675        return String::new();
676    }
677    params
678        .split(',')
679        .map(|p| {
680            let p = p.trim();
681            if let Some((name, ty)) = p.split_once(':') {
682                format!("{}:{}", name.trim(), ty.trim())
683            } else {
684                p.to_string()
685            }
686        })
687        .collect::<Vec<_>>()
688        .join(", ")
689}
690
691fn compact_type(ty: &str) -> String {
692    match ty.trim() {
693        "String" | "string" | "&str" | "str" => "s".to_string(),
694        "bool" | "boolean" => "b".to_string(),
695        "i32" | "i64" | "u32" | "u64" | "usize" | "f32" | "f64" | "number" => "n".to_string(),
696        "void" | "()" => "∅".to_string(),
697        other => {
698            if other.starts_with("Vec<") || other.starts_with("Array<") {
699                let inner = other
700                    .trim_start_matches("Vec<")
701                    .trim_start_matches("Array<")
702                    .trim_end_matches('>');
703                format!("[{}]", compact_type(inner))
704            } else if other.starts_with("Option<") || other.starts_with("Maybe<") {
705                let inner = other
706                    .trim_start_matches("Option<")
707                    .trim_start_matches("Maybe<")
708                    .trim_end_matches('>');
709                format!("?{}", compact_type(inner))
710            } else if other.starts_with("Result<") {
711                "R".to_string()
712            } else if other.starts_with("impl ") {
713                other.trim_start_matches("impl ").to_string()
714            } else {
715                other.to_string()
716            }
717        }
718    }
719}
720
721fn tdd_params(params: &str) -> String {
722    if params.trim().is_empty() {
723        return String::new();
724    }
725    params
726        .split(',')
727        .map(|p| {
728            let p = p.trim();
729            if p.starts_with('&') {
730                let rest = p.trim_start_matches("&mut ").trim_start_matches('&');
731                if let Some((name, ty)) = rest.split_once(':') {
732                    format!("&{}:{}", name.trim(), compact_type(ty))
733                } else {
734                    p.to_string()
735                }
736            } else if let Some((name, ty)) = p.split_once(':') {
737                format!("{}:{}", name.trim(), compact_type(ty))
738            } else if p == "self" || p == "&self" || p == "&mut self" {
739                "⊕".to_string()
740            } else {
741                p.to_string()
742            }
743        })
744        .collect::<Vec<_>>()
745        .join(",")
746}
747
748fn extract_generic_signatures(content: &str) -> Vec<Signature> {
749    let re_func = static_regex!(
750        r"^\s*(?:(?:public|private|protected|static|async|abstract|virtual|override|final|def|func|fun|fn)\s+)+(\w+)\s*\("
751    );
752    // PowerShell-style declarations: `function Verb-Noun {` — no paren required,
753    // hyphens allowed in the name. Also catches bash-like dialects the keyword+
754    // paren pattern above misses.
755    let re_ps_func = static_regex!(r"^\s*function\s+([\w-]+)");
756    let re_class = static_regex!(
757        r"^\s*(?:(?:public|private|protected|abstract|final|sealed|partial)\s+)*(?:class|struct|enum|interface|trait|module|object|record)\s+(\w+)"
758    );
759
760    let mut sigs = Vec::new();
761    for (line_idx, line) in content.lines().enumerate() {
762        let line_no = line_idx + 1;
763        let trimmed = line.trim();
764        if trimmed.is_empty()
765            || trimmed.starts_with("//")
766            || trimmed.starts_with('#')
767            || trimmed.starts_with("/*")
768            || trimmed.starts_with('*')
769        {
770            continue;
771        }
772        if let Some(caps) = re_class.captures(trimmed) {
773            sigs.push(Signature {
774                kind: "type",
775                name: caps[1].to_string(),
776                params: String::new(),
777                return_type: String::new(),
778                is_async: false,
779                is_exported: true,
780                indent: 0,
781                start_line: Some(line_no),
782                end_line: Some(line_no),
783            });
784        } else if let Some(caps) = re_func.captures(trimmed) {
785            sigs.push(Signature {
786                kind: "fn",
787                name: caps[1].to_string(),
788                params: String::new(),
789                return_type: String::new(),
790                is_async: trimmed.contains("async"),
791                is_exported: true,
792                indent: 0,
793                start_line: Some(line_no),
794                end_line: Some(line_no),
795            });
796        } else if let Some(caps) = re_ps_func.captures(trimmed) {
797            sigs.push(Signature {
798                kind: "fn",
799                name: caps[1].to_string(),
800                params: String::new(),
801                return_type: String::new(),
802                is_async: false,
803                is_exported: true,
804                indent: 0,
805                start_line: Some(line_no),
806                end_line: Some(line_no),
807            });
808        }
809    }
810    sigs
811}
812
813#[cfg(test)]
814mod tests {
815    use super::*;
816
817    fn sample_fn() -> Signature {
818        Signature {
819            kind: "fn",
820            name: "run".to_string(),
821            params: "id:usize".to_string(),
822            return_type: "bool".to_string(),
823            is_async: false,
824            is_exported: true,
825            indent: 0,
826            start_line: None,
827            end_line: None,
828        }
829    }
830
831    #[test]
832    fn line_suffix_formats_known_spans() {
833        let mut sig = sample_fn();
834        assert_eq!(sig.line_suffix(), "");
835
836        sig.start_line = Some(42);
837        sig.end_line = Some(42);
838        assert_eq!(sig.line_suffix(), " @L42");
839
840        sig.end_line = Some(57);
841        assert_eq!(sig.line_suffix(), " @L42-57");
842    }
843
844    #[test]
845    fn base_renderers_stay_suffix_free() {
846        // Compression-first modes must never pay for line ranges, even when
847        // the span is known.
848        let mut sig = sample_fn();
849        sig.start_line = Some(3);
850        sig.end_line = Some(9);
851        assert_eq!(sig.to_compact(), "fn pub run(id:usize) → bool");
852        assert_eq!(sig.to_tdd(), "λ+run(id:n)→b");
853    }
854
855    #[test]
856    fn located_renderers_append_line_suffix() {
857        let mut sig = sample_fn();
858        // Unknown span → identical to the base renderer.
859        assert_eq!(sig.to_compact_located(), "fn pub run(id:usize) → bool");
860        assert_eq!(sig.to_tdd_located(), "λ+run(id:n)→b");
861
862        sig.start_line = Some(3);
863        sig.end_line = Some(5);
864        assert_eq!(
865            sig.to_compact_located(),
866            "fn pub run(id:usize) → bool @L3-5"
867        );
868        assert_eq!(sig.to_tdd_located(), "λ+run(id:n)→b @L3-5");
869    }
870
871    #[test]
872    fn plain_notation_is_self_describing() {
873        // GL #580: plain mode must read like source keywords, no decoder ring.
874        let mut sig = sample_fn();
875        sig.kind = "struct";
876        assert_eq!(sig.to_compact(), "struct pub run");
877        sig.kind = "trait";
878        assert_eq!(sig.to_compact(), "trait pub run");
879        sig.kind = "enum";
880        sig.is_exported = false;
881        assert_eq!(sig.to_compact(), "enum run");
882        sig.kind = "const";
883        sig.return_type = "u32".to_string();
884        assert_eq!(sig.to_compact(), "const run:u32");
885        // Extracted parameter types stay exact (`a:i32`, not the lossy `a:n`).
886        let (extracted, _) =
887            extract_signatures_with_backend("fn f0(a: i32, s: &str) -> i32 {\n}\n", "rs");
888        assert_eq!(extracted[0].to_compact(), "fn f0(a:i32, s:&str) → i32");
889    }
890
891    #[test]
892    fn tdd_legend_explains_only_present_symbols() {
893        // GL #580: symbol outputs carry their own minimal legend.
894        let f = sample_fn();
895        let mut s = sample_fn();
896        s.kind = "struct";
897        s.is_exported = false;
898
899        let legend = tdd_legend(&[&f, &s]);
900        assert_eq!(legend, "[λ=fn §=class +=pub]");
901        // Stays comfortably under the 15-token budget for a typical file.
902        assert!(
903            lean_ctx_patterns::tokens::count_tokens(&legend) <= 15,
904            "{legend}"
905        );
906
907        assert_eq!(tdd_legend(&[]), "");
908    }
909
910    #[test]
911    fn regex_fallback_assigns_declaration_line_spans() {
912        let src = "\npublic class Service {}\n\npublic fn run() {\n}\n";
913        let sigs = extract_generic_signatures(src);
914
915        let service = sigs.iter().find(|s| s.name == "Service").unwrap();
916        assert_eq!(service.start_line, Some(2));
917        assert_eq!(service.end_line, Some(2));
918
919        let run = sigs.iter().find(|s| s.name == "run").unwrap();
920        assert_eq!(run.start_line, Some(4));
921        assert_eq!(run.end_line, Some(4));
922    }
923
924    // PowerShell in the generic regex fallback: `function Verb-Noun {` has no
925    // paren and a hyphenated name, which the old keyword+paren pattern missed
926    // entirely (limitation audit 2026-07-03). Covers non-tree-sitter builds.
927    #[test]
928    fn regex_fallback_matches_powershell_functions() {
929        let src = "function Get-CargoBinDir {\n}\nfunction Install($x) {\n}\n# function Commented-Out {\n";
930        let sigs = extract_generic_signatures(src);
931        let names: Vec<&str> = sigs.iter().map(|s| s.name.as_str()).collect();
932        assert!(names.contains(&"Get-CargoBinDir"), "got {names:?}");
933        assert!(names.contains(&"Install"), "got {names:?}");
934        assert!(
935            !names.contains(&"Commented-Out"),
936            "comment must be skipped; got {names:?}"
937        );
938    }
939}