opencv_binding_generator/
function.rs

1use std::borrow::Cow;
2use std::fmt;
3
4use clang::{Entity, EntityKind, EntityVisitResult, Type};
5
6use crate::type_ref::CppNameStyle;
7use crate::{CowMapBorrowedExt, Element, Field, GeneratorEnv, IteratorExt, TypeRef};
8
9#[derive(Clone)]
10pub struct Function<'tu, 'ge> {
11	type_ref: Type<'tu>,
12	parent_entity: Entity<'tu>,
13	gen_env: &'ge GeneratorEnv<'tu>,
14}
15
16impl<'tu, 'ge> Function<'tu, 'ge> {
17	pub fn new(type_ref: Type<'tu>, parent_entity: Entity<'tu>, gen_env: &'ge GeneratorEnv<'tu>) -> Self {
18		Self {
19			type_ref,
20			parent_entity,
21			gen_env,
22		}
23	}
24
25	pub fn arguments(&self) -> Vec<Field<'tu, 'ge>> {
26		let mut out = Vec::with_capacity(10);
27		self.parent_entity.visit_children(|c, _| {
28			if c.get_kind() == EntityKind::ParmDecl {
29				out.push(Field::new(c, self.gen_env));
30			}
31			EntityVisitResult::Continue
32		});
33		out
34	}
35
36	pub fn return_type(&self) -> TypeRef<'tu, 'ge> {
37		TypeRef::new(self.type_ref.get_result_type().expect("Can't get result type"), self.gen_env)
38	}
39}
40
41impl Element for Function<'_, '_> {
42	fn is_system(&self) -> bool {
43		false
44	}
45
46	fn is_public(&self) -> bool {
47		true
48	}
49
50	fn doc_comment(&self) -> Cow<'_, str> {
51		"".into()
52	}
53
54	fn cpp_namespace(&self) -> Cow<'_, str> {
55		"<unset>".into()
56	}
57
58	fn cpp_name(&self, _style: CppNameStyle) -> Cow<'_, str> {
59		let args = self
60			.arguments()
61			.iter()
62			.map(|a| {
63				a.type_ref()
64					.map_borrowed(|tref| tref.cpp_name_ext(CppNameStyle::Reference, "", false))
65			})
66			.join(", ");
67		let ret = self.return_type();
68		format!("{ret} (*)({args})", args = args, ret = ret.cpp_name(CppNameStyle::Reference)).into()
69	}
70}
71
72impl PartialEq for Function<'_, '_> {
73	fn eq(&self, other: &Self) -> bool {
74		self.type_ref == other.type_ref && self.parent_entity == other.parent_entity
75	}
76}
77
78impl fmt::Display for Function<'_, '_> {
79	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
80		write!(f, "{}", self.cpp_name(CppNameStyle::Reference))
81	}
82}
83
84impl fmt::Debug for Function<'_, '_> {
85	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
86		let mut debug_struct = f.debug_struct("Function");
87		self
88			.update_debug_struct(&mut debug_struct)
89			.field("arguments", &self.arguments())
90			.finish()
91	}
92}