1use crate::model::{LoopNode, Mode, ModelFn};
5use std::collections::{BTreeMap, BTreeSet};
6use std::fmt::Write;
7
8pub type Pos = (usize, usize);
10
11#[derive(Debug, Clone)]
13pub struct AeneasDecl {
14 pub lean: String,
16 pub rust: Option<String>,
18 pub loop_index: Option<usize>,
20 pub source: Option<(String, Pos, Pos)>,
22 pub body: String,
24}
25
26const DECL_KEYWORDS: &[&str] = &[
27 "def",
28 "structure",
29 "inductive",
30 "axiom",
31 "abbrev",
32 "opaque",
33 "theorem",
34 "class",
35 "instance",
36];
37
38fn parse_pos(s: &str) -> Option<(usize, usize)> {
39 let (l, c) = s.split_once(':')?;
40 Some((l.trim().parse().ok()?, c.trim().parse().ok()?))
41}
42
43fn decl_name(body: &str) -> Option<String> {
44 let mut text = body.trim_start();
45 loop {
46 if let Some(rest) = text.strip_prefix("@[") {
47 let mut depth = 1;
48 let mut end = None;
49 for (i, ch) in rest.char_indices() {
50 match ch {
51 '[' => depth += 1,
52 ']' => {
53 depth -= 1;
54 if depth == 0 {
55 end = Some(i);
56 break;
57 }
58 }
59 _ => {}
60 }
61 }
62 text = rest[end? + 1..].trim_start();
63 continue;
64 }
65 let mut words = text.split_whitespace();
66 let first = words.next()?;
67 if [
68 "noncomputable",
69 "private",
70 "protected",
71 "partial",
72 "unsafe",
73 "public",
74 ]
75 .contains(&first)
76 {
77 text = text[first.len()..].trim_start();
78 continue;
79 }
80 if DECL_KEYWORDS.contains(&first) {
81 return words.next().map(str::to_string);
82 }
83 return None;
84 }
85}
86
87pub fn parse_aeneas(text: &str) -> Vec<AeneasDecl> {
89 let mut out = Vec::new();
90 let chunks: Vec<&str> = text.split("/--").collect();
91 for chunk in chunks.iter().skip(1) {
92 let Some((doc, body)) = chunk.split_once("-/") else {
93 continue;
94 };
95 let Some(lean) = decl_name(body) else {
96 continue;
97 };
98 let doc = doc.trim();
99 let mut rust = None;
100 let mut loop_index = None;
101 if let Some(rest) = doc.strip_prefix('[') {
102 let mut depth = 1;
103 let mut end = 0;
104 for (i, ch) in rest.char_indices() {
105 match ch {
106 '[' => depth += 1,
107 ']' => {
108 depth -= 1;
109 if depth == 0 {
110 end = i;
111 break;
112 }
113 }
114 _ => {}
115 }
116 }
117 rust = Some(rest[..end].to_string());
118 let after = &rest[end + 1..];
119 if let Some(l) = after.trim_start_matches(':').trim().strip_prefix("loop ") {
120 loop_index = l
121 .split(|c: char| !c.is_ascii_digit())
122 .next()
123 .and_then(|n| n.parse().ok());
124 }
125 }
126 let source = doc.lines().find_map(|l| {
127 let l = l.trim().strip_prefix("Source: '")?;
128 let (file, rest) = l.split_once('\'')?;
129 let range = rest
130 .trim()
131 .trim_start_matches(',')
132 .trim()
133 .strip_prefix("lines ")?;
134 let (a, b) = range.split_once('-')?;
135 Some((file.to_string(), parse_pos(a)?, parse_pos(b)?))
136 });
137 let end = body.find("\nend ").unwrap_or(body.len());
138 out.push(AeneasDecl {
139 lean,
140 rust,
141 loop_index,
142 source,
143 body: body[..end].to_string(),
144 });
145 }
146 out
147}
148
149pub fn aeneas_unit(path: &str, crate_ident: &str) -> Option<String> {
154 let rest = path.strip_prefix(crate_ident)?.strip_prefix("::")?;
155 let last = |s: &str| -> String {
156 let s = s.split('<').next().unwrap_or(s).trim();
157 s.rsplit("::").next().unwrap_or(s).to_string()
158 };
159 if let Some(open) = rest.find('{') {
160 let close = rest[open..].find('}')? + open;
161 let module = rest[..open].trim_end_matches("::");
162 let inner = &rest[open + 1..close];
163 let after = rest[close + 1..].strip_prefix("::")?;
164 if after.contains('{') {
165 return None;
166 }
167 let mut s = String::from("crate");
168 if !module.is_empty() {
169 s.push_str("::");
170 s.push_str(module);
171 }
172 if let Some(imp) = inner.strip_prefix("impl ") {
173 let (tr, ty) = imp.split_once(" for ")?;
174 s.push_str(&format!("::<{} as {}>::{after}", last(ty), last(tr)));
175 } else {
176 s.push_str(&format!("::{}::{after}", last(inner)));
177 }
178 Some(s)
179 } else {
180 Some(format!("crate::{rest}"))
181 }
182}
183
184const LEAN_KEYWORDS: &[&str] = &[
185 "at",
186 "by",
187 "do",
188 "else",
189 "end",
190 "fun",
191 "have",
192 "if",
193 "in",
194 "let",
195 "match",
196 "then",
197 "with",
198 "show",
199 "from",
200 "where",
201 "def",
202 "theorem",
203 "open",
204 "import",
205 "namespace",
206 "section",
207 "for",
208 "unless",
209 "return",
210 "mut",
211 "deriving",
212 "instance",
213 "structure",
214 "class",
215 "inductive",
216 "variable",
217 "universe",
218 "example",
219 "abbrev",
220 "axiom",
221 "local",
222 "true",
223 "false",
224];
225
226pub fn lean_ident(s: &str) -> String {
228 if LEAN_KEYWORDS.contains(&s) {
229 format!("«{s}»")
230 } else {
231 s.to_string()
232 }
233}
234
235pub const RESERVED_LABELS: &[&str] = &["obligation", "proof", "rs", "impl", "csimp", "spec"];
237
238fn identifiers(text: &str) -> BTreeSet<String> {
240 let mut out = BTreeSet::new();
241 let mut cur = String::new();
242 let mut quoted = false;
243 for c in text.chars() {
244 if quoted {
245 cur.push(c);
246 if c == '»' {
247 quoted = false;
248 }
249 continue;
250 }
251 if c == '«' {
252 cur.push(c);
253 quoted = true;
254 } else if c.is_alphanumeric() || c == '_' || c == '.' || c == '\'' {
255 cur.push(c);
256 } else if !cur.is_empty() {
257 out.insert(std::mem::take(&mut cur));
258 }
259 }
260 if !cur.is_empty() {
261 out.insert(cur);
262 }
263 out
264}
265
266pub fn reachable_units(decls: &[AeneasDecl], root: &str, crate_ident: &str) -> BTreeSet<String> {
269 let by_name: BTreeMap<&str, &AeneasDecl> = decls.iter().map(|d| (d.lean.as_str(), d)).collect();
270 let mut seen: BTreeSet<&str> = BTreeSet::new();
271 let mut stack = vec![root];
272 let mut units = BTreeSet::new();
273 while let Some(n) = stack.pop() {
274 if !seen.insert(n) {
275 continue;
276 }
277 let Some(d) = by_name.get(n) else { continue };
278 if let Some(u) = d.rust.as_deref().and_then(|r| aeneas_unit(r, crate_ident)) {
279 units.insert(u);
280 }
281 for id in identifiers(&d.body) {
282 let mut cand = id.as_str();
283 loop {
284 if let Some((k, _)) = by_name.get_key_value(cand) {
285 stack.push(k);
286 break;
287 }
288 match cand.rfind('.') {
289 Some(i) => cand = &cand[..i],
290 None => break,
291 }
292 }
293 }
294 }
295 units
296}
297
298#[derive(Debug, Clone, PartialEq)]
301struct AeneasLoop {
302 name: String,
303 path: Vec<usize>,
304 end: Option<(usize, usize)>,
305 file: Option<String>,
306}
307
308fn aeneas_loops(decls: &[AeneasDecl], lean: &str) -> Vec<AeneasLoop> {
311 let mut out = Vec::new();
312 for d in decls {
313 if d.loop_index.is_none() {
314 continue;
315 }
316 let Some(suffix) = d.lean.strip_prefix(lean) else {
317 continue;
318 };
319 let path = if suffix == "_loop" {
320 Some(vec![0])
321 } else {
322 let mut path = Vec::new();
323 let mut ok = !suffix.is_empty();
324 for part in suffix.split("_loop").skip(1) {
325 match part.parse::<usize>() {
326 Ok(n) => path.push(n),
327 Err(_) => ok = false,
328 }
329 }
330 if suffix.split("_loop").next() != Some("") {
331 ok = false;
332 }
333 ok.then_some(path)
334 };
335 if let Some(path) = path {
336 out.push(AeneasLoop {
337 name: d.lean.clone(),
338 path,
339 end: d.source.as_ref().map(|s| s.2),
340 file: d.source.as_ref().map(|s| s.0.clone()),
341 });
342 }
343 }
344 out.sort_by(|a, b| a.path.cmp(&b.path));
345 out
346}
347
348fn show_rust_tree(nodes: &[LoopNode], depth: usize, out: &mut String) {
349 for n in nodes {
350 match n {
351 LoopNode::Loop {
352 label,
353 line,
354 children,
355 ..
356 } => {
357 let l = label
358 .as_deref()
359 .map(|l| format!("'{l}"))
360 .unwrap_or("(no label)".into());
361 let _ = writeln!(out, "{}{l} (line {line})", " ".repeat(depth + 1));
362 show_rust_tree(children, depth + 1, out);
363 }
364 LoopNode::Macro { start, .. } => {
365 let _ = writeln!(
366 out,
367 "{}macro call (line {})",
368 " ".repeat(depth + 1),
369 start.0
370 );
371 }
372 }
373 }
374}
375
376fn in_span(p: (usize, usize), start: (usize, usize), end: (usize, usize)) -> bool {
377 p >= start && p <= end
378}
379
380fn macro_spans(nodes: &[LoopNode], out: &mut Vec<(Pos, Pos)>) {
381 for n in nodes {
382 match n {
383 LoopNode::Macro { start, end } => out.push((*start, *end)),
384 LoopNode::Loop { children, .. } => macro_spans(children, out),
385 }
386 }
387}
388
389fn match_loops(
391 nodes: &[LoopNode],
392 loops: &[AeneasLoop],
393 prefix: &[usize],
394 labels: &mut Vec<String>,
395 out: &mut Vec<(Vec<String>, String)>,
396) -> bool {
397 let rust: Vec<&LoopNode> = nodes
398 .iter()
399 .filter(|n| matches!(n, LoopNode::Loop { .. }))
400 .collect();
401 let mut children: Vec<&AeneasLoop> = loops
402 .iter()
403 .filter(|l| l.path.len() == prefix.len() + 1 && l.path.starts_with(prefix))
404 .collect();
405 children.sort_by_key(|l| l.path[prefix.len()]);
406 if rust.len() != children.len() {
407 return false;
408 }
409 for (r, a) in rust.iter().zip(children) {
410 let LoopNode::Loop {
411 label,
412 children: rc,
413 ..
414 } = r
415 else {
416 continue;
417 };
418 labels.push(label.clone().unwrap_or_default());
419 out.push((labels.clone(), a.name.clone()));
420 let ok = match_loops(rc, loops, &a.path, labels, out);
421 labels.pop();
422 if !ok {
423 return false;
424 }
425 }
426 true
427}
428
429pub fn loop_aliases(
431 f: &ModelFn,
432 decls: &[AeneasDecl],
433 lean: &str,
434) -> Result<Vec<(Vec<String>, String)>, String> {
435 fn unlabeled(nodes: &[LoopNode]) -> Option<(usize, usize)> {
436 for n in nodes {
437 if let LoopNode::Loop {
438 label,
439 line,
440 column,
441 children,
442 } = n
443 {
444 if label.is_none() {
445 return Some((*line, *column));
446 }
447 if let Some(p) = unlabeled(children) {
448 return Some(p);
449 }
450 }
451 }
452 None
453 }
454 if let Some((line, col)) = unlabeled(&f.loops) {
455 return Err(format!(
456 "{}:{line}:{col}: a loop of the modelled function {} has no label; add one (`'name: for ..`) to name it in Lean",
457 f.file, f.rust
458 ));
459 }
460 let mut spans = Vec::new();
461 macro_spans(&f.loops, &mut spans);
462 let all = aeneas_loops(decls, lean);
463 let in_macro: Vec<&AeneasLoop> = all
464 .iter()
465 .filter(|l| {
466 l.file
467 .as_deref()
468 .is_some_and(|x| x == f.file || x.ends_with(&format!("/{}", f.file)))
469 && l.end
470 .is_some_and(|e| spans.iter().any(|(s, t)| in_span(e, *s, *t)))
471 })
472 .collect();
473 let loops: Vec<AeneasLoop> = all
474 .iter()
475 .filter(|l| !in_macro.iter().any(|m| l.path.starts_with(&m.path)))
476 .cloned()
477 .collect();
478 let mut out = Vec::new();
479 if !match_loops(&f.loops, &loops, &[], &mut Vec::new(), &mut out) || out.len() != loops.len() {
480 let mut rust = String::new();
481 show_rust_tree(&f.loops, 0, &mut rust);
482 let mut lean_tree = String::new();
483 for l in &all {
484 let _ = writeln!(lean_tree, "{}{}", " ".repeat(l.path.len()), l.name);
485 }
486 return Err(format!(
487 "{}:{}: the loops of {} do not match its Lean model\n Rust:\n{rust} Aeneas:\n{lean_tree}",
488 f.file, f.line, f.rust
489 ));
490 }
491 for (labels, _) in &out {
492 if let Some(r) = labels
493 .iter()
494 .find(|l| RESERVED_LABELS.contains(&l.as_str()))
495 {
496 return Err(format!(
497 "{}:{}: the loop label '{r} of {} is reserved; rename it",
498 f.file, f.line, f.rust
499 ));
500 }
501 }
502 Ok(out)
503}
504
505#[derive(Debug, Clone)]
509pub struct Spec {
510 pub lean: String,
512 pub boolean: bool,
514 pub named: Vec<String>,
516}
517
518pub fn lean_params(f: &ModelFn) -> Vec<String> {
520 f.sig.params.iter().map(|p| lean_ident(&p.name)).collect()
521}
522
523fn result_parts(f: &ModelFn, res: &str) -> Vec<String> {
524 let n = usize::from(f.sig.ret.is_some()) + f.sig.muts().len();
525 match n {
526 0 => Vec::new(),
527 1 => vec![res.to_string()],
528 _ => (0..n)
529 .map(|i| {
530 let mut s = format!("{res}{}", ".2".repeat(i));
531 if i + 1 < n {
532 s.push_str(".1");
533 }
534 s
535 })
536 .collect(),
537 }
538}
539
540fn spec_call(spec: &Spec, args: &[String]) -> String {
541 let mut all: Vec<&str> = vec![spec.lean.as_str()];
542 all.extend(args.iter().map(String::as_str));
543 all.extend(spec.named.iter().map(String::as_str));
544 all.join(" ")
545}
546
547fn applied(spec: &Spec, args: &[String]) -> String {
548 let call = spec_call(spec, args);
549 if spec.boolean {
550 format!("{call} = true")
551 } else {
552 call
553 }
554}
555
556#[derive(Debug, Clone, Default)]
560pub struct GenericParts {
561 pub binders: String,
562 pub insts: Vec<String>,
563}
564
565pub fn obligation_statement(
569 f: &ModelFn,
570 lean: &str,
571 label: &str,
572 spec: &Spec,
573 requires: Option<&Spec>,
574 generic: &GenericParts,
575) -> String {
576 let params = lean_params(f);
577 let binders = if params.is_empty() {
578 String::new()
579 } else {
580 format!("∀ {}, ", params.join(" "))
581 };
582 let pre = requires
583 .map(|r| format!("{} → ", applied(r, ¶ms)))
584 .unwrap_or_default();
585 let mut call_args = generic.insts.clone();
586 call_args.extend(params.iter().cloned());
587 let call = if call_args.is_empty() {
588 lean.to_string()
589 } else {
590 format!("{lean} {}", call_args.join(" "))
591 };
592 let mut res = "res".to_string();
593 while params.contains(&res) {
594 res.push('\'');
595 }
596 let body = if label.split('.').next() == Some("refines") {
597 let s = if params.is_empty() && spec.named.is_empty() {
598 spec.lean.clone()
599 } else {
600 format!("({})", spec_call(spec, ¶ms))
601 };
602 format!("{call} = ok {s}")
603 } else {
604 let mut args = params.clone();
605 args.extend(result_parts(f, &res));
606 format!("{call} ⦃ {res} => {} ⦄", applied(spec, &args))
607 };
608 format!("{}{binders}{pre}{body}", generic.binders)
609}
610
611#[derive(Debug, Clone, PartialEq)]
615pub struct Binder {
616 pub name: String,
617 pub ty: String,
618 pub implicit: bool,
620}
621
622pub fn decl_binders(body: &str) -> Vec<Binder> {
625 let Some(start) = body.find("def ") else {
626 return Vec::new();
627 };
628 let rest = &body[start + 4..];
629 let rest = rest.trim_start();
630 let name_end = rest
631 .find(|c: char| c.is_whitespace() || c == '(' || c == '{' || c == '[' || c == ':')
632 .unwrap_or(rest.len());
633 let mut chars = rest[name_end..].chars().peekable();
634 let mut out = Vec::new();
635 loop {
636 while chars.peek().is_some_and(|c| c.is_whitespace()) {
637 chars.next();
638 }
639 let Some(&open) = chars.peek() else { break };
640 if !matches!(open, '(' | '{' | '[') {
641 break;
642 }
643 chars.next();
644 let mut depth = 1;
645 let mut text = String::new();
646 for c in chars.by_ref() {
647 if c == '(' || c == '{' || c == '[' {
648 depth += 1;
649 } else if c == ')' || c == '}' || c == ']' {
650 depth -= 1;
651 if depth == 0 {
652 break;
653 }
654 }
655 text.push(c);
656 }
657 let Some((names, ty)) = text.split_once(':') else {
658 continue;
659 };
660 let ty = ty.split_whitespace().collect::<Vec<_>>().join(" ");
661 for n in names.split_whitespace() {
662 out.push(Binder {
663 name: n.to_string(),
664 ty: ty.clone(),
665 implicit: open == '{',
666 });
667 }
668 }
669 out
670}
671
672pub fn law_classes(trait_struct: &str) -> Option<(&'static [&'static str], &'static str)> {
675 Some(match trait_struct {
676 "core.cmp.PartialEq" => (&["DecidableEq"], "LeanRust.PartialEqModel"),
677 "core.cmp.Eq" => (&["DecidableEq"], "LeanRust.PartialEqModel"),
678 "core.cmp.PartialOrd" => (&["Preorder", "DecidableRel"], "LeanRust.PartialOrdModel"),
679 "core.cmp.Ord" => (&["LinearOrder"], "LeanRust.OrdModel"),
680 "core.clone.Clone" => (&[], "LeanRust.CloneModel"),
681 "core.marker.Copy" => (&[], ""),
682 "core.default.Default" => (&["Inhabited"], "LeanRust.DefaultModel"),
683 _ => return None,
684 })
685}
686
687pub fn generic_parts(binders: &[Binder], values: &[String]) -> Result<GenericParts, String> {
691 let mut params: Vec<(String, Vec<&'static str>)> = Vec::new();
692 let mut insts = Vec::new();
693 let mut hyps = Vec::new();
694 for b in binders {
695 if b.implicit {
696 if b.ty.starts_with("Type") {
697 params.push((b.name.clone(), Vec::new()));
698 }
699 continue;
700 }
701 if values.contains(&b.name) {
702 continue;
703 }
704 let mut words = b.ty.split_whitespace();
705 let Some(head) = words.next() else { continue };
706 let args: Vec<&str> = words.collect();
707 let Some(first) = args.first() else { continue };
708 let Some(p) = params.iter_mut().find(|(n, _)| n == first) else {
709 continue;
710 };
711 let Some((classes, law)) = law_classes(head) else {
712 return Err(format!(
713 "the trait bound `{}` has no law class (LeanRust.*Model): use `obligations = per_instance`",
714 b.ty
715 ));
716 };
717 if args.iter().any(|a| a != first) {
718 return Err(format!(
719 "the trait bound `{}` relates two types: use `obligations = per_instance`",
720 b.ty
721 ));
722 }
723 for c in classes {
724 if !p.1.contains(c) {
725 p.1.push(c);
726 }
727 }
728 insts.push(b.name.clone());
729 let target = if head == "core.cmp.Eq" {
730 format!("{}.partialEqInst", b.name)
731 } else {
732 b.name.clone()
733 };
734 let hyp = if law.is_empty() {
735 String::new()
736 } else {
737 format!(" [{law} {target}]")
738 };
739 hyps.push(format!("({} : {}){hyp}", b.name, b.ty));
740 }
741 let mut text = String::new();
742 for (n, classes) in ¶ms {
743 let _ = write!(text, "{{{n} : Type}} ");
744 let linear = classes.contains(&"LinearOrder");
745 let preorder = classes.contains(&"Preorder");
746 if linear {
747 let _ = write!(text, "[LinearOrder {n}] ");
748 } else if preorder {
749 let _ = write!(text, "[Preorder {n}] [DecidableRel (α := {n}) (· ≤ ·)] ");
750 }
751 if classes.contains(&"DecidableEq") && !linear {
752 let _ = write!(text, "[DecidableEq {n}] ");
753 }
754 if classes.contains(&"Inhabited") {
755 let _ = write!(text, "[Inhabited {n}] ");
756 }
757 }
758 for h in &hyps {
759 text.push_str(h);
760 text.push(' ');
761 }
762 Ok(GenericParts {
763 binders: if text.is_empty() {
764 String::new()
765 } else {
766 format!("∀ {}, ", text.trim_end())
767 },
768 insts,
769 })
770}
771
772pub fn library_type(rust: &str) -> Option<&'static str> {
775 Some(match rust {
776 "u8" => "U8",
777 "u16" => "U16",
778 "u32" => "U32",
779 "u64" => "U64",
780 "u128" => "U128",
781 "usize" => "Usize",
782 "i8" => "I8",
783 "i16" => "I16",
784 "i32" => "I32",
785 "i64" => "I64",
786 "i128" => "I128",
787 "isize" => "Isize",
788 "bool" => "Bool",
789 "()" => "Unit",
790 _ => return None,
791 })
792}
793
794pub fn library_instance(trait_struct: &str, rust: &str) -> Option<String> {
797 let ty = library_type(rust)?;
798 let ok = match ty {
799 "Bool" => matches!(
800 trait_struct,
801 "core.cmp.PartialEq" | "core.clone.Clone" | "core.marker.Copy"
802 ),
803 "Unit" => trait_struct == "core.cmp.PartialEq",
804 _ => law_classes(trait_struct).is_some(),
805 };
806 ok.then(|| format!("{trait_struct}{ty}"))
807}
808
809pub const LEAN_HEADER: &str = "-- Generated by cargo leanfran. Do not edit.\n";
810
811pub const AENEAS_MODEL_MODULE: &str = "LeanRustGen.Lib.AeneasModel";
813
814pub fn model_module(crate_ident: &str) -> String {
816 format!("LeanRustGen.Model.{crate_ident}.Funs")
817}
818
819pub fn module_of(prefix: &str, crate_ident: &str, module: &[String]) -> String {
821 let mut s = format!("LeanRustGen.{prefix}.{crate_ident}");
822 for m in module {
823 s.push('.');
824 s.push_str(&lean_ident(m));
825 }
826 s
827}
828
829pub fn module_path(module: &str) -> std::path::PathBuf {
831 let mut p = std::path::PathBuf::new();
832 for c in module.split('.') {
833 p.push(c.trim_start_matches('«').trim_end_matches('»'));
834 }
835 p.set_extension("lean");
836 p
837}
838
839pub fn rust_extern(
842 f: &ModelFn,
843 self_path: Option<&str>,
844 trait_path: Option<&str>,
845 types: &[String],
846) -> String {
847 let fish = |ts: &[String]| {
848 if ts.is_empty() {
849 String::new()
850 } else {
851 format!("::<{}>", ts.join(", "))
852 }
853 };
854 let (outer, own) = types.split_at(f.sig.impl_generics.min(types.len()));
855 let (outer, own) = (fish(outer), fish(own));
856 let mut module = String::from("crate");
857 for m in &f.module {
858 module.push_str("::");
859 module.push_str(m);
860 }
861 let path = match (self_path, trait_path) {
862 (Some(t), Some(tr)) => format!("<{t}{outer} as {tr}>::{}{own}", f.name),
863 (Some(t), None) => format!("{t}{outer}::{}{own}", f.name),
864 _ => format!("{module}::{}{own}", f.name),
865 };
866 let modes: Vec<&str> = f
867 .sig
868 .params
869 .iter()
870 .map(|p| match p.mode {
871 Mode::Value => "_",
872 Mode::Ref => "&",
873 Mode::RefMut => "&mut",
874 })
875 .collect();
876 let unit = if f.sig.ret.is_none() && !f.sig.muts().is_empty() {
877 "->()"
878 } else {
879 ""
880 };
881 format!("rs:{path}({}){unit}", modes.join(","))
882}
883
884pub fn crate_instance(funs: &str, trait_struct: &str, rust: &str) -> Option<String> {
887 let ty = rust.rsplit("::").next()?.split('<').next()?;
888 for line in funs.lines() {
889 let Some(rest) = line.strip_prefix("def ") else {
890 continue;
891 };
892 let Some((name, sig)) = rest.split_once(" : ") else {
893 continue;
894 };
895 let mut words = sig.split_whitespace();
896 if words.next() != Some(trait_struct) {
897 continue;
898 }
899 let Some(arg) = words.next() else { continue };
900 if arg.rsplit('.').next() == Some(ty) {
901 return Some(name.trim().to_string());
902 }
903 }
904 None
905}