tldr-cli 0.4.0

CLI binary for TLDR code analysis tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! Per-language test framework recognizers.
//!
//! Closes phase-11 BUG-AGG-3 (HIGH): `tldr specs --from-tests` and
//! `tldr invariants --from-tests` previously hard-coded Python `test_*`
//! pytest-style discovery, so JavaScript/Java/PHP/Swift/Go/Kotlin/Scala/
//! Ruby/Elixir/Lua test directories returned `test_files_scanned = 0`
//! despite containing real test functions.
//!
//! Each recognizer answers two questions per file:
//!
//! 1. **Is this a test file?** (per the language's discovery convention)
//! 2. **How many test functions does it contain?** (counted via tree-sitter
//!    AST walks rather than text-level heuristics, so comments and string
//!    literals can't false-match.)
//!
//! Languages handled:
//!
//! | Language    | Convention                                                 |
//! |-------------|------------------------------------------------------------|
//! | Python      | `def test_*` (pytest) or methods inside `class Test*`      |
//! | JavaScript  | `it(...)` / `test(...)` calls (Mocha/Jest/Jasmine)         |
//! | TypeScript  | `it(...)` / `test(...)` calls                              |
//! | Java        | Methods annotated with `@Test`                             |
//! | Kotlin      | Methods annotated with `@Test`                             |
//! | PHP         | `public function test*` inside class whose name ends `Test`|
//! | Swift       | `func test*()` inside class extending `XCTestCase`         |
//! | Ruby        | `def test_*` (Minitest) or `it/describe` blocks (RSpec)    |
//! | Go          | Top-level `func TestXxx(t *testing.T)`                     |
//! | Scala       | `test("...")` calls (Munit/ScalaTest FunSuite)             |
//! | Elixir      | `test "..." do ... end` blocks (ExUnit)                    |
//! | Lua / Luau  | `it(...)` / `describe(...)` blocks (busted)                |
//! | Rust        | `fn` items immediately preceded by `#[test]`               |
//! | C#          | Methods with `[Test]` / `[Fact]` / `[TestMethod]`          |
//! | C / C++ /   | (No widely standard test framework — fall back to file     |
//! | OCaml       |  count when name suggests test, function count = 0; the   |
//! |             |  framework adapter can be wired later.)                    |
//!
//! For languages without a clear convention, the recognizer treats files
//! whose name contains `test` (case-insensitive) as test files but reports
//! `0` functions — strictly better than the previous behaviour where the
//! file count itself was always `0` for non-Python.

use std::path::Path;

use tldr_core::ast::ParserPool;
use tldr_core::Language;
use tree_sitter::{Node, Tree};

/// Result of inspecting a single candidate file for test functions.
#[derive(Debug, Clone, Default)]
pub struct TestFileInfo {
    /// True if this file participates in a test suite (i.e. should bump
    /// `test_files_scanned`).
    pub is_test_file: bool,
    /// Number of test functions detected by walking the AST.
    pub test_function_count: u32,
}

/// Public entry point: classify a candidate file and count its tests.
///
/// `language` is the language the caller has already detected for the
/// file (typically via `Language::from_path` in `run_specs` /
/// `collect_observations`). Returns a default zero-info value if the
/// file is not parseable in this language.
pub fn recognize(path: &Path, source: &str, language: Language) -> TestFileInfo {
    if !is_candidate_test_file(path, language) {
        return TestFileInfo::default();
    }

    // language-specific-bugs-v1 (P14.AGG14-9): for Rust, every `.rs` is
    // a path-level candidate so `tldr specs --from-tests` can cover
    // inline `#[cfg(test)] mod tests { ... }` blocks inside production
    // source files (e.g. ripgrep `crates/globset/src/lib.rs`). To keep
    // directory walks cheap, gate on a fast `#[test]` substring check
    // before parsing — any `.rs` without `#[test]` cannot contribute
    // and parsing the entire file would just be wasted work.
    if matches!(language, Language::Rust) && !source.contains("#[test]") {
        return TestFileInfo::default();
    }

    // Empty or whitespace-only files: nothing to count.
    if source.trim().is_empty() {
        return TestFileInfo {
            is_test_file: true,
            test_function_count: 0,
        };
    }

    let pool = ParserPool::new();
    let tree = match pool.parse(source, language).ok() {
        Some(t) => t,
        None => {
            return TestFileInfo {
                is_test_file: true,
                test_function_count: 0,
            };
        }
    };

    let count = count_test_functions(&tree, source.as_bytes(), language);

    TestFileInfo {
        is_test_file: true,
        test_function_count: count,
    }
}

