repotoire 0.8.2

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
//! Shared AST helpers for security detectors.
//!
//! Consolidates `unwrap_callee`, `collect_named_args`, `node_text`,
//! `receiver_chain_label`, `receiver_chain_label_go`, and
//! `receiver_chain_label_js` formerly duplicated across 5+ detectors.
//! Caught by `AIDuplicateBlockDetector` during repotoire dogfooding (see
//! `docs/plans/2026-05-08-security-detector-ast-architecture.md`).
//!
//! Layering: this module depends only on `tree_sitter`. It MUST NOT depend
//! on any other module in the crate to avoid circular imports.

use tree_sitter::Node;

/// Decode a node's source-text slice as UTF-8.
///
/// Returns `None` if the byte range is not valid UTF-8. The end byte is
/// clamped to `source.len()` to defend against tree-sitter overshoot on
/// truncated input.
///
/// Formerly duplicated 6 times across the security detectors.
pub(crate) fn node_text<'a>(node: Node<'_>, source: &'a [u8]) -> Option<&'a str> {
    let start = node.start_byte();
    let end = node.end_byte().min(source.len());
    std::str::from_utf8(&source[start..end]).ok()
}

/// Strip parenthesisation and JS comma-operator wrappers from a callee
/// expression, returning the innermost expression that should be matched
/// against the call shape.
///
/// Handles:
/// - `parenthesized_expression` → first named child
/// - `sequence_expression` → last named child (comma operator: result is
///   the rightmost expression)
///
/// Formerly duplicated 5 times across the security detectors with
/// identical bodies (only comments differed).
pub(crate) fn unwrap_callee(mut node: Node<'_>) -> Node<'_> {
    loop {
        match node.kind() {
            "parenthesized_expression" => {
                let mut next = None;
                for i in 0..node.named_child_count() {
                    if let Some(c) = node.named_child(i) {
                        next = Some(c);
                        break;
                    }
                }
                match next {
                    Some(n) => node = n,
                    None => return node,
                }
            }
            "sequence_expression" => {
                // Last named child wins (comma operator).
                let last = (0..node.named_child_count())
                    .rev()
                    .find_map(|i| node.named_child(i));
                match last {
                    Some(n) => node = n,
                    None => return node,
                }
            }
            _ => return node,
        }
    }
}

/// Collect the named children of an arguments / parameter-list node.
///
/// This is the standard "give me the actual argument expressions, not
/// commas/parens" walk used in every JS/TS/Python call-shape matcher in
/// the security layer.
///
/// Formerly duplicated 6 times (5 as `collect_named_args`, once as
/// `collect_call_args` in `cleartext_credentials.rs` — functionally
/// identical, unified under the more descriptive name).
pub(crate) fn collect_named_args<'a>(args: Node<'a>) -> Vec<Node<'a>> {
    let mut out = Vec::new();
    let mut cursor = args.walk();
    for child in args.children(&mut cursor) {
        if child.is_named() {
            out.push(child);
        }
    }
    out
}

/// Locate a Python `keyword_argument` by name and return its value node.
///
/// Handles the common case where security detectors need to inspect a
/// specific kwarg passed to a function call (e.g. `shell` in
/// `subprocess.run(...)`, `Loader` in `yaml.load(...)`,
/// `allow_pickle` in `numpy.load(...)`).
///
/// The input slice is expected to be the named children of an
/// `argument_list` node (typically obtained via [`collect_named_args`]).
/// Non-keyword positional arguments are ignored.
pub(crate) fn python_kwarg_value<'a>(
    args: &[Node<'a>],
    name: &str,
    source: &[u8],
) -> Option<Node<'a>> {
    for a in args {
        if a.kind() != "keyword_argument" {
            continue;
        }
        let arg_name = a
            .child_by_field_name("name")
            .and_then(|n| node_text(n, source));
        if arg_name == Some(name) {
            return a.child_by_field_name("value");
        }
    }
    None
}

