assura 0.2.0

Contract-first AI-native language. Write what it should do. AI proves it does.
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
934
935
936
937
use super::*;

// `assura infer <rust_file>` -- generate skeleton Assura contracts
// ---------------------------------------------------------------------------

pub(crate) fn run_infer(
    filename: &str,
    function_filter: Option<&str>,
    output_path: Option<&str>,
    dry_run: bool,
    focus: Option<&str>,
) {
    let source = fs::read_to_string(filename).unwrap_or_else(|e| {
        eprintln!("Error: {filename}: {e}");
        process::exit(2);
    });

    // Parse focus patterns
    let focus_patterns: Vec<&str> = focus
        .map(|f| f.split(',').map(str::trim).collect())
        .unwrap_or_default();

    // Try heuristic-based inference using syn parser (for .rs files)
    if filename.ends_with(".rs") {
        run_infer_heuristic(filename, &source, &focus_patterns, dry_run, output_path);
        return;
    }

    // Legacy path: generate .assura bind skeletons from Rust source
    let signatures = extract_rust_fn_signatures(&source);

    if signatures.is_empty() {
        eprintln!("No public function signatures found in {filename}");
        process::exit(1);
    }

    let filtered: Vec<&RustFnSig> = if let Some(name) = function_filter {
        let matches: Vec<_> = signatures.iter().filter(|s| s.name == name).collect();
        if matches.is_empty() {
            eprintln!("Function '{name}' not found in {filename}");
            let names: Vec<_> = signatures
                .iter()
                .filter(|s| s.is_pub)
                .map(|s| s.name.as_str())
                .collect();
            eprintln!("Available public functions: {}", names.join(", "));
            process::exit(1);
        }
        matches
    } else {
        // Default: only public functions
        signatures.iter().filter(|s| s.is_pub).collect()
    };

    if filtered.is_empty() {
        eprintln!("No public function signatures found in {filename}");
        process::exit(1);
    }

    let module_path = derive_rust_module_path(filename);

    let mut out_buf = String::new();
    out_buf.push_str(&format!(
        "// Generated by: assura infer {filename}\n// Review and refine these contracts before use.\n\n"
    ));

    for sig in &filtered {
        generate_bind_skeleton(&module_path, sig, &mut out_buf);
    }

    out_buf.push_str(&format!(
        "\n// {} function(s) analyzed from {filename}\n",
        filtered.len()
    ));

    if let Some(path) = output_path {
        fs::write(path, &out_buf).unwrap_or_else(|e| {
            eprintln!("Error: cannot write {path}: {e}");
            process::exit(2);
        });
        eprintln!("Wrote {} contract(s) to {path}", filtered.len());
    } else {
        print!("{out_buf}");
    }
}

/// A suggested contract annotation for a function.
pub(crate) struct InferSuggestion {
    line: usize,
    fn_name: String,
    annotations: Vec<String>,
    pattern: String,
}