/// Decide whether `path` matches the language's test-file naming convention.
///
/// Each language has its own convention; we centralise them here so
/// `run_specs` can early-skip non-tests cheaply (without parsing).
fn is_candidate_test_file(path: &Path, language: Language) -> bool {
    let file_name = match path.file_name().and_then(|n| n.to_str()) {
        Some(n) => n,
        None => return false,
    };
    let stem = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or(file_name);
    let lower = file_name.to_ascii_lowercase();

    match language {
        // Python: `test_*.py` (pytest) or `*_test.py` (unittest-style).
        Language::Python => {
            file_name.starts_with("test_") && file_name.ends_with(".py")
                || file_name.ends_with("_test.py")
        }
        // JavaScript / TypeScript: Jest/Mocha conventions.
        // `*.test.js` / `*.spec.js` (and tsx/jsx variants), or any file
        // inside a directory literally named `__tests__`.
        Language::JavaScript | Language::TypeScript => {
            let in_tests_dir = path
                .components()
                .any(|c| c.as_os_str() == "__tests__" || c.as_os_str() == "test"
                    || c.as_os_str() == "tests" || c.as_os_str() == "spec");
            let has_test_marker = stem.ends_with(".test")
                || stem.ends_with(".spec")
                || stem.ends_with("_test")
                || stem.ends_with("_spec")
                || stem.ends_with("Test")
                || stem.ends_with("Spec");
            (has_test_marker || in_tests_dir)
                && (lower.ends_with(".js")
                    || lower.ends_with(".jsx")
                    || lower.ends_with(".mjs")
                    || lower.ends_with(".cjs")
                    || lower.ends_with(".ts")
                    || lower.ends_with(".tsx"))
        }
        // Java: Maven/Gradle convention — files under `src/test/java` are
        // tests, or any class whose name ends with `Test`/`Tests`.
        Language::Java => {
            if !lower.ends_with(".java") {
                return false;
            }
            stem.ends_with("Test")
                || stem.ends_with("Tests")
                || stem.ends_with("IT")
                || stem.ends_with("ITCase")
                || path.components().any(|c| c.as_os_str() == "test")
        }
        // Kotlin: same convention as Java.
        Language::Kotlin => {
            (lower.ends_with(".kt") || lower.ends_with(".kts"))
                && (stem.ends_with("Test")
                    || stem.ends_with("Tests")
                    || path.components().any(|c| c.as_os_str() == "test"))
        }
        // PHP: PHPUnit convention — class FooTest in FooTest.php.
        Language::Php => lower.ends_with(".php") && (stem.ends_with("Test") || stem.ends_with("Tests")),
        // Swift: XCTest convention — files named `*Tests.swift`.
        Language::Swift => {
            lower.ends_with(".swift")
                && (stem.ends_with("Tests") || stem.ends_with("Test") || stem.ends_with("Spec"))
        }
        // Ruby: Minitest `test_*.rb` / `*_test.rb`; RSpec `*_spec.rb`.
        Language::Ruby => {
            lower.ends_with(".rb")
                && (file_name.starts_with("test_")
                    || stem.ends_with("_test")
                    || stem.ends_with("_spec"))
        }
        // Go: convention is `*_test.go`.
        Language::Go => lower.ends_with("_test.go"),
        // Scala: Munit / ScalaTest convention — `*Suite.scala`/`*Spec.scala`/`*Test.scala`.
        Language::Scala => {
            lower.ends_with(".scala")
                && (stem.ends_with("Test")
                    || stem.ends_with("Tests")
                    || stem.ends_with("Spec")
                    || stem.ends_with("Suite"))
        }
        // Elixir: ExUnit convention — `*_test.exs`.
        Language::Elixir => {
            (lower.ends_with(".exs") || lower.ends_with(".ex"))
                && (stem.ends_with("_test") || file_name.starts_with("test_"))
        }
        // Lua / Luau: busted convention — `*_spec.lua`/`*_test.lua`.
        Language::Lua | Language::Luau => {
            (lower.ends_with(".lua") || lower.ends_with(".luau"))
                && (stem.ends_with("_spec")
                    || stem.ends_with("_test")
                    || file_name.starts_with("test_"))
        }
        // Rust: built-in `#[test]` framework — files under `tests/` are
        // integration tests, and any source file may contain `#[cfg(test)]`
        // mod blocks. Treat any `.rs` whose path contains `test` (a tests/
        // directory or a *_test.rs filename), `bench`, OR contains a
        // `#[test]` substring as a candidate;
        // matches_test_function then filters down to actual `#[test]` items.
        //
        // language-specific-bugs-v1 (P14.AGG14-9): the path-only filter
        // missed the canonical Rust convention of inline
        // `#[cfg(test)] mod tests { ... }` blocks inside a regular
        // `lib.rs` / module file (every cargo crate has these). The
        // additional substring check at recognise-time
        // (`source.contains("#[test]")`) is cheap relative to parsing and
        // turns single-file invocations like `tldr specs --from-tests
        // crates/globset/src/lib.rs` into yielding the inline tests they
        // contain. Directory walks accept any `.rs` here and still rely on
        // `matches_test_function` for per-fn filtering.
        Language::Rust => {
            lower.ends_with(".rs")
        }
        // C#: NUnit / xUnit / MSTest — files named `*Tests.cs` or under
        // a Tests directory. matches_test_function filters down to methods
        // carrying `[Test]` / `[Fact]` / `[TestMethod]` etc.
        Language::CSharp => {
            lower.ends_with(".cs")
                && (stem.ends_with("Test")
                    || stem.ends_with("Tests")
                    || path.components().any(|c| {
                        let s = c.as_os_str().to_string_lossy().to_ascii_lowercase();
                        s == "test" || s == "tests"
                    }))
        }
        // Languages without a single dominant convention. Fall back to the
        // weak heuristic of "filename contains 'test'" so directories laid
        // out as `tests/` still count their files. The function-count
        // walker still returns 0 for these — wiring grammar-specific
        // recognisers is left as TODO.
        Language::C | Language::Cpp | Language::Ocaml => {
            lower.contains("test") || lower.contains("spec")
        }
    }
}