/// Decide whether a Python boolean keyword argument is passed truthy.
///
/// Returns:
/// - `true` if the kwarg's value is the literal `True`.
/// - `false` if the kwarg's value is the literal `False`.
/// - `unknown_default` if the kwarg is present but the value is a
///   non-literal expression (variable, function call, attribute, ...).
///   Detectors choose this based on whether the unsafe path is the
///   conservative default for the call site (e.g. `shell=` and
///   `allow_pickle=` use `true`; `weights_only=` uses `false`).
/// - `false` if the kwarg is absent.
pub(crate) fn python_kwarg_truthy(
    args: &[Node<'_>],
    name: &str,
    source: &[u8],
    unknown_default: bool,
) -> bool {
    match python_kwarg_value(args, name, source) {
        Some(value) => match value.kind() {
            "true" => true,
            "false" => false,
            _ => unknown_default,
        },
        None => false,
    }
}

/// Compute the lower-cased "label" of a receiver expression in a method
/// chain — i.e. the last name in the chain (`a.b.c` → `"c"`,
/// `os.path.join` → `"join"`).
///
/// `call_resolver` is invoked when the receiver itself is a
/// `call_expression`; it lets the detector recognise patterns like
/// `require('child_process').exec` or `(await import('crypto')).randomBytes`
/// by mapping the call to a canonical module name. Pass `None` if the
/// detector does not need module-aware resolution.
///
/// Recognised receiver shapes:
/// - `member_expression` (JS/TS): take the `property` field.
/// - `attribute` (Python): take the `attribute` field.
/// - `selector_expression` (Go): take the `field` field.
/// - `member_access_expression` (C#): take the `name` field.
/// - `call_expression`: try `call_resolver`, otherwise fall back to text.
/// - `await_expression` / `parenthesized_expression`: descend into the
///   first named child.
/// - Anything else: lower-cased source text (covers bare identifiers,
///   `this`, `self`, `super`, etc.).
///
/// Formerly five separate impls with overlapping but divergent shape
/// support. The unified version is a strict superset of every prior
/// behavior. See the migration commit message for the per-detector
/// before/after.
pub(crate) fn receiver_chain_label(
    node: Node<'_>,
    source: &[u8],
    call_resolver: Option<&dyn Fn(Node<'_>, &[u8]) -> Option<&'static str>>,
) -> String {
    match node.kind() {
        // JS/TS `member_expression` and Python `attribute` are unified
        // here: try both field names so a grammar quirk in either
        // language doesn't silently fall through. (`cleartext_credentials`
        // historically did this defensive `or_else` chain.)
        "member_expression" | "attribute" => {
            if let Some(prop) = node
                .child_by_field_name("property")
                .or_else(|| node.child_by_field_name("attribute"))
            {
                if let Some(s) = node_text(prop, source) {
                    return s.to_lowercase();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        "selector_expression" => {
            if let Some(field) = node.child_by_field_name("field") {
                if let Some(s) = node_text(field, source) {
                    return s.to_lowercase();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        "member_access_expression" => {
            if let Some(name) = node.child_by_field_name("name") {
                if let Some(s) = node_text(name, source) {
                    return s.to_lowercase();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        "call_expression" => {
            if let Some(resolver) = call_resolver {
                if let Some(label) = resolver(node, source) {
                    return label.to_string();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        "await_expression" | "parenthesized_expression" => {
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    return receiver_chain_label(c, source, call_resolver);
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        _ => node_text(node, source).unwrap_or("").to_lowercase(),
    }
}

/// Go-specific receiver-chain label.
///
/// Tree-sitter-go represents method-chains as `selector_expression` with a
/// `field` child, so we don't need the broader JS/Python repertoire here.
/// Kept separate from the unified [`receiver_chain_label`] for clarity at
/// the callsite — `match_go_call` should never see a `member_expression`
/// or `attribute` node.
pub(crate) fn receiver_chain_label_go(node: Node<'_>, source: &[u8]) -> String {
    match node.kind() {
        "selector_expression" => {
            if let Some(field) = node.child_by_field_name("field") {
                if let Some(s) = node_text(field, source) {
                    return s.to_lowercase();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        _ => node_text(node, source).unwrap_or("").to_lowercase(),
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Python "library opt-out" structural pattern
//
// Used by the postprocess pass `demote_param_gated_security_branches`. A
// finding inside an if/elif/else branch whose condition references a
// parameter of the immediately enclosing function is the textbook shape of a
// library implementing a caller-controlled security parameter (HTTPX
// `verify=False`, `requests` `verify=False`, password hasher `legacy=True`,
// etc.). The actionable site is the call that passes the dangerous value;
// the implementation is doing what it was asked to do.
//
// These helpers are deliberately structural: no knowledge of TLS, crypto,
// subprocess, or any other domain. Every security detector benefits from
// them automatically.
// ─────────────────────────────────────────────────────────────────────────────

/// Find the deepest descendant of `root` whose 1-indexed source line range
/// contains `line`. Returns `None` if the line is out of range.
///
/// Tree-sitter rows are 0-indexed; we convert to the 1-indexed line numbers
/// findings carry. A node "contains" `line` when
/// `start_row + 1 <= line <= end_row + 1`.
pub(crate) fn node_at_line<'a>(root: Node<'a>, line: u32) -> Option<Node<'a>> {
    if line == 0 {
        return None;
    }
    let target_row = line - 1;
    let mut current = root;
    let in_range = |n: Node<'_>| {
        let s = n.start_position().row as u32;
        let e = n.end_position().row as u32;
        s <= target_row && target_row <= e
    };
    if !in_range(current) {
        return None;
    }
    // Descend into the deepest named child that still contains the target.
    loop {
        let mut descended = None;
        for i in 0..current.named_child_count() {
            if let Some(child) = current.named_child(i) {
                if in_range(child) {
                    descended = Some(child);
                    break;
                }
            }
        }
        match descended {
            Some(c) => current = c,
            None => return Some(current),
        }
    }
}

/// Tag for the kind of conditional clause a node lives inside.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ConditionalKind {
    /// `if` head — condition is the if_statement's `condition` field.
    If,
    /// `elif` clause — condition is the elif_clause's `condition` field.
    Elif,
    /// `else` clause — gated by the inverse of the parent if/elif chain's
    /// condition. We treat else branches as gated by the if's condition for
    /// the purposes of param-reference matching: if the if references a
    /// param, the else branch is implicitly param-gated too.
    Else,
}

/// Walk up from `node` to the nearest enclosing Python conditional clause.
///
/// Returns `(clause_node, kind)`. Stops at function/class/module boundaries
/// — a conditional in an outer function does NOT count for an inner
/// function's findings.
pub(crate) fn enclosing_python_conditional<'a>(
    node: Node<'a>,
) -> Option<(Node<'a>, ConditionalKind)> {
    let mut cur = node.parent()?;
    loop {
        match cur.kind() {
            "if_statement" => {
                // Distinguish the `if` head from a nested `elif`/`else` by
                // checking which child of the if_statement contains us.
                // Tree-sitter-python represents `elif` as `elif_clause` and
                // `else` as `else_clause`, both as children of the
                // if_statement. If we reached the if_statement directly
                // (not through one of those clauses), we're inside the
                // consequence of the if itself.
                return Some((cur, ConditionalKind::If));
            }
            "elif_clause" => return Some((cur, ConditionalKind::Elif)),
            "else_clause" => return Some((cur, ConditionalKind::Else)),
            // Stop at function/class/module — never escape outward.
            "function_definition" | "class_definition" | "module" | "lambda" => return None,
            _ => {}
        }
        cur = cur.parent()?;
    }
}

/// Walk up from `node` to the nearest enclosing `function_definition`.
/// Returns `None` if the node is at module level or only enclosed by a
/// class body.
pub(crate) fn enclosing_python_function<'a>(node: Node<'a>) -> Option<Node<'a>> {
    let mut cur = node.parent()?;
    loop {
        if cur.kind() == "function_definition" {
            return Some(cur);
        }
        cur = cur.parent()?;
    }
}

/// Collect parameter names from a Python `function_definition`.
///
/// Excludes `self` and `cls` so finding `if self.disabled: ...` does not
/// erroneously trip the predicate (those are instance attributes, not
/// caller-controlled inputs).
///
/// Recognised parameter shapes inside the `parameters` node:
/// - `identifier`            (`def f(x):`)
/// - `default_parameter`     (`def f(x=1):`)
/// - `typed_parameter`       (`def f(x: int):`)
/// - `typed_default_parameter` (`def f(x: int = 1):`)
/// - `list_splat_pattern`    (`def f(*args):`)
/// - `dictionary_splat_pattern` (`def f(**kwargs):`)
/// - `keyword_separator` / `positional_separator` are skipped (no name).
pub(crate) fn python_function_param_names(func: Node<'_>, source: &[u8]) -> Vec<String> {
    let mut names = Vec::new();
    let Some(params) = func.child_by_field_name("parameters") else {
        return names;
    };
    let mut cursor = params.walk();
    for child in params.children(&mut cursor) {
        if !child.is_named() {
            continue;
        }
        let name_node = match child.kind() {
            "identifier" => Some(child),
            "default_parameter"
            | "typed_parameter"
            | "typed_default_parameter"
            | "list_splat_pattern"
            | "dictionary_splat_pattern" => {
                // The first child is the parameter name (possibly itself
                // wrapped in `*` / `**` for splats).
                child.child_by_field_name("name").or_else(|| {
                    // typed_parameter has no "name" field — it's the
                    // first identifier child.
                    let mut c2 = child.walk();
                    let mut found = None;
                    for sub in child.children(&mut c2) {
                        if sub.kind() == "identifier" {
                            found = Some(sub);
                            break;
                        }
                    }
                    found
                })
            }
            _ => None,
        };
        if let Some(id) = name_node {
            if let Some(text) = node_text(id, source) {
                if text != "self" && text != "cls" {
                    names.push(text.to_string());
                }
            }
        }
    }
    names
}

/// Collect every bare-`identifier` name that appears in `expr`, recursively.
///
/// Used on a conditional's condition expression to gather every name the
/// condition mentions. The walker descends through all named children;
/// `attribute` access nodes (`x.y`) yield the receiver identifier `x` but
/// not the attribute name `y` (which isn't a referenceable parameter).
pub(crate) fn python_collect_name_idents(expr: Node<'_>, source: &[u8]) -> Vec<String> {
    let mut out = Vec::new();
    let mut stack = vec![expr];
    while let Some(n) = stack.pop() {
        match n.kind() {
            "identifier" => {
                if let Some(t) = node_text(n, source) {
                    out.push(t.to_string());
                }
            }
            // For `obj.attr.attr2` we want `obj` only — descend into the
            // `object` field and skip the `attribute` field.
            "attribute" => {
                if let Some(obj) = n.child_by_field_name("object") {
                    stack.push(obj);
                }
            }
            _ => {
                for i in 0..n.named_child_count() {
                    if let Some(c) = n.named_child(i) {
                        stack.push(c);
                    }
                }
            }
        }
    }
    out
}

/// Classify: is `node` inside a Python if/elif/else branch whose
/// enclosing conditional's condition references a parameter of the
/// immediately enclosing function? If so, return the matched parameter
/// name; otherwise return `None`.
///
/// This is the structural shape of "library implementing a caller-controlled
/// security parameter". See module-level doc for full motivation.
///
/// Returns `None` when:
/// - The node is not inside any conditional within a function.
/// - The enclosing conditional's condition references only globals,
///   function calls, or `self`/`cls` attributes (no parameter match).
/// - The enclosing function has no parameters (after excluding self/cls).
///
/// Else-branch handling: for an `else_clause` we walk to the parent
/// `if_statement` and use its condition. The else is gated by the inverse
/// of the if's condition; if the if's condition references a param, the
/// else branch is also param-gated by that same param.
///
/// Tied-name policy: if the condition references multiple parameters,
/// the first one (in `python_collect_name_idents` traversal order, which
/// is left-to-right source order) that matches a parameter name wins.
/// Ties are rare in practice and the choice is stable per parse tree.
///
/// History: this used to be a boolean predicate `is_python_param_gated_branch`.
/// Phase 2c's dual-branch promotion needs the *name* of the gating
/// parameter to populate `PredictionReasonKind::EnclosingScope { name }`,
/// so the function signature was widened. Callers that only want the
/// boolean answer write `.is_some()` at the call site — that's strictly
/// less surface than maintaining two API entry points.
pub(crate) fn python_param_gated_branch_param_name(
    node: Node<'_>,
    source: &[u8],
) -> Option<String> {
    let (clause, kind) = enclosing_python_conditional(node)?;
    let func = enclosing_python_function(clause)?;

    let condition_node = match kind {
        ConditionalKind::If | ConditionalKind::Elif => clause.child_by_field_name("condition")?,
        ConditionalKind::Else => {
            // Walk up to the parent if_statement and use its condition.
            // (else_clause's parent is the if_statement.)
            let parent = clause.parent()?;
            if parent.kind() != "if_statement" {
                return None;
            }
            parent.child_by_field_name("condition")?
        }
    };

    let params = python_function_param_names(func, source);
    if params.is_empty() {
        return None;
    }
    let names = python_collect_name_idents(condition_node, source);
    names.into_iter().find(|n| params.iter().any(|p| p == n))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tree_sitter::Parser;

    fn parse_js(src: &str) -> tree_sitter::Tree {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_javascript::LANGUAGE.into())
            .expect("load js grammar");
        parser.parse(src, None).expect("parse")
    }

    fn parse_ts(src: &str) -> tree_sitter::Tree {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into())
            .expect("load ts grammar");
        parser.parse(src, None).expect("parse")
    }

    fn parse_python(src: &str) -> tree_sitter::Tree {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_python::LANGUAGE.into())
            .expect("load python grammar");
        parser.parse(src, None).expect("parse")
    }

    fn parse_go(src: &str) -> tree_sitter::Tree {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_go::LANGUAGE.into())
            .expect("load go grammar");
        parser.parse(src, None).expect("parse")
    }

    /// Walk the tree and return the first node whose `kind()` matches.
    fn find_kind<'a>(root: Node<'a>, kind: &str) -> Option<Node<'a>> {
        let mut stack = vec![root];
        while let Some(n) = stack.pop() {
            if n.kind() == kind {
                return Some(n);
            }
            for i in (0..n.child_count()).rev() {
                if let Some(c) = n.child(i) {
                    stack.push(c);
                }
            }
        }
        None
    }

    // ----- unwrap_callee -----

    #[test]
    fn unwrap_callee_parenthesized() {
        // `(eval)("alert(1)")` — the call expression's `function` field is a
        // parenthesized_expression wrapping `eval`.
        let src = "(eval)('x');\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let func = call.child_by_field_name("function").expect("func");
        assert_eq!(func.kind(), "parenthesized_expression");
        let unwrapped = unwrap_callee(func);
        assert_eq!(unwrapped.kind(), "identifier");
        assert_eq!(node_text(unwrapped, src.as_bytes()), Some("eval"));
    }

    #[test]
    fn unwrap_callee_ts_passthrough() {
        // TS `as_expression` is NOT handled here (out of scope of the
        // current consolidated behavior — none of the prior copies handled
        // it either). This test pins that contract: `as` casts pass
        // through unchanged.
        let src = "(x as Foo)();\n";
        let tree = parse_ts(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let func = call.child_by_field_name("function").expect("func");
        // The outer wrap is a parenthesized_expression around `x as Foo`.
        let unwrapped = unwrap_callee(func);
        // Should descend through the parens to the as_expression.
        assert_eq!(unwrapped.kind(), "as_expression");
    }

    #[test]
    fn unwrap_callee_plain_identifier() {
        let src = "eval('x');\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let func = call.child_by_field_name("function").expect("func");
        let unwrapped = unwrap_callee(func);
        assert_eq!(unwrapped.kind(), "identifier");
        assert_eq!(unwrapped.id(), func.id());
    }

    // ----- collect_named_args -----

    #[test]
    fn collect_named_args_positional_only() {
        let src = "f(1, 2, 3);\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let args = call.child_by_field_name("arguments").expect("args");
        let collected = collect_named_args(args);
        assert_eq!(collected.len(), 3);
        assert!(collected.iter().all(|n| n.kind() == "number"));
    }

    #[test]
    fn collect_named_args_python_keyword() {
        // Python lets us mix kwargs; both kinds are named children of the
        // argument_list.
        let src = "f(name='x')\n";
        let tree = parse_python(src);
        let call = find_kind(tree.root_node(), "call").expect("call");
        let args = call.child_by_field_name("arguments").expect("args");
        let collected = collect_named_args(args);
        assert_eq!(collected.len(), 1);
        assert_eq!(collected[0].kind(), "keyword_argument");
    }

    #[test]
    fn collect_named_args_mixed() {
        let src = "f(1, 'two', x);\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let args = call.child_by_field_name("arguments").expect("args");
        let collected = collect_named_args(args);
        assert_eq!(collected.len(), 3);
        // commas are unnamed and must be filtered out.
        assert!(!collected.iter().any(|n| n.kind() == ","));
    }

    // ----- python_kwarg_value / python_kwarg_truthy -----

    fn collect_py_call_args<'a>(tree: &'a tree_sitter::Tree) -> Vec<Node<'a>> {
        let call = find_kind(tree.root_node(), "call").expect("call");
        let args = call.child_by_field_name("arguments").expect("args");
        collect_named_args(args)
    }

    #[test]
    fn python_kwarg_value_locates_named_arg() {
        let src = "f(shell=True, timeout=30)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        let v = python_kwarg_value(&args, "shell", src.as_bytes()).expect("shell value");
        assert_eq!(v.kind(), "true");
        let v2 = python_kwarg_value(&args, "timeout", src.as_bytes()).expect("timeout value");
        assert_eq!(v2.kind(), "integer");
    }

    #[test]
    fn python_kwarg_value_returns_none_for_absent() {
        let src = "f(shell=True)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(python_kwarg_value(&args, "missing", src.as_bytes()).is_none());
    }

    #[test]
    fn python_kwarg_value_skips_positional_args() {
        // Positional args are not keyword_arguments; the helper must not
        // misidentify them.
        let src = "f(\"shell\", x)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(python_kwarg_value(&args, "shell", src.as_bytes()).is_none());
    }

    #[test]
    fn python_kwarg_truthy_literal_true() {
        let src = "f(shell=True)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(python_kwarg_truthy(&args, "shell", src.as_bytes(), false));
        assert!(python_kwarg_truthy(&args, "shell", src.as_bytes(), true));
    }

    #[test]
    fn python_kwarg_truthy_literal_false() {
        let src = "f(shell=False)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        // Literal False overrides unknown_default in either direction.
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), false));
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), true));
    }

    #[test]
    fn python_kwarg_truthy_non_literal_uses_default() {
        let src = "f(shell=some_var)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(python_kwarg_truthy(&args, "shell", src.as_bytes(), true));
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), false));
    }

    #[test]
    fn python_kwarg_truthy_absent_is_false() {
        // Absent kwarg always returns false regardless of unknown_default —
        // the default semantic only kicks in when the kwarg is *present*
        // but its value is non-literal.
        let src = "f(timeout=5)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), true));
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), false));
    }

    // ----- receiver_chain_label -----

    #[test]
    fn receiver_chain_label_simple_identifier() {
        // For a bare identifier, the label is just its lowercased text.
        let src = "x;\n";
        let tree = parse_js(src);
        let id = find_kind(tree.root_node(), "identifier").expect("id");
        assert_eq!(receiver_chain_label(id, src.as_bytes(), None), "x");
    }

    #[test]
    fn receiver_chain_label_member_chain() {
        // `a.b.c` — the outer member_expression's property is `c`.
        let src = "a.b.c;\n";
        let tree = parse_js(src);
        let mem = find_kind(tree.root_node(), "member_expression").expect("mem");
        // `find_kind` returns the first match found via the LIFO stack walk;
        // for `a.b.c`, that's the outermost expression with property `c`.
        let label = receiver_chain_label(mem, src.as_bytes(), None);
        assert_eq!(label, "c");
    }

    #[test]
    fn receiver_chain_label_python_attribute() {
        let src = "os.path.join\n";
        let tree = parse_python(src);
        let attr = find_kind(tree.root_node(), "attribute").expect("attr");
        let label = receiver_chain_label(attr, src.as_bytes(), None);
        assert_eq!(label, "join");
    }

    #[test]
    fn receiver_chain_label_call_with_resolver() {
        // `require('fs').readFile` — when the resolver matches the
        // `require('fs')` call_expression, it returns `"fs"` and that
        // wins over the raw text.
        let src = "require('fs');\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let resolver = |n: Node<'_>, _src: &[u8]| -> Option<&'static str> {
            if n.kind() == "call_expression" {
                Some("fs")
            } else {
                None
            }
        };
        let label = receiver_chain_label(call, src.as_bytes(), Some(&resolver));
        assert_eq!(label, "fs");
        // Without the resolver, the raw call text falls through.
        let label_noresolve = receiver_chain_label(call, src.as_bytes(), None);
        assert_eq!(label_noresolve, "require('fs')");
    }

    // ----- receiver_chain_label_go -----

    #[test]
    fn receiver_chain_label_go_selector() {
        let src = "package m\nfunc f() { exec.Command(\"ls\") }\n";
        let tree = parse_go(src);
        let sel = find_kind(tree.root_node(), "selector_expression").expect("sel");
        let label = receiver_chain_label_go(sel, src.as_bytes());
        assert_eq!(label, "command");
    }

    // ─── python_param_gated_branch_param_name and friends ────────────────

    /// Return the deepest node containing `line` (1-indexed) — convenience
    /// wrapper around the public `node_at_line` so each test can target a
    /// specific source line.
    fn node_for_line<'a>(tree: &'a tree_sitter::Tree, line: u32) -> Node<'a> {
        node_at_line(tree.root_node(), line).expect("node for line")
    }

    #[test]
    fn param_gated_module_level_returns_false() {
        // Module-level if has no enclosing function — not a "library
        // opt-out implementation", just a top-level guard.
        let src = "if condition:\n    x = ssl.CERT_NONE\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 2);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_none());
    }

    #[test]
    fn param_gated_if_body_with_matching_param_returns_true() {
        let src = "def f(verify):\n    if verify is False:\n        x = 1\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 3);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_some());
    }

    #[test]
    fn param_gated_global_in_condition_returns_false() {
        // Condition references `is_production()` — not a function param.
        let src = "def f(x):\n    if is_production():\n        ctx.verify_mode = ssl.CERT_NONE\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 3);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_none());
    }

    #[test]
    fn param_gated_any_param_match_is_enough() {
        // Function has multiple params; condition only references one.
        // Any match in the param set qualifies the branch.
        let src = "def f(a, verify, c):\n    if verify:\n        x = 1\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 3);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_some());
    }

    #[test]
    fn param_gated_walks_to_nearest_function() {
        // Inner function's params are what matter; outer function's `verify`
        // does NOT make the inner function's branch param-gated.
        let src =
            "def outer(verify):\n    def inner(other):\n        if verify:\n            x = 1\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 4);
        // Inner function's params = [other]; condition refs `verify` which
        // is NOT in inner's params. Should be false.
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_none());
    }

    #[test]
    fn param_gated_kwargs_count_as_param() {
        let src = "def f(**kwargs):\n    if kwargs.get('insecure'):\n        x = 1\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 3);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_some());
    }

    #[test]
    fn param_gated_self_does_not_count() {
        // `self.disabled` is not a caller-controlled parameter — even though
        // `self` appears in the parameter list, our predicate explicitly
        // excludes it.
        let src = "class C:\n    def m(self):\n        if self.disabled:\n            x = 1\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 4);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_none());
    }

    #[test]
    fn param_gated_cls_does_not_count() {
        let src = "class C:\n    @classmethod\n    def m(cls):\n        if cls.disabled:\n            x = 1\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 5);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_none());
    }

    #[test]
    fn param_gated_else_branch_inherits_if_param_gate() {
        // The else is gated by the inverse of `verify` — still
        // param-controlled.
        let src =
            "def f(verify):\n    if verify:\n        a = 1\n    else:\n        b = ssl.CERT_NONE\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 5);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_some());
    }

    #[test]
    fn param_gated_elif_branch_with_param_match() {
        // The HTTPX exact shape: `elif verify is False:` inside a function.
        let src = "def f(verify):\n    if verify is True:\n        a = 1\n    elif verify is False:\n        ctx.verify_mode = ssl.CERT_NONE\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 5);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_some());
    }

    #[test]
    fn param_gated_typed_default_param() {
        // `def f(verify: bool = True): ...`
        let src = "def f(verify: bool = True):\n    if verify:\n        a = 1\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 3);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_some());
    }

    #[test]
    fn param_gated_function_with_no_useful_params() {
        // Only `self`; no caller-controlled params.
        let src = "class C:\n    def m(self):\n        if some_global:\n            x = 1\n";
        let tree = parse_python(src);
        let node = node_for_line(&tree, 4);
        assert!(python_param_gated_branch_param_name(node, src.as_bytes()).is_none());
    }

    #[test]
    fn node_at_line_returns_none_for_out_of_range() {
        let src = "x = 1\n";
        let tree = parse_python(src);
        assert!(node_at_line(tree.root_node(), 999).is_none());
        assert!(node_at_line(tree.root_node(), 0).is_none());
    }

    #[test]
    fn node_at_line_finds_deepest_node() {
        let src = "def f():\n    x = ssl.CERT_NONE\n";
        let tree = parse_python(src);
        // Line 2 should resolve to a node inside the assignment, not the
        // function_definition.
        let n = node_at_line(tree.root_node(), 2).expect("node");
        // The deepest named node containing line 2 should be a leaf-ish
        // identifier or attribute, definitely not "function_definition".
        assert_ne!(n.kind(), "function_definition");
        assert_ne!(n.kind(), "module");
    }
}