Skip to main content

bindings_generat/interactive/
clarification.rs

1use anyhow::Result;
2use dialoguer::{Confirm, Select};
3use tracing::info;
4
5use crate::analyzer::raii::{LifecyclePair, RaiiPatterns};
6
7/// Threshold for low-confidence lifecycle pairs that need confirmation
8const LOW_CONFIDENCE_THRESHOLD: f32 = 0.7;
9
10/// Interactive clarification results
11#[derive(Debug, Clone)]
12pub struct ClarificationResults {
13    pub confirmed_pairs: Vec<LifecyclePair>,
14    pub rejected_pairs: Vec<String>, // Pairs rejected by user (by create_fn name)
15}
16
17impl Default for ClarificationResults {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22
23impl ClarificationResults {
24    pub fn new() -> Self {
25        Self {
26            confirmed_pairs: Vec::new(),
27            rejected_pairs: Vec::new(),
28        }
29    }
30}
31
32/// Request user confirmation for ambiguous RAII patterns
33pub fn clarify_patterns(patterns: &RaiiPatterns) -> Result<ClarificationResults> {
34    let mut results = ClarificationResults::new();
35
36    // Find low-confidence pairs that need confirmation
37    let low_confidence_pairs: Vec<_> = patterns
38        .lifecycle_pairs
39        .iter()
40        .filter(|pair| pair.confidence < LOW_CONFIDENCE_THRESHOLD)
41        .collect();
42
43    if low_confidence_pairs.is_empty() {
44        info!("All lifecycle pairs have high confidence, no clarification needed");
45        results.confirmed_pairs = patterns.lifecycle_pairs.clone();
46        return Ok(results);
47    }
48
49    println!("\n⚠️  Some lifecycle pairs need confirmation:");
50    println!();
51
52    for pair in low_confidence_pairs {
53        let should_confirm = Confirm::new()
54            .with_prompt(format!(
55                "Is '{}' paired with '{}' for handle '{}'? (confidence: {:.0}%)",
56                pair.create_fn,
57                pair.destroy_fn,
58                pair.handle_type,
59                pair.confidence * 100.0
60            ))
61            .default(pair.confidence > 0.5)
62            .interact()?;
63
64        if should_confirm {
65            results.confirmed_pairs.push(pair.clone());
66        } else {
67            results.rejected_pairs.push(pair.create_fn.clone());
68        }
69    }
70
71    // Add all high-confidence pairs automatically
72    for pair in &patterns.lifecycle_pairs {
73        if pair.confidence >= LOW_CONFIDENCE_THRESHOLD {
74            results.confirmed_pairs.push(pair.clone());
75        }
76    }
77
78    println!();
79    Ok(results)
80}
81
82/// Ask user to select from multiple possible destroy functions for a create function
83pub fn select_destroy_function(
84    create_fn: &str,
85    candidates: &[String],
86    handle_type: &str,
87) -> Result<Option<String>> {
88    if candidates.is_empty() {
89        return Ok(None);
90    }
91
92    if candidates.len() == 1 {
93        return Ok(Some(candidates[0].clone()));
94    }
95
96    println!();
97    let selection = Select::new()
98        .with_prompt(format!(
99            "Multiple possible destroy functions for '{}' (handle: '{}'). Which is correct?",
100            create_fn, handle_type
101        ))
102        .items(candidates)
103        .default(0)
104        .interact_opt()?;
105
106    Ok(selection.map(|idx| candidates[idx].clone()))
107}
108
109/// Ask user to confirm which functions are truly create/destroy pairs
110pub fn select_lifecycle_pairs(
111    handle_type: &str,
112    create_candidates: &[String],
113    destroy_candidates: &[String],
114) -> Result<Vec<(String, String)>> {
115    println!();
116    println!(
117        "🔍 Ambiguous lifecycle functions detected for handle '{}'",
118        handle_type
119    );
120    println!();
121
122    if create_candidates.is_empty() || destroy_candidates.is_empty() {
123        return Ok(Vec::new());
124    }
125
126    let mut pairs = Vec::new();
127
128    // For each create function, ask which destroy function it pairs with
129    for create_fn in create_candidates {
130        let options: Vec<String> = destroy_candidates
131            .iter()
132            .map(|d| d.to_string())
133            .chain(std::iter::once("(None - skip this function)".to_string()))
134            .collect();
135
136        let selection = Select::new()
137            .with_prompt(format!(
138                "Which function destroys resources created by '{}'?",
139                create_fn
140            ))
141            .items(&options)
142            .default(0)
143            .interact()?;
144
145        if selection < destroy_candidates.len() {
146            pairs.push((create_fn.clone(), destroy_candidates[selection].clone()));
147        }
148    }
149
150    Ok(pairs)
151}
152
153/// Check if user wants to manually add a lifecycle pair not detected automatically
154pub fn prompt_manual_pair() -> Result<Option<(String, String, String)>> {
155    println!();
156    let add_manual = Confirm::new()
157        .with_prompt("Would you like to manually specify a lifecycle pair that wasn't detected?")
158        .default(false)
159        .interact()?;
160
161    if !add_manual {
162        return Ok(None);
163    }
164
165    let handle_type: String = dialoguer::Input::new()
166        .with_prompt("Handle type name (e.g., 'MyHandle')")
167        .interact_text()?;
168
169    let create_fn: String = dialoguer::Input::new()
170        .with_prompt("Create function name")
171        .interact_text()?;
172
173    let destroy_fn: String = dialoguer::Input::new()
174        .with_prompt("Destroy function name")
175        .interact_text()?;
176
177    Ok(Some((handle_type, create_fn, destroy_fn)))
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn test_clarification_results_creation() {
186        let results = ClarificationResults::new();
187        assert!(results.confirmed_pairs.is_empty());
188        assert!(results.rejected_pairs.is_empty());
189    }
190
191    const _: () = {
192        assert!(LOW_CONFIDENCE_THRESHOLD > 0.0);
193        assert!(LOW_CONFIDENCE_THRESHOLD <= 1.0);
194    };
195}