/// AST-walk a parsed test file and count test functions per language convention.
fn count_test_functions(tree: &Tree, source: &[u8], language: Language) -> u32 {
    let root = tree.root_node();
    let mut count = 0u32;
    walk_count(&root, source, language, &mut count);
    count
}

fn walk_count(node: &Node, source: &[u8], language: Language, count: &mut u32) {
    if matches_test_function(node, source, language) {
        *count += 1;
        // Don't recurse into a function body — nested calls inside a
        // matched test function shouldn't be double-counted (e.g. an
        // `it(...)` inside a `describe(...)` block both match the JS
        // recogniser; only the leaf `it` counts).
        return;
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        walk_count(&child, source, language, count);
    }
}

/// Public wrapper around the per-language test-function predicate.
///
/// `tldr specs --from-tests` re-uses this from the generic spec extractor
/// so the same definition of "test function" used to count tests is used
/// to harvest assertions inside them.
pub fn is_test_function_node(node: &Node, source: &[u8], language: Language) -> bool {
    matches_test_function(node, source, language)
}

/// Per-language predicate: is this AST node a test function declaration?
fn matches_test_function(node: &Node, source: &[u8], language: Language) -> bool {
    match language {
        Language::Python => python_is_test_function(node, source),
        Language::JavaScript | Language::TypeScript => js_is_test_call(node, source),
        Language::Java | Language::Kotlin => jvm_has_test_annotation(node, source),
        Language::Php => php_is_test_method(node, source),
        Language::Swift => swift_is_test_method(node, source),
        Language::Ruby => ruby_is_test_def_or_block(node, source),
        Language::Go => go_is_top_level_test_function(node, source),
        Language::Scala => scala_is_test_call(node, source),
        Language::Elixir => elixir_is_test_macro(node, source),
        Language::Lua | Language::Luau => lua_is_test_call(node, source),
        Language::Rust => rust_is_test_function(node, source),
        Language::CSharp => csharp_has_test_attribute(node, source),
        Language::C | Language::Cpp | Language::Ocaml => false,
    }
}

// -- Rust: `#[test]` attribute precedes a `fn` item ---------------------------
//
// In tree-sitter-rust, `#[test]` is parsed as an `attribute_item` that is a
// SIBLING (preceding) of the `function_item`, not a child. So at every
// `function_item` we walk back to the previous siblings collecting any
// `attribute_item` nodes; if any contains an `attribute` whose head
// identifier is `test`, this is a unit test. We also accept aliases
// commonly used in async/integration setups: `tokio::test`, `async_std::test`,
// `rstest`, `proptest`, plus the common `test_case` macro.
fn rust_is_test_function(node: &Node, source: &[u8]) -> bool {
    if node.kind() != "function_item" {
        return false;
    }
    let mut prev = node.prev_sibling();
    while let Some(p) = prev {
        match p.kind() {
            "attribute_item" => {
                if rust_attribute_is_test(&p, source) {
                    return true;
                }
                prev = p.prev_sibling();
            }
            "line_comment" | "block_comment" => {
                prev = p.prev_sibling();
            }
            _ => break,
        }
    }
    false
}