/// Run heuristic-based inference on a Rust source file.
///
/// Detects common patterns that suggest contracts:
/// - Division operations: suggest `@requires divisor != 0`
/// - Array/slice indexing: suggest `@requires index < len`
/// - `.unwrap()` calls: suggest `@requires` for `is_some()`/`is_ok()`
/// - Unsafe blocks: note for manual review
pub(crate) fn run_infer_heuristic(
    filename: &str,
    source: &str,
    focus: &[&str],
    dry_run: bool,
    output_path: Option<&str>,
) {
    let mut suggestions = Vec::new();

    // Parse with syn for precise analysis
    let file = match syn::parse_file(source) {
        Ok(f) => f,
        Err(e) => {
            eprintln!("Error parsing {filename}: {e}");
            process::exit(1);
        }
    };

    for item in &file.items {
        match item {
            syn::Item::Fn(func) => {
                let suggs = analyze_function_body(func, source, focus);
                suggestions.extend(suggs);
            }
            syn::Item::Impl(imp) => {
                for impl_item in &imp.items {
                    if let syn::ImplItem::Fn(method) = impl_item {
                        let suggs = analyze_method_body(method, source, focus);
                        suggestions.extend(suggs);
                    }
                }
            }
            _ => {}
        }
    }

    if suggestions.is_empty() {
        println!("No contract suggestions for {filename}");
        if !focus.is_empty() {
            println!("  (filtered by: {})", focus.join(", "));
        }
        return;
    }

    // Format output
    let mut output = String::new();
    output.push_str(&format!(
        "// Contract suggestions for {filename}\n// Generated by: assura infer --dry-run\n// Review each suggestion before accepting.\n\n"
    ));

    for s in &suggestions {
        output.push_str(&format!(
            "// [{pattern}] {fn_name} (line {line})\n",
            pattern = s.pattern,
            fn_name = s.fn_name,
            line = s.line
        ));
        for ann in &s.annotations {
            output.push_str(&format!("//   {ann}\n"));
        }
        output.push('\n');
    }

    output.push_str(&format!(
        "// {} suggestion(s) for {} function(s)\n",
        suggestions
            .iter()
            .map(|s| s.annotations.len())
            .sum::<usize>(),
        suggestions.len()
    ));

    if dry_run || output_path.is_none() {
        print!("{output}");
    }
    if let Some(path) = output_path
        && !dry_run
    {
        fs::write(path, &output).unwrap_or_else(|e| {
            eprintln!("Error writing {path}: {e}");
            process::exit(2);
        });
        eprintln!("Wrote suggestions to {path}");
    }

    println!(
        "\n{} suggestion(s) found across {} function(s)",
        suggestions
            .iter()
            .map(|s| s.annotations.len())
            .sum::<usize>(),
        suggestions.len()
    );
}

/// Analyze a free function body for contract suggestions.
pub(crate) fn analyze_function_body(
    func: &syn::ItemFn,
    source: &str,
    focus: &[&str],
) -> Vec<InferSuggestion> {
    let name = func.sig.ident.to_string();
    let body_str = extract_block_text(&func.block, source);
    let line = func.sig.fn_token.span.start().line + 1;
    let params = extract_param_names(&func.sig);
    analyze_body_text(&name, &body_str, line, &params, focus)
}

/// Analyze a method body for contract suggestions.
pub(crate) fn analyze_method_body(
    method: &syn::ImplItemFn,
    source: &str,
    focus: &[&str],
) -> Vec<InferSuggestion> {
    let name = method.sig.ident.to_string();
    let body_str = extract_block_text(&method.block, source);
    let line = method.sig.fn_token.span.start().line + 1;
    let params = extract_param_names(&method.sig);
    analyze_body_text(&name, &body_str, line, &params, focus)
}

/// Extract the text of a block from source using span info.
pub(crate) fn extract_block_text(block: &syn::Block, _source: &str) -> String {
    use quote::ToTokens;
    block.to_token_stream().to_string()
}

/// Extract parameter names from a function signature.
pub(crate) fn extract_param_names(sig: &syn::Signature) -> Vec<String> {
    sig.inputs
        .iter()
        .filter_map(|arg| match arg {
            syn::FnArg::Typed(pt) => {
                use quote::ToTokens;
                Some(pt.pat.to_token_stream().to_string())
            }
            syn::FnArg::Receiver(_) => None,
        })
        .collect()
}

