opencv_binding_generator/writer/rust_native/
func.rs

1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::fmt::Write;
4use std::iter;
5use std::iter::{Chain, Once};
6use std::rc::Rc;
7use std::sync::LazyLock;
8use std::vec::IntoIter;
9
10use Cow::{Borrowed, Owned};
11
12use super::comment::{render_ref, RenderComment};
13use super::element::{DefaultRustNativeElement, RustElement};
14use super::type_ref::{BorrowKind, Lifetime, TypeRefExt, TypeRefKindExt};
15use super::{comment, rust_disambiguate_names_ref, RustNativeGeneratedElement};
16use crate::field::Field;
17use crate::func::{FuncCppBody, FuncKind, FuncRustBody, FuncRustExtern, InheritConfig, OperatorKind, ReturnKind};
18use crate::name_pool::NamePool;
19use crate::settings::ARG_OVERRIDE_SELF;
20use crate::type_ref::{Constness, CppNameStyle, ExternDir, FishStyle, NameStyle, StrEnc, StrType, TypeRef, TypeRefTypeHint};
21use crate::writer::rust_native::class::ClassExt;
22use crate::writer::rust_native::type_ref::render_lane::FunctionProps;
23use crate::{reserved_rename, CompiledInterpolation, Element, Func, IteratorExt, NameDebug, StrExt, StringExt, SupportedModule};
24
25pub trait FuncExt<'tu, 'ge> {
26	fn companion_functions(&self) -> Vec<Func<'tu, 'ge>>;
27	fn with_companion_functions(self) -> Chain<Once<Self>, IntoIter<Self>>
28	where
29		Self: Sized;
30}
31
32impl<'tu, 'ge> FuncExt<'tu, 'ge> for Func<'tu, 'ge> {
33	fn companion_functions(&self) -> Vec<Func<'tu, 'ge>> {
34		let mut out = vec![];
35		if let Some(default_func) = companion_func_default_args(self) {
36			out.extend(default_func.companion_functions());
37			out.push(default_func);
38		}
39		out.extend(companion_func_boxref_mut(self));
40		out
41	}
42
43	fn with_companion_functions(self) -> Chain<Once<Self>, IntoIter<Self>> {
44		let companions = self.companion_functions();
45		iter::once(self).chain(companions)
46	}
47}
48
49impl RustElement for Func<'_, '_> {
50	fn rust_module(&self) -> SupportedModule {
51		match self {
52			&Self::Clang { entity, .. } => DefaultRustNativeElement::rust_module(entity),
53			Self::Desc(desc) => desc.rust_module,
54		}
55	}
56
57	fn rust_name(&self, style: NameStyle) -> Cow<'_, str> {
58		match self {
59			&Self::Clang { entity, .. } => DefaultRustNativeElement::rust_name(self, entity, style).into(),
60			Self::Desc(_) => match style {
61				NameStyle::Declaration => self.rust_leafname(FishStyle::No),
62				NameStyle::Reference(fish_style) => format!(
63					"{}::{}",
64					DefaultRustNativeElement::rust_module_reference(self),
65					self.rust_leafname(fish_style)
66				)
67				.into(),
68			},
69		}
70	}
71
72	fn rust_leafname(&self, _fish_style: FishStyle) -> Cow<'_, str> {
73		if let Some(rust_custom_leafname) = self.rust_custom_leafname() {
74			return rust_custom_leafname.into();
75		}
76		let cpp_name = match self {
77			&Self::Clang { entity, gen_env, .. } => {
78				if let Some(name) = gen_env.get_rename_config(entity).map(|c| &c.rename) {
79					Borrowed(name.as_ref())
80				} else {
81					self.cpp_name(CppNameStyle::Declaration)
82				}
83			}
84			Self::Desc(_) => self.cpp_name(CppNameStyle::Declaration),
85		};
86		let rust_name = if self.is_clone() {
87			Borrowed("try_clone")
88		} else {
89			let kind = self.kind();
90			if let Some(cls) = kind.as_constructor() {
91				let args = self.arguments();
92				let ctor_name = 'ctor_name: {
93					if args.is_empty() {
94						break 'ctor_name "default";
95					} else if args.len() == 1 {
96						let arg_typeref = args[0].type_ref();
97						let source = arg_typeref.source_smart();
98						if let Some(class_arg) = source.kind().as_class() {
99							if cls == class_arg.as_ref() {
100								break 'ctor_name if arg_typeref.constness().is_const() {
101									"copy"
102								} else {
103									"copy_mut"
104								};
105							} else if class_arg.descendants().contains(cls) {
106								break 'ctor_name "from_base";
107							}
108						}
109					}
110					"new"
111				};
112				Borrowed(ctor_name)
113			} else if kind.as_conversion_method().is_some() {
114				let mut conv_name = self.return_type_ref().rust_name(NameStyle::decl()).into_owned();
115				conv_name.cleanup_name();
116				conv_name.insert_str(0, "to_");
117				Owned(conv_name)
118			} else if let Some((cls, kind)) = kind.as_operator() {
119				if cpp_name.starts_with("operator") {
120					let op_name = match kind {
121						OperatorKind::Unsupported => cpp_name.as_ref(),
122						OperatorKind::Index => {
123							if self.constness().is_const() {
124								"get"
125							} else {
126								"get_mut"
127							}
128						}
129						OperatorKind::Add => "add",
130						OperatorKind::Sub => "sub",
131						OperatorKind::Mul => "mul",
132						OperatorKind::Div => "div",
133						OperatorKind::Apply => "apply",
134						OperatorKind::Set => "set",
135						OperatorKind::Deref => {
136							if self.constness().is_const() {
137								"try_deref"
138							} else {
139								"try_deref_mut"
140							}
141						}
142						OperatorKind::Equals => "equals",
143						OperatorKind::NotEquals => "not_equals",
144						OperatorKind::GreaterThan => "greater_than",
145						OperatorKind::GreaterThanOrEqual => "greater_than_or_equal",
146						OperatorKind::LessThan => "less_than",
147						OperatorKind::LessThanOrEqual => "less_than_or_equal",
148						OperatorKind::Incr => "incr",
149						OperatorKind::Decr => "decr",
150						OperatorKind::And => "and",
151						OperatorKind::Or => "or",
152						OperatorKind::Xor => "xor",
153						OperatorKind::BitwiseNot => "negate",
154					};
155					if kind.add_args_to_name() {
156						let args = self.arguments();
157						let args = args.as_ref();
158						let is_single_arg_same_as_class = if let (Some(cls), [single_arg]) = (cls, args) {
159							single_arg
160								.type_ref()
161								.source()
162								.kind()
163								.as_class()
164								.is_some_and(|single_class| single_class.as_ref() == cls)
165						} else {
166							false
167						};
168						if args.is_empty() || is_single_arg_same_as_class {
169							Borrowed(op_name)
170						} else {
171							let args = args.iter().map(|arg| arg.type_ref().rust_simple_name()).join("_");
172							Owned(format!("{op_name}_{args}"))
173						}
174					} else {
175						Borrowed(op_name)
176					}
177				} else {
178					cpp_name
179				}
180			} else {
181				cpp_name
182			}
183		};
184		let rust_name = reserved_rename(rust_name.cpp_name_to_rust_fn_case());
185		if let Self::Clang { gen_env, .. } = self {
186			if let Some(&name) = gen_env.settings.func_rename.get(self.identifier().as_str()) {
187				return if name.contains('+') {
188					Owned(name.replacen('+', rust_name.as_ref(), 1))
189				} else {
190					name.into()
191				};
192			}
193		}
194		Owned(rust_name.into_owned())
195	}
196
197	fn rust_doc_comment(&self, comment_marker: &str, opencv_version: &str) -> String {
198		let mut comment = RenderComment::new(self.doc_comment().into_owned(), opencv_version);
199		let args = self.arguments();
200		let (_, default_args) = split_default_args(&args);
201		let default_args_comment = comment::render_cpp_default_args(default_args);
202		if !default_args_comment.is_empty() {
203			if !comment.doc_comment.is_empty() {
204				comment.doc_comment.push_str("\n\n");
205			}
206			comment.doc_comment.push_str("## C++ default parameters\n");
207			comment.doc_comment.push_str(default_args_comment.trim_end());
208		}
209		comment.render_with_comment_marker(comment_marker).into_owned()
210	}
211}
212
213impl RustNativeGeneratedElement for Func<'_, '_> {
214	fn element_safe_id(&self) -> String {
215		format!("{}-{}", self.rust_module().opencv_name(), self.rust_name(NameStyle::decl()))
216	}
217
218	fn gen_rust(&self, opencv_version: &str) -> String {
219		static TPL: LazyLock<CompiledInterpolation> =
220			LazyLock::new(|| include_str!("tpl/func/rust.tpl.rs").compile_interpolation());
221
222		let name = self.rust_leafname(FishStyle::No);
223		let kind = self.kind();
224		let return_kind = self.return_kind();
225		let return_type_ref = self.return_type_ref();
226		let safety = self.safety();
227		let identifier = self.identifier();
228
229		let args = self.arguments();
230		let as_instance_method = kind.as_instance_method();
231		let mut decl_args = Vec::with_capacity(args.len());
232		let mut pre_call_args = Vec::with_capacity(args.len());
233		let mut call_args = Vec::with_capacity(args.len() + 1);
234		let mut forward_args = Vec::with_capacity(args.len());
235		let mut post_success_call_args = Vec::with_capacity(args.len());
236		let (return_lifetime, return_lt_from_args) = return_lifetime(&kind, &args, &return_type_ref);
237		if let Some(cls) = as_instance_method {
238			let constness = self.constness();
239			let cls_type_ref = cls.type_ref().with_inherent_constness(constness);
240			let render_lane = cls_type_ref.render_lane();
241			let render_lane = render_lane.to_dyn();
242			let lt = return_lt_from_args
243				.filter(|from_args| from_args.contains(&ARG_OVERRIDE_SELF))
244				.map_or(Lifetime::Elided, |_| return_lifetime);
245			decl_args.push(render_lane.rust_self_func_decl(lt));
246			call_args.push(render_lane.rust_arg_func_call("self"));
247		}
248		let mut callback_arg_name: Option<String> = None;
249		let function_props = FunctionProps {
250			is_infallible: return_kind.is_infallible(),
251		};
252		for (name, arg) in rust_disambiguate_names_ref(args.as_ref()) {
253			let arg_type_ref = arg.type_ref();
254			let arg_type_hint = arg_type_ref.type_hint();
255			let arg_as_slice_len = arg_type_hint.as_slice_len();
256			let arg_kind = arg_type_ref.kind();
257			let render_lane = arg_type_ref.render_lane();
258			let render_lane = render_lane.to_dyn();
259			if arg.is_user_data() {
260				pre_call_args.push_code_line_if_not_empty(format!(
261					"userdata_arg!({decl} => {callback_name})",
262					decl = arg_type_ref.render_lane().to_dyn().rust_extern_arg_func_decl(&name),
263					callback_name = callback_arg_name.as_ref().expect("Can't get name of the callback arg")
264				));
265			} else {
266				if !arg_as_slice_len.is_some() {
267					let lt = return_lt_from_args
268						.filter(|from_args| from_args.contains(&name.as_str()))
269						.map(|_| return_lifetime)
270						.or_else(|| arg_type_hint.as_explicit_lifetime())
271						.unwrap_or(Lifetime::Elided);
272					decl_args.push(render_lane.rust_arg_func_decl(&name, lt).into());
273				}
274				pre_call_args.push_code_line_if_not_empty(render_lane.rust_arg_pre_call(&name, &function_props));
275				if arg_kind.is_function() {
276					callback_arg_name = Some(name.clone());
277				}
278			}
279			if let Some((slice_args, len_div)) = arg_as_slice_len {
280				let arg_is_size_t = arg_kind.is_size_t();
281				let mut slice_len_call = String::new();
282				for slice_arg in slice_args {
283					let len_divided = if len_div > 1 {
284						format!("{slice_arg}.len() / {len_div}")
285					} else {
286						format!("{slice_arg}.len()")
287					};
288					if slice_len_call.is_empty() {
289						if len_div > 1 && (!arg_is_size_t || slice_args.len() > 1) {
290							write!(&mut slice_len_call, "({len_divided})").expect("Impossible");
291						} else {
292							slice_len_call.push_str(&len_divided);
293						}
294					} else {
295						write!(&mut slice_len_call, ".min({len_divided})").expect("Impossible");
296					}
297				}
298				if !arg_is_size_t {
299					slice_len_call.push_str(".try_into()?");
300				}
301				call_args.push(slice_len_call);
302			} else {
303				call_args.push(render_lane.rust_arg_func_call(&name));
304			}
305			post_success_call_args.push_code_line_if_not_empty(render_lane.rust_arg_post_success_call(&name));
306			forward_args.push(name);
307		}
308		if !return_kind.is_naked() {
309			call_args.push("ocvrs_return.as_mut_ptr()".to_string());
310		}
311
312		let doc_comment = self.rust_doc_comment("///", opencv_version);
313		let visibility = if let Some(cls) = as_instance_method {
314			if cls.kind().is_trait() {
315				""
316			} else {
317				"pub "
318			}
319		} else {
320			"pub "
321		};
322		let mut return_type_func_decl = return_type_ref.rust_return(FishStyle::No, return_lifetime);
323		if !return_kind.is_infallible() {
324			return_type_func_decl = format!("Result<{return_type_func_decl}>").into()
325		};
326		let return_type_func_decl = if return_type_func_decl == "()" {
327			"".to_string()
328		} else {
329			format!(" -> {return_type_func_decl}")
330		};
331		let (ret_pre_call, ret_handle, ret_stmt) = rust_return(self, &return_type_ref, return_kind, return_lifetime);
332		let mut attributes = Vec::with_capacity(2);
333		if self.is_no_discard() {
334			attributes.push(Borrowed("#[must_use]"));
335		}
336		if let Some((rust_attr, _)) = self.cfg_attrs() {
337			if !rust_attr.is_empty() {
338				attributes.push(format!("#[cfg({rust_attr})]").into());
339			}
340		}
341
342		TPL.interpolate(&HashMap::from([
343			("doc_comment", doc_comment.as_str()),
344			("debug", &self.get_debug()),
345			("attributes", &attributes.join("\n")),
346			("visibility", visibility),
347			("unsafety_decl", safety.rust_func_safety_qual()),
348			("name", name.as_ref()),
349			("generic_decl", &rust_generic_decl(self, &return_type_ref)),
350			("decl_args", &decl_args.join(", ")),
351			("rv_rust_full", &return_type_func_decl),
352			("pre_call_args", &pre_call_args.join("\n")),
353			("return_pre_call", ret_pre_call),
354			(
355				"call",
356				&rust_call(self, &identifier, &name, &call_args, &forward_args, return_kind),
357			),
358			("return_handle", &ret_handle),
359			("post_success_call_args", &post_success_call_args.join("\n")),
360			("return", ret_stmt),
361		]))
362	}
363
364	fn gen_rust_externs(&self) -> String {
365		static TPL: LazyLock<CompiledInterpolation> =
366			LazyLock::new(|| include_str!("tpl/func/rust_extern.tpl.rs").compile_interpolation());
367
368		if matches!(self.rust_extern_definition(), FuncRustExtern::Absent) {
369			return "".to_string();
370		}
371
372		let identifier = self.identifier();
373		let mut attributes = String::new();
374		if let Some((rust_attr, _)) = self.cfg_attrs() {
375			attributes = format!("#[cfg({rust_attr})]");
376		}
377		let mut args = vec![];
378		if let Some(cls) = self.kind().as_instance_method() {
379			args.push(
380				cls.type_ref()
381					.with_inherent_constness(self.constness())
382					.render_lane()
383					.to_dyn()
384					.rust_extern_arg_func_decl("instance"),
385			);
386		}
387		for (name, arg) in rust_disambiguate_names_ref(self.arguments().as_ref()) {
388			args.push(arg.type_ref().render_lane().to_dyn().rust_extern_arg_func_decl(&name))
389		}
390
391		let return_kind = self.return_kind();
392		let naked_return = return_kind.is_naked();
393		let is_infallible = return_kind.is_infallible();
394		let return_type = self.return_type_ref();
395		let return_wrapper_type = if is_infallible {
396			return_type.rust_extern(ExternDir::FromCpp)
397		} else {
398			return_type.rust_extern_return_fallible()
399		};
400		if !naked_return {
401			let ret_name = "ocvrs_return";
402			args.push(format!("{ret_name}: *mut {return_wrapper_type}"));
403		}
404		let return_type_kind = return_type.kind();
405		let return_wrapper_type = if return_type_kind.is_void() || !naked_return {
406			"".to_string()
407		} else {
408			format!(" -> {return_wrapper_type}")
409		};
410		TPL.interpolate(&HashMap::from([
411			("attributes", attributes),
412			("debug", self.get_debug()),
413			("identifier", identifier),
414			("args", args.join(", ")),
415			("return_type", return_wrapper_type),
416		]))
417	}
418
419	fn gen_cpp(&self) -> String {
420		static TPL: LazyLock<CompiledInterpolation> =
421			LazyLock::new(|| include_str!("tpl/func/cpp.tpl.cpp").compile_interpolation());
422
423		if matches!(self.cpp_body(), FuncCppBody::Absent) {
424			return "".to_string();
425		}
426
427		let identifier = self.identifier();
428
429		let kind = self.kind();
430		let return_kind = self.return_kind();
431		let return_type_ref = self.return_type_ref();
432
433		// attributes
434		let mut attributes_begin = String::new();
435		let mut attributes_end = String::new();
436		if let Some((_, cpp_attr)) = self.cfg_attrs() {
437			attributes_begin = format!("#if {cpp_attr}");
438			attributes_end = "#endif".to_string();
439		}
440
441		// arguments
442		let args = cpp_disambiguate_names(self.arguments().into_owned()).collect::<Vec<_>>();
443		let mut decl_args = Vec::with_capacity(args.len());
444		let mut pre_call_args = Vec::with_capacity(args.len());
445		let mut call_args = Vec::with_capacity(args.len());
446		let mut post_call_args = Vec::with_capacity(args.len());
447		if let Some(cls) = kind.as_instance_method() {
448			decl_args.push(
449				cls.type_ref()
450					.with_inherent_constness(self.constness())
451					.render_lane()
452					.to_dyn()
453					.cpp_arg_func_decl("instance")
454					.into_owned(),
455			);
456		}
457		for (name, arg) in &args {
458			let arg_type_ref = arg.type_ref();
459			let render_lane = arg_type_ref.render_lane();
460			let render_lane = render_lane.to_dyn();
461			decl_args.push(render_lane.cpp_arg_func_decl(name).into_owned());
462			pre_call_args.push_code_line_if_not_empty(render_lane.cpp_arg_pre_call(name));
463			call_args.push(render_lane.cpp_arg_func_call(name));
464			post_call_args.push_code_line_if_not_empty(render_lane.cpp_arg_post_call(name));
465		}
466
467		// return
468		let ocv_ret_name = "ocvrs_return";
469		let cpp_extern_return = return_type_ref.cpp_extern_return();
470		let ret_full = if return_kind.is_infallible() {
471			cpp_extern_return
472		} else {
473			return_type_ref.cpp_extern_return_fallible()
474		};
475		let return_type_ref_mut = return_type_ref.as_ref().clone().with_inherent_constness(Constness::Mut);
476		let ret_wrapper_full_mut = if return_kind.is_infallible() {
477			return_type_ref_mut.cpp_extern_return()
478		} else {
479			return_type_ref_mut.cpp_extern_return_fallible()
480		};
481		if !return_kind.is_naked() {
482			decl_args.push(format!("{ret_wrapper_full_mut}* {ocv_ret_name}"));
483		}
484		let return_spec = if return_kind.is_naked() {
485			Borrowed(ret_full.as_ref())
486		} else {
487			"void".into()
488		};
489		let (ret, ret_cast) = cpp_return_map(&return_type_ref, "ret", kind.as_constructor().is_some());
490
491		// exception handling
492		let func_try = if return_kind.is_infallible() {
493			""
494		} else {
495			"try {"
496		};
497		let catch = if return_kind.is_infallible() {
498			"".to_string()
499		} else {
500			format!("}} OCVRS_CATCH({ocv_ret_name});")
501		};
502
503		TPL.interpolate(&HashMap::from([
504			("attributes_begin", attributes_begin.as_str()),
505			("debug", &self.get_debug()),
506			("return_spec", &return_spec),
507			("identifier", &identifier),
508			("decl_args", &decl_args.join(", ")),
509			("try", func_try),
510			("pre_call_args", &pre_call_args.join("\n")),
511			("call", &cpp_call(self, &kind, &call_args, &return_type_ref)),
512			("post_call_args", &post_call_args.join("\n")),
513			(
514				"return",
515				&cpp_return(self, return_kind, &ret, ret_cast.then(|| ret_full.as_ref()), ocv_ret_name),
516			),
517			("catch", &catch),
518			("attributes_end", &attributes_end),
519		]))
520	}
521}
522
523fn rust_call(
524	f: &Func,
525	identifier: &str,
526	func_name: &str,
527	call_args: &[String],
528	forward_args: &[String],
529	return_kind: ReturnKind,
530) -> String {
531	#![allow(clippy::too_many_arguments)]
532	static CALL_TPL: LazyLock<CompiledInterpolation> =
533		LazyLock::new(|| "{{ret_receive}}unsafe { sys::{{identifier}}({{call_args}}) };".compile_interpolation());
534
535	let ret_receive = if return_kind.is_naked() {
536		"let ret = "
537	} else {
538		""
539	};
540	let tpl = match f.rust_body() {
541		FuncRustBody::Auto => Borrowed(&*CALL_TPL),
542		FuncRustBody::ManualCall(body) | FuncRustBody::ManualCallReturn(body) => Owned(body.compile_interpolation()),
543	};
544	tpl.interpolate(&HashMap::from([
545		("ret_receive", ret_receive),
546		("identifier", identifier),
547		("name", func_name),
548		("call_args", &call_args.join(", ")),
549		("forward_args", &forward_args.join(", ")),
550	]))
551}
552
553fn return_lifetime(
554	func_kind: &FuncKind,
555	args: &[Field],
556	return_type_ref: &TypeRef,
557) -> (Lifetime, Option<&'static [&'static str]>) {
558	if let Some((_, args, lifetime)) = return_type_ref.type_hint().as_boxed_as_ref() {
559		(lifetime, Some(args))
560	} else {
561		let lt = match return_type_ref.rust_lifetime_count() {
562			0 => Lifetime::Elided,
563			1 => {
564				let borrow_kind_from_any_arg = func_kind
565					.as_instance_method()
566					.into_iter()
567					.map(|cls| Owned(cls.type_ref()))
568					.chain(args.iter().map(|arg| arg.type_ref()))
569					.fold(BorrowKind::Impossible, |a, arg_type_ref| {
570						a.more_complicated(arg_type_ref.kind().rust_borrow_kind(arg_type_ref.type_hint()))
571					});
572				match borrow_kind_from_any_arg {
573					BorrowKind::FromPointer => return_type_ref
574						.kind()
575						.as_class()
576						.and_then(|cls| cls.rust_lifetime())
577						.unwrap_or(Lifetime::automatic()),
578					BorrowKind::FromLifetime => Lifetime::Elided,
579					BorrowKind::Impossible => Lifetime::statik(),
580				}
581			}
582			2.. => panic!("Rendering of more than 1 lifetime in the function return type is not yet supported"),
583		};
584		(lt, None)
585	}
586}
587
588fn rust_return(
589	f: &Func,
590	return_type_ref: &TypeRef,
591	return_kind: ReturnKind,
592	lifetime: Lifetime,
593) -> (&'static str, String, &'static str) {
594	match f.rust_body() {
595		FuncRustBody::Auto | FuncRustBody::ManualCall(_) => {
596			let ret_pre = if !return_kind.is_naked() {
597				"return_send!(via ocvrs_return);"
598			} else {
599				""
600			};
601
602			let mut ret_convert = Vec::with_capacity(3);
603			if !return_kind.is_naked() {
604				ret_convert.push(Borrowed("return_receive!(ocvrs_return => ret);"));
605			}
606			if !return_kind.is_infallible() {
607				ret_convert.push("let ret = ret.into_result()?;".into())
608			}
609			let ret_map = rust_return_map(return_type_ref, "ret", return_kind, lifetime);
610			if !ret_map.is_empty() {
611				ret_convert.push(format!("let ret = {ret_map};").into());
612			}
613
614			let ret_stmt = if return_kind.is_infallible() {
615				"ret"
616			} else {
617				"Ok(ret)"
618			};
619			(ret_pre, ret_convert.join("\n"), ret_stmt)
620		}
621		FuncRustBody::ManualCallReturn(_) => ("", "".to_string(), ""),
622	}
623}
624
625fn rust_return_map(return_type: &TypeRef, ret_name: &str, return_kind: ReturnKind, lifetime: Lifetime) -> Cow<'static, str> {
626	let return_type_kind = return_type.kind();
627	if return_type_kind.as_string(return_type.type_hint()).is_some() || return_type_kind.extern_pass_kind().is_by_void_ptr() {
628		format!(
629			"unsafe {{ {typ}::opencv_from_extern({ret_name}) }}",
630			typ = return_type.rust_return(FishStyle::Turbo, lifetime),
631		)
632		.into()
633	} else if return_type_kind.as_pointer().is_some_and(|i| !i.kind().is_void())
634		&& !return_type_kind.is_rust_by_ptr(return_type.type_hint())
635		|| return_type_kind.as_fixed_array().is_some()
636	{
637		let ptr_call = if return_type.constness().is_const() {
638			"as_ref"
639		} else {
640			"as_mut"
641		};
642		let error_handling = if return_kind.is_infallible() {
643			".expect(\"Function returned null pointer\")"
644		} else {
645			".ok_or_else(|| Error::new(core::StsNullPtr, \"Function returned null pointer\"))?"
646		};
647		format!("unsafe {{ {ret_name}.{ptr_call}() }}{error_handling}").into()
648	} else {
649		"".into()
650	}
651}
652
653fn cpp_call(f: &Func, kind: &FuncKind, call_args: &[String], return_type_ref: &TypeRef) -> String {
654	static CALL_TPL: LazyLock<CompiledInterpolation> = LazyLock::new(|| "{{name}}({{args}})".compile_interpolation());
655
656	static VOID_TPL: LazyLock<CompiledInterpolation> = LazyLock::new(|| "{{call}};".compile_interpolation());
657
658	static RETURN_TPL: LazyLock<CompiledInterpolation> =
659		LazyLock::new(|| "{{ret_with_type}} = {{doref}}{{call}};".compile_interpolation());
660
661	static CONSTRUCTOR_TPL: LazyLock<CompiledInterpolation> =
662		LazyLock::new(|| "{{ret_with_type}}({{args}});".compile_interpolation());
663
664	static CONSTRUCTOR_NO_ARGS_TPL: LazyLock<CompiledInterpolation> =
665		LazyLock::new(|| "{{ret_with_type}};".compile_interpolation());
666
667	static BOXED_CONSTRUCTOR_TPL: LazyLock<CompiledInterpolation> =
668		LazyLock::new(|| "{{ret_type}}* ret = new {{ret_type}}({{args}});".compile_interpolation());
669
670	let call_args = call_args.join(", ");
671
672	let return_type_kind = return_type_ref.kind();
673	let ret_type = return_type_ref.cpp_name(CppNameStyle::Reference);
674	let ret_with_type = return_type_ref.cpp_name_ext(CppNameStyle::Reference, "ret", true);
675	let doref = if return_type_kind.as_fixed_array().is_some() {
676		"&"
677	} else {
678		""
679	};
680
681	let call_name = match kind {
682		FuncKind::Constructor(cls) => cls.cpp_name(CppNameStyle::Reference),
683		FuncKind::Function | FuncKind::GenericFunction | FuncKind::StaticMethod(..) | FuncKind::FunctionOperator(..) => {
684			f.cpp_name(CppNameStyle::Reference)
685		}
686		FuncKind::FieldAccessor(cls, fld) => cpp_method_call_name(
687			cls.type_ref().kind().extern_pass_kind().is_by_ptr(),
688			&fld.cpp_name(CppNameStyle::Declaration),
689		)
690		.into(),
691		FuncKind::InstanceMethod(cls)
692		| FuncKind::GenericInstanceMethod(cls)
693		| FuncKind::ConversionMethod(cls)
694		| FuncKind::InstanceOperator(cls, ..) => cpp_method_call_name(
695			cls.type_ref().kind().extern_pass_kind().is_by_ptr(),
696			&f.cpp_name(CppNameStyle::Declaration),
697		)
698		.into(),
699	};
700
701	let mut inter_vars = HashMap::from([
702		("ret_type", ret_type),
703		("ret_with_type", ret_with_type),
704		("doref", doref.into()),
705		("args", call_args.as_str().into()),
706		("name", call_name),
707	]);
708
709	let (call_tpl, full_tpl) = match f.cpp_body() {
710		FuncCppBody::Auto => {
711			if let Some(cls) = kind.as_constructor() {
712				if cls.kind().is_boxed() {
713					(None, Some(Borrowed(&*BOXED_CONSTRUCTOR_TPL)))
714				} else if call_args.is_empty() {
715					(None, Some(Borrowed(&*CONSTRUCTOR_NO_ARGS_TPL)))
716				} else {
717					(None, Some(Borrowed(&*CONSTRUCTOR_TPL)))
718				}
719			} else {
720				(Some(Borrowed(&*CALL_TPL)), None)
721			}
722		}
723		FuncCppBody::ManualCall(call) => (Some(Owned(call.compile_interpolation())), None),
724		FuncCppBody::ManualCallReturn(full_tpl) => (None, Some(Owned(full_tpl.compile_interpolation()))),
725		FuncCppBody::Absent => (None, None),
726	};
727	let tpl = full_tpl
728		.or_else(|| {
729			call_tpl.map(|call_tpl| {
730				let call = call_tpl.interpolate(&inter_vars);
731				inter_vars.insert("call", call.into());
732				if return_type_ref.kind().is_void() {
733					Borrowed(&*VOID_TPL)
734				} else {
735					Borrowed(&*RETURN_TPL)
736				}
737			})
738		})
739		.expect("Impossible");
740
741	tpl.interpolate(&inter_vars)
742}
743
744fn cpp_return(f: &Func, return_kind: ReturnKind, ret: &str, ret_cast: Option<&str>, ocv_ret_name: &str) -> Cow<'static, str> {
745	match &f.cpp_body() {
746		FuncCppBody::Auto | FuncCppBody::ManualCall(_) => match return_kind {
747			ReturnKind::InfallibleNaked => {
748				if ret.is_empty() {
749					"".into()
750				} else {
751					let cast = if let Some(ret_type) = ret_cast {
752						format!("({ret_type})")
753					} else {
754						"".to_string()
755					};
756					format!("return {cast}{ret};").into()
757				}
758			}
759			ReturnKind::InfallibleViaArg => {
760				if ret.is_empty() {
761					"".into()
762				} else {
763					format!("*{ocv_ret_name} = {ret};").into()
764				}
765			}
766			ReturnKind::Fallible => {
767				if ret.is_empty() {
768					format!("Ok({ocv_ret_name});").into()
769				} else {
770					let cast = if let Some(ret_type) = ret_cast {
771						format!("<{ret_type}>")
772					} else {
773						"".to_string()
774					};
775					format!("Ok{cast}({ret}, {ocv_ret_name});").into()
776				}
777			}
778		},
779		FuncCppBody::ManualCallReturn(_) | FuncCppBody::Absent => "".into(),
780	}
781}
782
783pub fn cpp_return_map<'f>(return_type: &TypeRef, name: &'f str, is_constructor: bool) -> (Cow<'f, str>, bool) {
784	let return_kind = return_type.kind();
785	if return_kind.is_void() {
786		("".into(), false)
787	} else if let Some((_, string_type)) = return_kind.as_string(return_type.type_hint()) {
788		let str_mk = match string_type {
789			StrType::StdString(StrEnc::Text) | StrType::CvString(StrEnc::Text) => {
790				format!("ocvrs_create_string({name}.c_str())").into()
791			}
792			StrType::StdString(StrEnc::Binary) => format!("ocvrs_create_byte_string({name}.data(), {name}.size())").into(),
793			StrType::CvString(StrEnc::Binary) => format!("ocvrs_create_byte_string({name}.begin(), {name}.size())").into(),
794			StrType::CharPtr(StrEnc::Text) => format!("ocvrs_create_string({name})").into(),
795			StrType::CharPtr(StrEnc::Binary) => panic!("Returning a byte string via char* is not supported yet"),
796		};
797		(str_mk, false)
798	} else if return_kind.extern_pass_kind().is_by_void_ptr() && !is_constructor {
799		let ret_source = return_type.source();
800		let out = ret_source.kind().as_class().filter(|cls| cls.is_abstract()).map_or_else(
801			|| {
802				// todo implement higher count if it's needed
803				let deref_count = return_type.kind().as_pointer().map_or(0, |_| 1);
804				format!(
805					"new {typ}({:*<deref_count$}{name})",
806					"",
807					typ = ret_source.cpp_name(CppNameStyle::Reference)
808				)
809				.into()
810			},
811			|_| name.into(),
812		);
813		(out, false)
814	} else {
815		(name.into(), return_kind.as_fixed_array().is_some())
816	}
817}
818
819fn cpp_method_call_name(extern_by_ptr: bool, method_name: &str) -> String {
820	if extern_by_ptr {
821		format!("instance->{method_name}")
822	} else {
823		format!("instance.{method_name}")
824	}
825}
826
827pub fn cpp_disambiguate_names<'tu, 'ge>(
828	args: impl IntoIterator<Item = Field<'tu, 'ge>>,
829) -> impl Iterator<Item = (String, Field<'tu, 'ge>)>
830where
831	'tu: 'ge,
832{
833	let args = args.into_iter();
834	let size_hint = args.size_hint();
835	NamePool::with_capacity(size_hint.1.unwrap_or(size_hint.0)).into_disambiguator(args, |f| f.cpp_name(CppNameStyle::Declaration))
836}
837
838fn rust_generic_decl<'f>(f: &'f Func, return_type_ref: &TypeRef) -> Cow<'f, str> {
839	let mut decls = vec![];
840	if let Some((_, _, lt)) = return_type_ref.type_hint().as_boxed_as_ref() {
841		decls.push(lt.to_string());
842	}
843	match f {
844		Func::Clang { .. } => {}
845		Func::Desc(desc) => {
846			decls.reserve(desc.rust_generic_decls.len());
847			for (typ, constraint) in desc.rust_generic_decls.as_ref() {
848				decls.push(format!("{typ}: {constraint}"));
849			}
850		}
851	}
852	let decls = decls.join(", ");
853	if decls.is_empty() {
854		"".into()
855	} else {
856		format!("<{decls}>").into()
857	}
858}
859
860fn viable_default_arg(arg: &Field) -> bool {
861	arg.default_value().is_some() && !arg.is_user_data() && {
862		let type_ref = arg.type_ref();
863		// don't remove the arguments that are used to pass the slice or its length
864		!matches!(
865			type_ref.type_hint(),
866			TypeRefTypeHint::Slice | TypeRefTypeHint::LenForSlice(..)
867		)
868	}
869}
870
871/// Split `arg` into 2 sub-slices, (args_without_default_value, args_with_default_value)
872///
873/// Arguments with special meanings like userdata and slice length are not included in the args_with_default_value slice.
874fn split_default_args<'a, 'tu, 'ge>(args: &'a [Field<'tu, 'ge>]) -> (&'a [Field<'tu, 'ge>], &'a [Field<'tu, 'ge>]) {
875	// default args are in the end
876	let last_non_default_arg_idx = args.iter().rposition(|arg| !viable_default_arg(arg));
877	if let Some(last_non_default_arg_idx) = last_non_default_arg_idx {
878		args.split_at(last_non_default_arg_idx + 1)
879	} else {
880		(&[], args)
881	}
882}
883
884/// Companion function with all optional arguments as defaults
885fn companion_func_default_args<'tu, 'ge>(f: &Func<'tu, 'ge>) -> Option<Func<'tu, 'ge>> {
886	if f.kind().as_field_accessor().is_some() {
887		return None;
888	}
889
890	match f {
891		Func::Clang { gen_env, .. } => {
892			if gen_env
893				.settings
894				.func_companion_tweak
895				.get(&mut f.matcher())
896				.is_some_and(|t| t.skip_default())
897			{
898				return None;
899			}
900		}
901		Func::Desc(_) => {}
902	}
903
904	let args = f.arguments();
905	let (args_without_def, args_with_def) = split_default_args(&args);
906	if args_with_def.is_empty() {
907		return None;
908	}
909	let original_rust_leafname = f.rust_leafname(FishStyle::No);
910	let mut doc_comment = f.doc_comment().into_owned();
911	let rust_leafname = format!("{original_rust_leafname}_def");
912	let default_args = comment::render_cpp_default_args(args_with_def);
913	if !doc_comment.is_empty() {
914		doc_comment.push_str("\n\n");
915	}
916	write!(
917			&mut doc_comment,
918			"## Note\nThis alternative version of [{refr}] function uses the following default values for its arguments:\n{default_args}",
919			refr = render_ref(f, Some(&original_rust_leafname))
920		)
921	.expect("Impossible");
922	let mut desc = f.to_desc_with_skip_config(InheritConfig::empty().doc_comment().arguments());
923	let desc_mut = Rc::make_mut(&mut desc);
924	desc_mut.rust_custom_leafname = Some(rust_leafname.into());
925	desc_mut.arguments = args_without_def.into();
926	desc_mut.doc_comment = doc_comment.into();
927	let out = Func::Desc(desc);
928	if out.exclude_kind().is_included() {
929		Some(out)
930	} else {
931		None
932	}
933}
934
935/// Companion function returning `BoxRefMut` for a corresponding function returning `BoxRef`
936fn companion_func_boxref_mut<'tu, 'ge>(f: &Func<'tu, 'ge>) -> Option<Func<'tu, 'ge>> {
937	let ret_type_ref = f.return_type_ref();
938	if let Some((Constness::Mut, borrow_arg_names, _)) = ret_type_ref.type_hint().as_boxed_as_ref() {
939		let mut desc = f.to_desc_with_skip_config(InheritConfig::empty());
940		let desc_mut = Rc::make_mut(&mut desc);
941		let mut cloned_args = None;
942		// Rc::make_mut doesn't work on slices
943		let args = if let Some(args) = Rc::get_mut(&mut desc_mut.arguments) {
944			args
945		} else {
946			cloned_args = Some(desc_mut.arguments.to_vec());
947			cloned_args.as_mut().unwrap()
948		};
949		let mut borrow_arg_is_const = false;
950		if borrow_arg_names.contains(&ARG_OVERRIDE_SELF) {
951			if desc_mut.kind.as_instance_method().is_some() && desc_mut.constness.is_const() {
952				borrow_arg_is_const = true;
953				desc_mut.constness = Constness::Mut;
954			}
955		} else {
956			let borrow_arg = args
957				.iter_mut()
958				.find(|arg| borrow_arg_names.contains(&arg.cpp_name(CppNameStyle::Declaration).as_ref()));
959			if let Some(borrow_arg) = borrow_arg {
960				let type_ref = borrow_arg.type_ref();
961				let kind = type_ref.kind();
962				borrow_arg_is_const = type_ref.constness().is_const()
963					&& kind
964						.as_pointer_reference_move()
965						.is_some_and(|ptr_or_ref| ptr_or_ref.kind().as_class().is_some());
966				if borrow_arg_is_const {
967					*borrow_arg = borrow_arg.clone().with_type_ref(
968						borrow_arg
969							.type_ref()
970							.map_ptr_ref(|inner| inner.clone().with_inherent_constness(Constness::Mut)),
971					);
972				}
973			}
974		}
975		if borrow_arg_is_const {
976			if let Some(args) = cloned_args {
977				desc_mut.arguments = args.into();
978			}
979			desc_mut.rust_custom_leafname = Some(format!("{}_mut", f.rust_leafname(FishStyle::No)).into());
980			desc_mut.return_type_ref.set_inherent_constness(Constness::Mut);
981			Some(Func::Desc(desc))
982		} else {
983			None
984		}
985	} else {
986		None
987	}
988}
989
990trait PrePostArgs {
991	fn push_code_line_if_not_empty(&mut self, arg: String);
992}
993
994impl PrePostArgs for Vec<String> {
995	fn push_code_line_if_not_empty(&mut self, mut arg: String) {
996		if !arg.is_empty() {
997			arg.push(';');
998			self.push(arg);
999		}
1000	}
1001}