Skip to main content

bindings_generat/
lib.rs

1pub mod analyzer;
2pub mod cli;
3pub mod config;
4pub mod discovery;
5pub mod ffi;
6pub mod generator;
7pub mod interactive;
8pub mod llm;
9pub mod output;
10pub mod sources;
11pub mod utils;
12
13pub use cli::Cli;
14pub use config::Config;
15
16use anyhow::Result;
17use indicatif::{ProgressBar, ProgressStyle};
18use tracing::info;
19
20/// Main orchestrator for the bindings generation process
21pub struct BindingsGenerator {
22    config: Config,
23    // Store intermediate results
24    ffi_info: Option<ffi::FfiInfo>,
25    analysis: Option<analyzer::AnalysisResult>,
26    generated_code: Option<generator::GeneratedCode>,
27    // LLM enhancements
28    llm_enhancements: Option<llm::CodeEnhancements>,
29    // Ollama installation state
30    ollama_installer: Option<llm::OllamaInstaller>,
31    ollama_process: Option<std::process::Child>,
32}
33
34impl BindingsGenerator {
35    pub fn new(config: Config) -> Self {
36        Self {
37            config,
38            ffi_info: None,
39            analysis: None,
40            generated_code: None,
41            llm_enhancements: None,
42            ollama_installer: None,
43            ollama_process: None,
44        }
45    }
46
47    pub fn run(&mut self) -> Result<()> {
48        println!(
49            "šŸ”§ bindings-generat v{} - Automatic FFI Wrapper Generator\n",
50            env!("CARGO_PKG_VERSION")
51        );
52
53        // Phase 0: Ollama Setup (if LLM is enabled)
54        if self.config.use_llm {
55            self.phase_ollama_setup()?;
56        }
57
58        // Phase 1: Discovery
59        let (headers, lib_name, source_path) = self.phase_discovery()?;
60
61        // Phase 2: FFI Generation
62        self.phase_ffi_generation(&headers, &lib_name, &source_path)?;
63
64        // Phase 3: Pattern Analysis
65        self.phase_pattern_analysis()?;
66
67        // Phase 4: Code Generation
68        self.phase_code_generation(&lib_name)?;
69
70        // Phase 5: LLM Enhancement (optional)
71        if self.config.use_llm {
72            self.phase_llm_enhancement()?;
73        }
74
75        // Phase 6: Interactive Clarification (optional)
76        if self.config.interactive {
77            self.phase_interactive()?;
78        }
79
80        // Phase 7: Output Generation
81        self.phase_output(&lib_name)?;
82
83        // Phase 8: Validation
84        self.phase_validation()?;
85
86        // Phase 9: Cleanup (if we installed Ollama portably)
87        self.phase_cleanup()?;
88
89        println!("\nšŸŽ‰ Done! Your safe Rust wrapper is ready.");
90        println!("   Location: {}", self.config.output_path.display());
91        println!("\nNext steps:");
92        println!("   cd {}", self.config.output_path.display());
93        println!("   cargo doc --open");
94
95        Ok(())
96    }
97
98    fn phase_discovery(&self) -> Result<(Vec<std::path::PathBuf>, String, std::path::PathBuf)> {
99        let pb = Self::create_progress_bar("Phase 1: Preparing source...");
100
101        info!("Starting source preparation phase");
102
103        // Prepare source (download/extract if needed)
104        let prepared_source = sources::prepare_source(&self.config.source)?;
105        pb.println(format!(
106            "   āœ“ Source prepared: {}",
107            prepared_source.path().display()
108        ));
109
110        // Now discover the library structure
111        pb.set_message("Phase 1: Discovering library...".to_string());
112
113        let discovery_result = discovery::discover(&prepared_source.path().to_path_buf())?;
114        pb.println(format!(
115            "   āœ“ Found {} header files",
116            discovery_result.headers.len()
117        ));
118
119        let lib_name = if let Some(name) = &self.config.lib_name {
120            name.clone()
121        } else {
122            discovery_result.library_name.clone()
123        };
124        pb.println(format!("   āœ“ Detected library: {}", lib_name));
125
126        pb.finish_and_clear();
127        Ok((
128            discovery_result.headers,
129            lib_name,
130            prepared_source.path().to_path_buf(),
131        ))
132    }
133
134    fn phase_ffi_generation(
135        &mut self,
136        headers: &[std::path::PathBuf],
137        lib_name: &str,
138        source_path: &std::path::Path,
139    ) -> Result<()> {
140        let pb = Self::create_progress_bar("Phase 2: Running bindgen...");
141
142        info!("Starting FFI generation phase");
143
144        let ffi_info = ffi::generate_and_parse_ffi(headers, lib_name, source_path)?;
145        pb.println(format!(
146            "   āœ“ Generated FFI bindings ({} functions, {} types)",
147            ffi_info.functions.len(),
148            ffi_info.types.len()
149        ));
150
151        self.ffi_info = Some(ffi_info);
152
153        pb.finish_and_clear();
154        Ok(())
155    }
156
157    fn phase_pattern_analysis(&mut self) -> Result<()> {
158        let pb = Self::create_progress_bar("Phase 3: Analyzing patterns...");
159
160        info!("Starting pattern analysis phase");
161
162        let ffi_info = self.ffi_info.as_ref().expect("FFI info not generated");
163        let analysis = analyzer::analyze_ffi(ffi_info)?;
164
165        pb.println(format!(
166            "   āœ“ Found {} handle types",
167            analysis.raii_patterns.handle_types.len()
168        ));
169        pb.println(format!(
170            "   āœ“ Detected {} lifecycle pairs",
171            analysis.raii_patterns.lifecycle_pairs.len()
172        ));
173
174        self.analysis = Some(analysis);
175
176        pb.finish_and_clear();
177        Ok(())
178    }
179
180    fn phase_code_generation(&mut self, lib_name: &str) -> Result<()> {
181        let pb = Self::create_progress_bar("Phase 4: Generating safe wrappers...");
182
183        info!("Starting code generation phase");
184
185        let ffi_info = self.ffi_info.as_ref().expect("FFI info not generated");
186        let analysis = self.analysis.as_ref().expect("Analysis not performed");
187
188        let generated =
189            generator::generate_code(ffi_info, analysis, lib_name, self.llm_enhancements.as_ref())?;
190
191        pb.println("   āœ“ Created RAII wrapper types");
192        pb.println("   āœ“ Converted status codes to Error");
193
194        self.generated_code = Some(generated);
195
196        pb.finish_and_clear();
197        Ok(())
198    }
199
200    fn phase_llm_enhancement(&mut self) -> Result<()> {
201        if !self.config.use_llm {
202            info!("LLM enhancement disabled via config");
203            return Ok(());
204        }
205
206        let pb = Self::create_progress_bar("Phase 5: Enhancing with LLM...");
207
208        info!("Starting LLM enhancement phase");
209
210        // Check if Ollama is available
211        if !llm::is_ollama_available() {
212            pb.println("   ⚠ Ollama not detected, skipping LLM enhancement");
213            pb.println("      Install Ollama from https://ollama.ai to enable this feature");
214            pb.finish_and_clear();
215            return Ok(());
216        }
217
218        // Create enhancement storage
219        let mut enhancements = llm::CodeEnhancements::new();
220
221        // Create documentation enhancer (with custom URL if portable install)
222        let enhancer = if let Some(ref installer) = self.ollama_installer {
223            let base_url = installer.ollama_host();
224            match llm::docs::DocsEnhancer::with_base_url(
225                self.config.llm_model.clone(),
226                &base_url,
227                Some(self.config.cache_dir.clone()),
228            ) {
229                Ok(e) => e,
230                Err(e) => {
231                    pb.println(format!("   ⚠ Failed to create LLM client: {}", e));
232                    pb.finish_and_clear();
233                    return Ok(());
234                }
235            }
236        } else {
237            match llm::docs::DocsEnhancer::new(
238                self.config.llm_model.clone(),
239                Some(self.config.cache_dir.clone()),
240            ) {
241                Ok(e) => e,
242                Err(e) => {
243                    pb.println(format!("   ⚠ Failed to create LLM client: {}", e));
244                    pb.finish_and_clear();
245                    return Ok(());
246                }
247            }
248        };
249
250        let mut enhanced_count = 0;
251
252        // Enhance error messages
253        if let Some(analysis) = &self.analysis
254            && let Some(error_enum) = analysis.error_patterns.error_enums.first()
255        {
256            pb.set_message("Enhancing error messages...");
257            for variant in &error_enum.error_variants {
258                if let Ok(Some(message)) = enhancer.enhance_error_message(variant, &error_enum.name)
259                {
260                    info!("Enhanced error message for {}: {}", variant, message);
261                    enhancements.add_error_message(variant.clone(), message);
262                    enhanced_count += 1;
263                }
264            }
265        }
266
267        // Enhance function documentation
268        if let Some(ffi_info) = &self.ffi_info {
269            pb.set_message("Enhancing function documentation...");
270            let sample_funcs: Vec<_> = ffi_info
271                .functions
272                .iter()
273                .take(5) // Sample first 5 functions to avoid too many LLM calls
274                .collect();
275
276            for func in sample_funcs {
277                let signature = format!(
278                    "{}({}) -> {}",
279                    func.name,
280                    func.params
281                        .iter()
282                        .map(|p| format!("{}: {}", p.name, p.ty))
283                        .collect::<Vec<_>>()
284                        .join(", "),
285                    func.return_type
286                );
287
288                let context = format!(
289                    "C FFI function from {} library",
290                    self.config.lib_name.as_deref().unwrap_or("unknown")
291                );
292
293                if let Ok(Some(enhanced_docs)) =
294                    enhancer.enhance_function_docs(&func.name, &signature, &context)
295                {
296                    info!("Enhanced docs for {}: {}", func.name, enhanced_docs);
297                    enhancements.add_function_docs(func.name.clone(), enhanced_docs);
298                    enhanced_count += 1;
299                }
300            }
301        }
302
303        // Suggest better naming for C-style functions
304        if let Some(ffi_info) = &self.ffi_info {
305            pb.set_message("Suggesting idiomatic names...");
306            let sample_funcs: Vec<_> = ffi_info
307                .functions
308                .iter()
309                .filter(|f| f.name.contains('_')) // C-style names with underscores
310                .take(3)
311                .collect();
312
313            for func in sample_funcs {
314                let context = format!(
315                    "C FFI function from {} library: {}",
316                    self.config.lib_name.as_deref().unwrap_or("unknown"),
317                    func.name
318                );
319
320                if let Ok(Some(suggestions)) =
321                    enhancer.suggest_names(&func.name, &context, "function")
322                {
323                    info!("Naming suggestions for {}: {:?}", func.name, suggestions);
324                    // Store the first suggestion as the preferred name
325                    if let Some(first_suggestion) = suggestions.first() {
326                        enhancements.add_function_name(func.name.clone(), first_suggestion.clone());
327                    }
328                    enhanced_count += 1;
329                }
330            }
331        }
332
333        pb.println(format!(
334            "   āœ“ LLM enhancement complete ({} items enhanced)",
335            enhanced_count
336        ));
337        pb.finish_and_clear();
338
339        // Store the enhancements for use in code generation
340        self.llm_enhancements = Some(enhancements);
341
342        Ok(())
343    }
344
345    fn phase_interactive(&mut self) -> Result<()> {
346        let pb = Self::create_progress_bar("Phase 6: Clarifying ambiguities...");
347
348        info!("Starting interactive phase");
349
350        // Check if we have analysis results with RAII patterns
351        if let Some(analysis) = &self.analysis {
352            // Check if there are low-confidence patterns that need clarification
353            let has_low_confidence = analysis
354                .raii_patterns
355                .lifecycle_pairs
356                .iter()
357                .any(|pair| pair.confidence < 0.7);
358
359            if has_low_confidence {
360                pb.println("   ⚠ Low-confidence patterns detected, requesting clarification...");
361                pb.finish_and_clear();
362
363                // Request user clarification
364                let clarifications = interactive::clarify_patterns(&analysis.raii_patterns)?;
365
366                let confirmed_count = clarifications.confirmed_pairs.len();
367
368                // Update analysis with confirmed pairs
369                if let Some(mut_analysis) = &mut self.analysis {
370                    mut_analysis.raii_patterns.lifecycle_pairs = clarifications.confirmed_pairs;
371                }
372
373                println!(
374                    "   āœ“ Clarification complete ({} pairs confirmed)",
375                    confirmed_count
376                );
377            } else {
378                pb.println("   ℹ No ambiguities detected");
379                pb.finish_and_clear();
380            }
381        } else {
382            pb.println("   ℹ No analysis available for clarification");
383            pb.finish_and_clear();
384        }
385
386        Ok(())
387    }
388
389    fn phase_output(&self, lib_name: &str) -> Result<()> {
390        let pb = Self::create_progress_bar(&format!(
391            "Phase 7: Writing output to {}...",
392            self.config.output_path.display()
393        ));
394
395        info!("Starting output phase");
396
397        let generated = self.generated_code.as_ref().expect("Code not generated");
398
399        output::output_generated_code(&self.config.output_path, &generated.lib_rs, lib_name)?;
400
401        pb.println("   āœ“ Created Cargo.toml");
402        pb.println("   āœ“ Created src/lib.rs");
403        pb.println("   āœ“ Created build.rs");
404
405        pb.finish_and_clear();
406        Ok(())
407    }
408
409    fn phase_validation(&self) -> Result<()> {
410        let pb = Self::create_progress_bar("Phase 8: Validating...");
411
412        info!("Starting validation phase");
413
414        if output::validator::is_cargo_available() {
415            match output::validate_code(&self.config.output_path) {
416                Ok(true) => pb.println("   āœ“ Checking with cargo check... SUCCESS!"),
417                Ok(false) => pb.println("   ⚠ Checking with cargo check... FAILED (see logs)"),
418                Err(e) => pb.println(format!("   ⚠ Validation error: {}", e)),
419            }
420        } else {
421            pb.println("   ⚠ cargo not available, skipping validation");
422        }
423
424        pb.finish_and_clear();
425        Ok(())
426    }
427
428    fn phase_ollama_setup(&mut self) -> Result<()> {
429        info!("Checking Ollama availability");
430
431        // Check if Ollama is already installed
432        if llm::OllamaInstaller::is_available() {
433            info!("Ollama already installed");
434            let installer = llm::OllamaInstaller::new();
435            self.ollama_installer = Some(installer);
436            return Ok(());
437        }
438
439        // Ollama not found, prompt user for installation
440        let mut installer = llm::OllamaInstaller::new();
441
442        match installer.prompt_installation() {
443            Ok(llm::OllamaInstallType::SystemWide) => {
444                installer.install_system_wide()?;
445                self.ollama_installer = Some(installer);
446                Ok(())
447            }
448            Ok(llm::OllamaInstallType::Portable { path, .. }) => {
449                // Prompt for model selection
450                let model = llm::select_model()?;
451                let process = installer.install_portable(path, &model)?;
452                self.ollama_process = Some(process);
453                self.ollama_installer = Some(installer);
454                Ok(())
455            }
456            Ok(llm::OllamaInstallType::AlreadyInstalled) => {
457                self.ollama_installer = Some(installer);
458                Ok(())
459            }
460            Err(e) => {
461                // User chose to skip LLM features
462                info!("User skipped Ollama installation: {}", e);
463                self.config.use_llm = false;
464                Ok(())
465            }
466        }
467    }
468
469    fn phase_cleanup(&mut self) -> Result<()> {
470        if let Some(ref mut installer) = self.ollama_installer {
471            // Only prompt for cleanup if we installed portably
472            if matches!(
473                installer.install_type(),
474                Some(llm::OllamaInstallType::Portable { .. })
475            ) {
476                installer.prompt_cleanup()?;
477            }
478        }
479        Ok(())
480    }
481
482    fn create_progress_bar(message: &str) -> ProgressBar {
483        let pb = ProgressBar::new_spinner();
484        pb.set_style(
485            ProgressStyle::default_spinner()
486                .template("{spinner:.green} {msg}")
487                .unwrap(),
488        );
489        pb.set_message(message.to_string());
490        pb.enable_steady_tick(std::time::Duration::from_millis(100));
491        pb
492    }
493}