/// Analyze function body text for patterns that suggest contracts.
pub(crate) fn analyze_body_text(
    fn_name: &str,
    body: &str,
    line: usize,
    params: &[String],
    focus: &[&str],
) -> Vec<InferSuggestion> {
    let mut suggestions = Vec::new();
    let focus_all = focus.is_empty();

    // Pattern: division by a parameter
    if (focus_all || focus.contains(&"division")) && body.contains('/') {
        for param in params {
            if body.contains(&format!("/ {param}"))
                || body.contains(&format!("/{param}"))
                || body.contains(&format!("% {param}"))
            {
                suggestions.push(InferSuggestion {
                    line,
                    fn_name: fn_name.to_string(),
                    annotations: vec![format!("/// @requires {param} != 0")],
                    pattern: "division".to_string(),
                });
            }
        }
    }

    // Pattern: .unwrap() calls (tokenized output may have spaces: ". unwrap ()")
    if (focus_all || focus.contains(&"unwrap"))
        && (body.contains(".unwrap()") || body.contains(". unwrap ()"))
    {
        suggestions.push(InferSuggestion {
            line,
            fn_name: fn_name.to_string(),
            annotations: vec![
                "/// @requires <value>.is_some() // or .is_ok()".to_string(),
                "// REVIEW: .unwrap() panics on None/Err".to_string(),
            ],
            pattern: "unwrap".to_string(),
        });
    }

    // Pattern: array/slice indexing with parameter
    // Tokenized output may have spaces: "items [idx]" or "[idx]"
    if (focus_all || focus.contains(&"index")) && body.contains('[') {
        for param in params {
            if body.contains(&format!("[{param}]"))
                || body.contains(&format!("[ {param} ]"))
                || body.contains(&format!("[{param} ]"))
                || body.contains(&format!("[ {param}]"))
            {
                suggestions.push(InferSuggestion {
                    line,
                    fn_name: fn_name.to_string(),
                    annotations: vec![format!("/// @requires {param} < <collection>.len()")],
                    pattern: "index".to_string(),
                });
            }
        }
    }

    // Pattern: unsafe blocks (keyword may appear in tokenized output)
    if (focus_all || focus.contains(&"unsafe"))
        && (body.contains("unsafe") || body.contains("unsafe {"))
    {
        suggestions.push(InferSuggestion {
            line,
            fn_name: fn_name.to_string(),
            annotations: vec![
                "// REVIEW: contains unsafe block, manual contract required".to_string(),
            ],
            pattern: "unsafe".to_string(),
        });
    }

    // Pattern: panic!/todo!/unimplemented! (tokenized: "panic !", "todo !", etc.)
    if (focus_all || focus.contains(&"panic"))
        && (body.contains("panic!")
            || body.contains("panic !")
            || body.contains("todo!")
            || body.contains("todo !")
            || body.contains("unimplemented!")
            || body.contains("unimplemented !"))
    {
        suggestions.push(InferSuggestion {
            line,
            fn_name: fn_name.to_string(),
            annotations: vec![
                "// REVIEW: contains panic!/todo!/unimplemented!, add @requires to prevent"
                    .to_string(),
            ],
            pattern: "panic".to_string(),
        });
    }

    suggestions
}

/// A parsed Rust function signature (minimal, no syn dependency).
pub(crate) struct RustFnSig {
    pub(crate) name: String,
    pub(crate) params: Vec<(String, String)>, // (name, type)
    pub(crate) return_type: String,
    pub(crate) is_pub: bool,
}

/// Extract public function signatures from Rust source text.
///
/// This is a lightweight regex-free parser that handles common patterns.
/// It does NOT use syn (to avoid adding a heavy dependency to the CLI).
pub(crate) fn extract_rust_fn_signatures(source: &str) -> Vec<RustFnSig> {
    let mut sigs = Vec::new();
    let lines: Vec<&str> = source.lines().collect();
    let mut i = 0;

    while i < lines.len() {
        let line = lines[i].trim();

        // Strip leading modifiers to find `fn ` keyword.
        // Handles: pub fn, pub(crate) fn, pub async fn, pub const fn,
        //          pub unsafe fn, async fn, const fn, unsafe fn, etc.
        let (is_pub, fn_part) = match strip_fn_prefix(line) {
            Some(pair) => pair,
            None => {
                i += 1;
                continue;
            }
        };

        // Collect full signature (may span multiple lines)
        let mut full_sig = fn_part.to_string();
        let mut j = i + 1;
        while !full_sig.contains('{') && !full_sig.contains(';') && j < lines.len() {
            full_sig.push(' ');
            full_sig.push_str(lines[j].trim());
            j += 1;
        }

        if let Some(sig) = parse_fn_signature(&full_sig, is_pub) {
            sigs.push(sig);
        }

        i = j.max(i + 1);
    }

    sigs
}

