Skip to main content

rinne_graph/
branches.rs

1//! Tree-sitter extraction of branch/guard conditions — the conditionals that
2//! encode a codebase's real rules (eligibility gates, thresholds, fallbacks).
3
4use tree_sitter::Parser;
5
6use crate::lang::support_for;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum BranchKind {
10    If,
11    Match,
12    Guard,
13    ErrorPath,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Branch {
18    pub line: u32,
19    pub condition: String,
20    pub kind: BranchKind,
21}
22
23/// Extract branch/guard conditions from `source`. Returns empty when the
24/// language is unsupported or the source doesn't parse.
25pub fn extract_branches(lang: &str, source: &str) -> Vec<Branch> {
26    let Some(support) = support_for(lang) else {
27        return Vec::new();
28    };
29    let mut parser = Parser::new();
30    if parser.set_language(&support.language()).is_err() {
31        return Vec::new();
32    }
33    let Some(tree) = parser.parse(source, None) else {
34        return Vec::new();
35    };
36    let bytes = source.as_bytes();
37    let mut out: Vec<Branch> = Vec::new();
38    let mut stack = vec![tree.root_node()];
39    while let Some(node) = stack.pop() {
40        // Condition-bearing node kinds across rust / python / ts-js.
41        let kind = match node.kind() {
42            "if_expression" | "match_expression" | "while_expression" | "if_statement"
43            | "while_statement" | "match_statement" | "switch_statement" | "ternary_expression" => {
44                Some(node.kind())
45            }
46            _ => None,
47        };
48        if let Some(k) = kind {
49            // The condition child: rust/py/ts `condition`; match/switch use
50            // the discriminee (`value`/`subject`). Try named fields in order.
51            let cond_node = node
52                .child_by_field_name("condition")
53                .or_else(|| node.child_by_field_name("value"))
54                .or_else(|| node.child_by_field_name("subject"));
55            if let Some(cn) = cond_node {
56                let text = cn.utf8_text(bytes).unwrap_or("").trim();
57                // Collapse to a single line so the render stays scannable.
58                let condition: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
59                if !condition.is_empty() {
60                    let branch_kind = if k.contains("match") || k.contains("switch") {
61                        BranchKind::Match
62                    } else {
63                        BranchKind::If
64                    };
65                    out.push(Branch {
66                        line: cn.start_position().row as u32 + 1,
67                        condition,
68                        kind: branch_kind,
69                    });
70                }
71            }
72        }
73        // Error-path heuristic (deterministic): a Rust `?` is a real fallback rule.
74        // Cheap to detect by node kind.
75        if node.kind() == "try_expression" {
76            out.push(Branch {
77                line: node.start_position().row as u32 + 1,
78                condition: node
79                    .utf8_text(bytes)
80                    .unwrap_or("?")
81                    .trim()
82                    .chars()
83                    .take(60)
84                    .collect(),
85                kind: BranchKind::ErrorPath,
86            });
87        }
88        let mut cursor = node.walk();
89        for child in node.children(&mut cursor) {
90            stack.push(child);
91        }
92    }
93    // Stable order by line; dedup identical (line, condition).
94    out.sort_by(|a, b| {
95        a.line
96            .cmp(&b.line)
97            .then_with(|| a.condition.cmp(&b.condition))
98    });
99    out.dedup_by(|a, b| a.line == b.line && a.condition == b.condition);
100    out
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn extracts_rust_if_condition() {
109        let src = "fn f(tier: &str, seats: u32) {\n    if tier == \"enterprise\" && seats > 50 {\n        gate();\n    }\n}\n";
110        let branches = extract_branches("rust", src);
111        assert!(
112            branches.iter().any(|b| b.kind == BranchKind::If
113                && b.condition.contains("enterprise")
114                && b.condition.contains("seats > 50")),
115            "if condition captured verbatim: {branches:?}"
116        );
117    }
118
119    #[test]
120    fn extracts_python_if_condition() {
121        let src = "def f(x):\n    if x > 10:\n        return True\n";
122        let branches = extract_branches("python", src);
123        assert!(
124            branches
125                .iter()
126                .any(|b| b.kind == BranchKind::If && b.condition.contains("x > 10")),
127            "python if captured: {branches:?}"
128        );
129    }
130
131    #[test]
132    fn unsupported_lang_is_empty() {
133        assert!(extract_branches("cobol", "IF X GREATER 1").is_empty());
134    }
135}