fn rust_attribute_is_test(attr_item: &Node, source: &[u8]) -> bool {
    // attribute_item -> [#, [, attribute(...), ]]
    let mut cursor = attr_item.walk();
    for child in attr_item.children(&mut cursor) {
        if child.kind() == "attribute" {
            // attribute can be `test`, `tokio::test`, `test_case::test_case`,
            // etc. Walk and collect the tail identifier(s).
            let text = node_text(child, source);
            // Strip any argument list `(...)` and whitespace; take the path tail.
            let head = text
                .split(|c: char| c == '(' || c.is_whitespace())
                .next()
                .unwrap_or("");
            let tail = head.rsplit("::").next().unwrap_or("");
            if matches!(
                tail,
                "test" | "tokio_test" | "async_test" | "rstest" | "test_case"
            ) {
                return true;
            }
        }
    }
    false
}

// -- C#: methods with `[Test]` / `[Fact]` / `[TestMethod]` etc. --------------
//
// tree-sitter-c-sharp uses `method_declaration` whose direct children include
// one or more `attribute_list` nodes. Each `attribute_list` contains
// `attribute` children whose first identifier names the attribute (e.g.
// "Test", "Fact", "TestMethod", "TestCase", "Theory").
fn csharp_has_test_attribute(node: &Node, source: &[u8]) -> bool {
    if node.kind() != "method_declaration" {
        return false;
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "attribute_list" {
            let mut inner = child.walk();
            for attr in child.children(&mut inner) {
                if attr.kind() == "attribute" && csharp_attribute_is_test(&attr, source) {
                    return true;
                }
            }
        }
    }
    false
}

fn csharp_attribute_is_test(attribute: &Node, source: &[u8]) -> bool {
    // Read the tail identifier of the attribute name.
    let text = node_text(*attribute, source);
    let head = text
        .split(|c: char| c == '(' || c.is_whitespace())
        .next()
        .unwrap_or("");
    let tail = head.rsplit('.').next().unwrap_or("");
    matches!(
        tail,
        "Test"
            | "TestAttribute"
            | "Fact"
            | "FactAttribute"
            | "Theory"
            | "TheoryAttribute"
            | "TestMethod"
            | "TestMethodAttribute"
            | "TestCase"
            | "TestCaseAttribute"
            | "DataTestMethod"
            | "DataTestMethodAttribute"
    )
}

// -- Python: `def test_*` -----------------------------------------------------
fn python_is_test_function(node: &Node, source: &[u8]) -> bool {
    if node.kind() != "function_definition" {
        return false;
    }
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(n, source))
        .unwrap_or_default();
    name.starts_with("test_")
}

// -- JS/TS: `it(...)` / `test(...)` -------------------------------------------
fn js_is_test_call(node: &Node, source: &[u8]) -> bool {
    // tree-sitter-typescript / -javascript both expose `call_expression`
    // with a `function` child that's an identifier for top-level calls.
    if node.kind() != "call_expression" {
        return false;
    }
    let func_node = match node.child_by_field_name("function") {
        Some(n) => n,
        None => return false,
    };
    // We only want unqualified identifiers (`it("...")`, `test("...")`),
    // not member calls like `obj.it(...)` which are unrelated.
    if func_node.kind() != "identifier" {
        return false;
    }
    let name = node_text(func_node, source);
    matches!(name.as_str(), "it" | "test" | "fit" | "xit" | "xtest")
}

// -- Java/Kotlin: methods with @Test annotation -------------------------------
fn jvm_has_test_annotation(node: &Node, source: &[u8]) -> bool {
    // Java tree-sitter: `method_declaration` with a sibling `modifiers`
    // child containing `marker_annotation` / `annotation` whose name is
    // `Test`. Kotlin (kotlin-ng): `function_declaration` with a `modifiers`
    // child containing `annotation` -> `user_type` -> `type_identifier`
    // text "Test".
    let kind = node.kind();
    if kind != "method_declaration" && kind != "function_declaration" {
        return false;
    }

    // Walk this node's modifier subtree looking for an annotation whose
    // last identifier component is "Test". Spans both Java and Kotlin AST
    // shapes, since both use roughly the same node names.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "modifiers" {
            if subtree_contains_annotation_named(&child, source, "Test") {
                return true;
            }
        } else if child.kind() == "annotation" || child.kind() == "marker_annotation" {
            if annotation_has_name(&child, source, "Test") {
                return true;
            }
        }
    }
    false
}