/// Strip function declaration prefix and return (is_pub, rest_after_fn).
/// Handles all modifier combinations: pub/pub(vis), async, const, unsafe.
pub(crate) fn strip_fn_prefix(line: &str) -> Option<(bool, &str)> {
    let mut rest = line;
    let mut is_pub = false;

    // Check for pub / pub(vis)
    if let Some(after_pub) = rest.strip_prefix("pub") {
        is_pub = true;
        rest = after_pub;
        // Handle pub(crate), pub(super), pub(in path)
        let trimmed = rest.trim_start();
        if let Some(after_paren) = trimmed.strip_prefix('(') {
            if let Some(close) = after_paren.find(')') {
                rest = &after_paren[close + 1..];
            } else {
                return None;
            }
        } else {
            rest = trimmed;
        }
    }

    // Strip optional modifiers: async, const, unsafe (in any order)
    loop {
        let trimmed = rest.trim_start();
        if let Some(after) = trimmed.strip_prefix("async ") {
            rest = after;
        } else if let Some(after) = trimmed.strip_prefix("const ") {
            rest = after;
        } else if let Some(after) = trimmed.strip_prefix("unsafe ") {
            rest = after;
        } else {
            rest = trimmed;
            break;
        }
    }

    // Must find `fn ` keyword
    let after_fn = rest.strip_prefix("fn ")?;
    Some((is_pub, after_fn))
}

/// Parse a single function signature string like "foo(x: i64, y: &str) -> bool {"
pub(crate) fn parse_fn_signature(sig: &str, is_pub: bool) -> Option<RustFnSig> {
    let paren_open = sig.find('(')?;
    let raw_name = sig[..paren_open].trim();

    // Strip generic parameters: `encode<T: Serialize>` -> `encode`
    let name = if let Some(angle) = raw_name.find('<') {
        raw_name[..angle].trim().to_string()
    } else {
        raw_name.to_string()
    };

    // Skip if name contains invalid chars (macros, etc.)
    if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
        return None;
    }

    // Find matching closing paren (handle nested parens)
    let after_open = &sig[paren_open + 1..];
    let mut depth = 1i32;
    let mut close_offset = 0;
    for (i, ch) in after_open.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    close_offset = i;
                    break;
                }
            }
            _ => {}
        }
    }

    let params_str = &after_open[..close_offset];
    let params = parse_param_list(params_str);

    // Extract return type
    let after_close = &after_open[close_offset + 1..];
    let return_type = if let Some(arrow_pos) = after_close.find("->") {
        let ret = after_close[arrow_pos + 2..].trim();
        // Strip trailing { or where
        let ret = ret
            .split('{')
            .next()
            .unwrap_or(ret)
            .split("where")
            .next()
            .unwrap_or(ret)
            .trim();
        ret.to_string()
    } else {
        "()".to_string()
    };

    Some(RustFnSig {
        name,
        params,
        return_type,
        is_pub,
    })
}