fn subtree_contains_annotation_named(node: &Node, source: &[u8], target: &str) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        let kind = child.kind();
        if (kind == "annotation" || kind == "marker_annotation")
            && annotation_has_name(&child, source, target)
        {
            return true;
        }
        if subtree_contains_annotation_named(&child, source, target) {
            return true;
        }
    }
    false
}

/// True if `annotation_node` has its tail identifier equal to `target`
/// (e.g. `@Test`, `@org.junit.Test`, `@org.junit.jupiter.api.Test`).
fn annotation_has_name(annotation_node: &Node, source: &[u8], target: &str) -> bool {
    let text = node_text(*annotation_node, source);
    // Strip leading `@` and any argument list, then compare the tail
    // identifier (after the last `.`).
    let trimmed = text.trim_start_matches('@');
    let head = trimmed.split(|c: char| c == '(' || c.is_whitespace()).next().unwrap_or("");
    let last = head.rsplit('.').next().unwrap_or("");
    last == target
}

// -- PHP: PHPUnit `public function test*` -------------------------------------
fn php_is_test_method(node: &Node, source: &[u8]) -> bool {
    if node.kind() != "method_declaration" {
        return false;
    }
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(n, source))
        .unwrap_or_default();
    name.starts_with("test")
}

// -- Swift: `func test*()` ----------------------------------------------------
fn swift_is_test_method(node: &Node, source: &[u8]) -> bool {
    // tree-sitter-swift uses `function_declaration` (top-level) and
    // `protocol_function_declaration` (inside class body); we accept any
    // declaration whose `name` child starts with "test".
    let kind = node.kind();
    if !(kind == "function_declaration" || kind == "protocol_function_declaration") {
        return false;
    }
    // Swift grammar exposes the method name as the first `simple_identifier`
    // child after the `func` keyword. Walk children to find it.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "simple_identifier" {
            return node_text(child, source).starts_with("test");
        }
    }
    false
}

// -- Ruby: `def test_*` (Minitest) or `it/describe` blocks (RSpec) -----------
fn ruby_is_test_def_or_block(node: &Node, source: &[u8]) -> bool {
    match node.kind() {
        "method" => {
            // Minitest: `def test_<name>`.
            let name = node
                .child_by_field_name("name")
                .map(|n| node_text(n, source))
                .unwrap_or_default();
            name.starts_with("test_")
        }
        "call" => {
            // RSpec: `it "..." do ... end` / `specify "..." do ... end`.
            let method = node
                .child_by_field_name("method")
                .map(|n| node_text(n, source))
                .unwrap_or_default();
            matches!(method.as_str(), "it" | "specify")
        }
        _ => false,
    }
}

// -- Go: top-level `func TestXxx(t *testing.T)` -------------------------------
fn go_is_top_level_test_function(node: &Node, source: &[u8]) -> bool {
    if node.kind() != "function_declaration" {
        return false;
    }
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(n, source))
        .unwrap_or_default();
    if !name.starts_with("Test") {
        return false;
    }
    // Filter out `Test` exactly (no following uppercase). The Go testing
    // convention is `TestXxx` where `X` is upper.
    let after = name.strip_prefix("Test").unwrap_or("");
    let starts_upper = after.chars().next().map(|c| c.is_ascii_uppercase()).unwrap_or(false);
    starts_upper
}

// -- Scala: `test("...") { ... }` calls ---------------------------------------
fn scala_is_test_call(node: &Node, source: &[u8]) -> bool {
    // tree-sitter-scala uses `call_expression`; the function child is a
    // `simple_identifier`/`identifier` named "test". We also accept the
    // FunSuite naming convention where a class extends `FunSuite` and
    // calls `test(...)` at class scope. Pattern-matching just the call
    // shape is sufficient for the common case.
    if node.kind() != "call_expression" {
        return false;
    }
    let func_node = match node.child_by_field_name("function") {
        Some(n) => n,
        None => return false,
    };
    let name = node_text(func_node, source);
    matches!(name.as_str(), "test")
}