/// Parse a parameter list like "x: i64, y: &str, _: bool"
pub(crate) fn parse_param_list(params: &str) -> Vec<(String, String)> {
    let params = params.trim();
    if params.is_empty() {
        return Vec::new();
    }

    let mut result = Vec::new();
    let mut depth = 0i32;
    let mut paren_depth = 0i32;
    let mut start = 0;

    // Split on commas respecting <> and ()
    let mut segments = Vec::new();
    for (i, ch) in params.char_indices() {
        match ch {
            '<' => depth += 1,
            '>' if depth > 0 => depth -= 1,
            '(' => paren_depth += 1,
            ')' if paren_depth > 0 => paren_depth -= 1,
            ',' if depth == 0 && paren_depth == 0 => {
                segments.push(&params[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    segments.push(&params[start..]);

    for seg in segments {
        let seg = seg.trim();
        // Skip self, &self, &mut self
        if seg == "self" || seg == "&self" || seg == "&mut self" {
            continue;
        }
        if let Some(colon_pos) = seg.find(':') {
            let name = seg[..colon_pos].trim();
            let ty = seg[colon_pos + 1..].trim();
            if !name.is_empty() {
                result.push((name.to_string(), ty.to_string()));
            }
        }
    }

    result
}

/// Derive a Rust module path from a filesystem path.
///
/// Walks up from the file looking for `Cargo.toml` to find the crate name.
/// Converts hyphens to underscores (Rust identifier convention).
/// Strips the `src/` segment and maps `lib.rs`/`mod.rs` to their parent module.
///
/// Examples:
///   `crates/assura-codegen/src/type_map.rs` -> `assura_codegen::type_map`
///   `src/lib.rs` -> `my_crate` (crate name from Cargo.toml)
///   `src/foo/bar.rs` -> `my_crate::foo::bar`
pub(crate) fn derive_rust_module_path(file_path: &str) -> String {
    let path = Path::new(file_path);

    // Find the src/ component and the crate root above it
    let components: Vec<_> = path.components().collect();
    let mut crate_name: Option<String> = None;
    let mut src_index: Option<usize> = None;

    for (i, comp) in components.iter().enumerate() {
        if comp.as_os_str() == "src" {
            src_index = Some(i);
            // Crate root is the directory containing src/
            let crate_root: std::path::PathBuf = if i > 0 {
                components[..i].iter().collect()
            } else {
                std::path::PathBuf::from(".")
            };
            // Try to read crate name from Cargo.toml
            let cargo_path = crate_root.join("Cargo.toml");
            if let Ok(content) = fs::read_to_string(&cargo_path) {
                for line in content.lines() {
                    let trimmed = line.trim();
                    if let Some(rest) = trimmed.strip_prefix("name") {
                        let rest = rest.trim_start();
                        if let Some(rest) = rest.strip_prefix('=') {
                            let rest = rest.trim();
                            let name = rest.trim_matches('"').trim_matches('\'');
                            crate_name = Some(name.replace('-', "_"));
                            break;
                        }
                    }
                }
            }
            break;
        }
    }

    let crate_segment = crate_name.unwrap_or_else(|| "crate".to_string());

    if let Some(si) = src_index {
        // Build relative path from components after src/
        if si + 1 < components.len() {
            let after_src: std::path::PathBuf = components[si + 1..].iter().collect();
            let rel_str = after_src
                .to_string_lossy()
                .trim_end_matches(".rs")
                .replace(['/', '\\'], "::");

            // lib.rs / mod.rs -> just the parent module (or crate root)
            if rel_str == "lib" || rel_str == "mod" {
                crate_segment
            } else if rel_str.ends_with("::mod") || rel_str.ends_with("::lib") {
                let trimmed = rel_str.trim_end_matches("::mod").trim_end_matches("::lib");
                format!("{crate_segment}::{trimmed}")
            } else {
                format!("{crate_segment}::{rel_str}")
            }
        } else {
            // Path ends at src/ itself (unusual)
            crate_segment
        }
    } else {
        // No src/ found; fallback: strip .rs, convert path separators, fix hyphens
        file_path
            .trim_end_matches(".rs")
            .replace('/', "::")
            .replace('-', "_")
    }
}

/// Generate a bind skeleton for a single function.
pub(crate) fn generate_bind_skeleton(module_path: &str, sig: &RustFnSig, out: &mut String) {
    use assura_codegen::type_map::rust_type_to_assura;

    let rust_path = format!("{module_path}::{}", sig.name);

    out.push_str(&format!("bind \"{}\" as {} {{\n", rust_path, sig.name));

    // Input params
    if !sig.params.is_empty() {
        out.push_str("    input(");
        let params: Vec<String> = sig
            .params
            .iter()
            .map(|(name, ty)| format!("{}: {}", name, rust_type_to_assura(ty)))
            .collect();
        out.push_str(&params.join(", "));
        out.push_str(")\n");
    }

    // Output
    let assura_ret = rust_type_to_assura(&sig.return_type);
    if assura_ret != "Unit" {
        out.push_str(&format!("    output(result: {assura_ret})\n"));
    }

    // Heuristic clause generation based on parameter and return types
    let mut has_clause = false;

    for (name, rust_ty) in &sig.params {
        let param_assura = rust_type_to_assura(rust_ty);
        if matches!(param_assura.as_str(), "Int" | "Nat" | "Float") {
            out.push_str(&format!("    requires {{ {name} >= 0 }}\n"));
            has_clause = true;
        }
    }

    if matches!(assura_ret.as_str(), "Int" | "Nat" | "Float") {
        out.push_str("    ensures { result >= 0 }\n");
        has_clause = true;
    }

    if !has_clause {
        out.push_str("    // TODO: add requires clauses (preconditions)\n");
        out.push_str("    // TODO: add ensures clauses (postconditions)\n");
    }

    out.push_str("}\n\n");
}

// ---------------------------------------------------------------------------

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

    // ---- strip_fn_prefix ----

    #[test]
    fn strip_pub_fn() {
        let (is_pub, rest) = strip_fn_prefix("pub fn foo()").unwrap();
        assert!(is_pub);
        assert_eq!(rest, "foo()");
    }

    #[test]
    fn strip_plain_fn() {
        let (is_pub, rest) = strip_fn_prefix("fn bar()").unwrap();
        assert!(!is_pub);
        assert_eq!(rest, "bar()");
    }

    #[test]
    fn strip_pub_crate_fn() {
        let (is_pub, rest) = strip_fn_prefix("pub(crate) fn baz()").unwrap();
        assert!(is_pub);
        assert_eq!(rest, "baz()");
    }

    #[test]
    fn strip_pub_async_fn() {
        let (is_pub, rest) = strip_fn_prefix("pub async fn fetch()").unwrap();
        assert!(is_pub);
        assert_eq!(rest, "fetch()");
    }

    #[test]
    fn strip_pub_unsafe_fn() {
        let (is_pub, rest) = strip_fn_prefix("pub unsafe fn danger()").unwrap();
        assert!(is_pub);
        assert_eq!(rest, "danger()");
    }

    #[test]
    fn strip_pub_const_fn() {
        let (is_pub, rest) = strip_fn_prefix("pub const fn SIZE()").unwrap();
        assert!(is_pub);
        assert_eq!(rest, "SIZE()");
    }

    #[test]
    fn strip_non_fn_line() {
        assert!(strip_fn_prefix("let x = 5;").is_none());
        assert!(strip_fn_prefix("struct Foo {}").is_none());
        assert!(strip_fn_prefix("// fn comment").is_none());
    }

    // ---- parse_param_list ----

    #[test]
    fn parse_empty_params() {
        let params = parse_param_list("");
        assert!(params.is_empty());
    }

    #[test]
    fn parse_single_param() {
        let params = parse_param_list("x: i64");
        assert_eq!(params.len(), 1);
        assert_eq!(params[0].0, "x");
        assert_eq!(params[0].1, "i64");
    }

    #[test]
    fn parse_multiple_params() {
        let params = parse_param_list("a: i32, b: &str, c: bool");
        assert_eq!(params.len(), 3);
        assert_eq!(params[0].0, "a");
        assert_eq!(params[1].0, "b");
        assert_eq!(params[2].0, "c");
    }

    #[test]
    fn parse_skips_self() {
        let params = parse_param_list("&self, x: i64");
        assert_eq!(params.len(), 1);
        assert_eq!(params[0].0, "x");
    }

    #[test]
    fn parse_generic_params() {
        let params = parse_param_list("items: Vec<String>, idx: usize");
        assert_eq!(params.len(), 2);
        assert_eq!(params[0].1, "Vec<String>");
        assert_eq!(params[1].0, "idx");
    }

    #[test]
    fn parse_nested_generic_params() {
        let params = parse_param_list("m: HashMap<String, Vec<i32>>");
        assert_eq!(params.len(), 1);
        assert_eq!(params[0].1, "HashMap<String, Vec<i32>>");
    }

    // ---- parse_fn_signature ----

    #[test]
    fn parse_simple_signature() {
        let sig = parse_fn_signature("add(a: i32, b: i32) -> i32 {", true).unwrap();
        assert_eq!(sig.name, "add");
        assert_eq!(sig.params.len(), 2);
        assert_eq!(sig.return_type, "i32");
        assert!(sig.is_pub);
    }

    #[test]
    fn parse_no_return_type() {
        let sig = parse_fn_signature("init() {", false).unwrap();
        assert_eq!(sig.name, "init");
        assert_eq!(sig.return_type, "()");
    }

    #[test]
    fn parse_generic_fn() {
        let sig = parse_fn_signature("encode<T: Serialize>(value: T) -> String {", true).unwrap();
        assert_eq!(sig.name, "encode");
        assert_eq!(sig.params.len(), 1);
    }

    #[test]
    fn parse_where_clause_stripped() {
        let sig = parse_fn_signature(
            "process(data: Vec<u8>) -> Result<(), Error> where T: Clone {",
            true,
        )
        .unwrap();
        assert_eq!(sig.return_type, "Result<(), Error>");
    }

    // ---- extract_rust_fn_signatures ----

    #[test]
    fn extract_pub_fns_from_source() {
        let source = "pub fn add(a: i32, b: i32) -> i32 {\n    a + b\n}\n\nfn private_helper() {\n}\n\npub fn greet(name: &str) -> String {\n    format!(\"Hello, {name}\")\n}\n";
        let sigs = extract_rust_fn_signatures(source);
        assert_eq!(sigs.len(), 3);

        let pub_sigs: Vec<_> = sigs.iter().filter(|s| s.is_pub).collect();
        assert_eq!(pub_sigs.len(), 2);
        assert_eq!(pub_sigs[0].name, "add");
        assert_eq!(pub_sigs[1].name, "greet");
    }

    // ---- derive_rust_module_path ----

    #[test]
    fn module_path_no_src() {
        let path = derive_rust_module_path("foo/bar.rs");
        assert_eq!(path, "foo::bar");
    }

    // ---- analyze_body_text ----

    #[test]
    fn detects_division_pattern() {
        let suggs = analyze_body_text(
            "divide",
            "result = a / b",
            10,
            &["a".into(), "b".into()],
            &[],
        );
        assert!(suggs.iter().any(|s| s.pattern == "division"));
    }

    #[test]
    fn detects_unwrap_pattern() {
        let suggs = analyze_body_text("process", "x.unwrap()", 5, &[], &[]);
        assert!(suggs.iter().any(|s| s.pattern == "unwrap"));
    }

    #[test]
    fn detects_index_pattern() {
        let suggs = analyze_body_text(
            "lookup",
            "items[idx]",
            1,
            &["items".into(), "idx".into()],
            &[],
        );
        assert!(suggs.iter().any(|s| s.pattern == "index"));
    }

    #[test]
    fn detects_unsafe_pattern() {
        let suggs = analyze_body_text("raw_op", "unsafe { *ptr }", 1, &[], &[]);
        assert!(suggs.iter().any(|s| s.pattern == "unsafe"));
    }

    #[test]
    fn detects_panic_pattern() {
        let suggs = analyze_body_text("bail", "panic!(\"oh no\")", 1, &[], &[]);
        assert!(suggs.iter().any(|s| s.pattern == "panic"));
    }

    #[test]
    fn focus_filters_patterns() {
        let suggs = analyze_body_text(
            "mixed",
            "x.unwrap(); items[idx]; a / b",
            1,
            &["a".into(), "b".into(), "idx".into()],
            &["division"],
        );
        assert!(suggs.iter().all(|s| s.pattern == "division"));
    }

    #[test]
    fn no_false_positives_on_clean_body() {
        let suggs = analyze_body_text(
            "clean",
            "a + b * c",
            1,
            &["a".into(), "b".into(), "c".into()],
            &[],
        );
        assert!(suggs.is_empty());
    }

    // ---- generate_bind_skeleton ----

    #[test]
    fn bind_skeleton_has_input_and_output() {
        let sig = RustFnSig {
            name: "add".to_string(),
            params: vec![
                ("a".to_string(), "i64".to_string()),
                ("b".to_string(), "i64".to_string()),
            ],
            return_type: "i64".to_string(),
            is_pub: true,
        };
        let mut out = String::new();
        generate_bind_skeleton("my_crate", &sig, &mut out);
        assert!(out.contains("bind \"my_crate::add\" as add"));
        assert!(out.contains("input(a: Int, b: Int)"));
        assert!(out.contains("output(result: Int)"));
    }

    #[test]
    fn bind_skeleton_unit_return_omits_output() {
        let sig = RustFnSig {
            name: "init".to_string(),
            params: vec![],
            return_type: "()".to_string(),
            is_pub: true,
        };
        let mut out = String::new();
        generate_bind_skeleton("my_crate", &sig, &mut out);
        assert!(!out.contains("output"));
    }
}