// -- Elixir: `test "..." do ... end` ------------------------------------------
fn elixir_is_test_macro(node: &Node, source: &[u8]) -> bool {
    // tree-sitter-elixir parses macros as `call` nodes; the head is the
    // `target` child (an `identifier`), and the body is a `do_block`.
    if node.kind() != "call" {
        return false;
    }
    let target = match node.child_by_field_name("target") {
        Some(n) => n,
        None => return false,
    };
    node_text(target, source) == "test"
}

// -- Lua/Luau: `it(...)` / `describe(...)` (busted) ---------------------------
fn lua_is_test_call(node: &Node, source: &[u8]) -> bool {
    // tree-sitter-lua / -luau represent calls as `function_call`. The
    // function name lives in the `name` field (an `identifier`).
    if node.kind() != "function_call" && node.kind() != "function_call_statement" {
        return false;
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "identifier" {
            return matches!(node_text(child, source).as_str(), "it" | "test");
        }
    }
    false
}

// -- Helpers ------------------------------------------------------------------
fn node_text(node: Node, source: &[u8]) -> String {
    let start = node.start_byte();
    let end = node.end_byte();
    if end <= source.len() {
        std::str::from_utf8(&source[start..end])
            .unwrap_or("")
            .to_string()
    } else {
        String::new()
    }
}

/// Detect language for a candidate test file. Returns `None` if the
/// extension isn't supported.
pub fn detect_language(path: &Path) -> Option<Language> {
    Language::from_path(path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn write(dir: &Path, name: &str, body: &str) -> std::path::PathBuf {
        let p = dir.join(name);
        if let Some(parent) = p.parent() {
            fs::create_dir_all(parent).ok();
        }
        fs::write(&p, body).unwrap();
        p
    }

    #[test]
    fn python_test_function_counted() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "test_x.py",
            "def test_one():\n    pass\n\ndef test_two():\n    pass\n",
        );
        let src = fs::read_to_string(&p).unwrap();
        let info = recognize(&p, &src, Language::Python);
        assert!(info.is_test_file);
        assert_eq!(info.test_function_count, 2);
    }

    #[test]
    fn javascript_describe_it_counted() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "foo.test.js",
            "describe('s', () => { it('a', () => {}); it('b', () => {}); });",
        );
        let src = fs::read_to_string(&p).unwrap();
        let info = recognize(&p, &src, Language::JavaScript);
        assert!(info.is_test_file);
        assert_eq!(info.test_function_count, 2);
    }

    #[test]
    fn java_test_annotation_counted() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "FooTest.java",
            "import org.junit.Test;\nclass FooTest {\n  @Test public void shouldFoo() {}\n  @Test public void shouldBar() {}\n}\n",
        );
        let src = fs::read_to_string(&p).unwrap();
        let info = recognize(&p, &src, Language::Java);
        assert!(info.is_test_file);
        assert_eq!(info.test_function_count, 2);
    }

    #[test]
    fn php_phpunit_counted() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "FooTest.php",
            "<?php\nclass FooTest {\n  public function testBar() {}\n  public function testBaz() {}\n}\n",
        );
        let src = fs::read_to_string(&p).unwrap();
        let info = recognize(&p, &src, Language::Php);
        assert!(info.is_test_file);
        assert_eq!(info.test_function_count, 2);
    }

    #[test]
    fn swift_xctest_counted() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "FooTests.swift",
            "import XCTest\nclass FooTests: XCTestCase {\n  func testBar() {}\n  func testBaz() {}\n}\n",
        );
        let src = fs::read_to_string(&p).unwrap();
        let info = recognize(&p, &src, Language::Swift);
        assert!(info.is_test_file);
        assert!(info.test_function_count >= 2);
    }

    #[test]
    fn go_testing_counted() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "foo_test.go",
            "package foo\nimport \"testing\"\nfunc TestFoo(t *testing.T) {}\nfunc TestBar(t *testing.T) {}\nfunc helper() {}\n",
        );
        let src = fs::read_to_string(&p).unwrap();
        let info = recognize(&p, &src, Language::Go);
        assert!(info.is_test_file);
        assert_eq!(info.test_function_count, 2);
    }

    #[test]
    fn ruby_minitest_counted() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "foo_test.rb",
            "class FooTest\n  def test_one; end\n  def test_two; end\nend\n",
        );
        let src = fs::read_to_string(&p).unwrap();
        let info = recognize(&p, &src, Language::Ruby);
        assert!(info.is_test_file);
        assert_eq!(info.test_function_count, 2);
    }
}