opencv_binding_generator/writer/rust_native/
mod.rs1use std::collections::HashMap;
2use std::fmt::Debug;
3use std::fs::{File, OpenOptions};
4use std::io::{BufWriter, ErrorKind, Write};
5use std::path::{Path, PathBuf};
6use std::{fs, io, iter};
7
8use class::ClassExt;
9use comment::RenderComment;
10use dunce::canonicalize;
11use element::{RustElement, RustNativeGeneratedElement};
12use func::FuncExt;
13use once_cell::sync::Lazy;
14pub use string_ext::RustStringExt;
15
16use crate::comment::strip_doxygen_comment_markers;
17use crate::field::Field;
18use crate::name_pool::NamePool;
19use crate::type_ref::{Constness, CppNameStyle, FishStyle, NameStyle};
20use crate::{
21 opencv_module_from_path, settings, Class, CompiledInterpolation, Const, Element, Enum, Func, GeneratedType, GeneratorVisitor,
22 IteratorExt, StrExt, Typedef,
23};
24
25mod abstract_ref_wrapper;
26mod class;
27mod comment;
28mod constant;
29pub mod element;
30mod enumeration;
31mod field;
32mod func;
33mod function;
34pub mod renderer;
35mod smart_ptr;
36mod string_ext;
37mod tuple;
38pub mod type_ref;
39mod typedef;
40mod vector;
41
42type Entries = Vec<(String, String)>;
43type UniqueEntries = HashMap<String, String>;
44
45#[derive(Clone, Debug)]
47pub struct RustNativeBindingWriter<'s> {
48 debug: bool,
49 src_cpp_dir: PathBuf,
50 module: &'s str,
51 opencv_version: &'s str,
52 debug_path: PathBuf,
53 out_dir: PathBuf,
54 comment: String,
55 prelude_traits: Vec<String>,
56 consts: Entries,
57 enums: Entries,
58 rust_funcs: Entries,
59 rust_typedefs: UniqueEntries,
60 rust_classes: Entries,
61 extern_funcs: Entries,
62 extern_classes: Entries,
63 cpp_funcs: Entries,
64 cpp_classes: Entries,
65}
66
67impl<'s> RustNativeBindingWriter<'s> {
68 pub fn new(src_cpp_dir: &Path, out_dir: impl Into<PathBuf>, module: &'s str, opencv_version: &'s str, debug: bool) -> Self {
69 let out_dir = out_dir.into();
70 let debug_path = out_dir.join(format!("{module}.log"));
71 #[allow(clippy::collapsible_if)]
72 if false {
73 if debug {
74 File::create(&debug_path).expect("Can't create debug log");
75 }
76 }
77 Self {
78 debug,
79 src_cpp_dir: canonicalize(src_cpp_dir).expect("Can't canonicalize src_cpp_dir"),
80 module,
81 opencv_version,
82 debug_path,
83 out_dir,
84 comment: String::new(),
85 prelude_traits: vec![],
86 consts: vec![],
87 enums: vec![],
88 rust_funcs: vec![],
89 rust_typedefs: UniqueEntries::new(),
90 rust_classes: vec![],
91 extern_funcs: vec![],
92 extern_classes: vec![],
93 cpp_funcs: vec![],
94 cpp_classes: vec![],
95 }
96 }
97
98 fn emit_debug_log(&mut self, obj: &impl Debug) {
99 #[allow(clippy::collapsible_if)]
100 if false {
101 if self.debug {
102 let mut f = OpenOptions::new()
103 .append(true)
104 .open(&self.debug_path)
105 .expect("Can't open debug file");
106 writeln!(f, "{obj:#?}").expect("Can't write debug info");
107 }
108 }
109 }
110}
111
112impl GeneratorVisitor<'_> for RustNativeBindingWriter<'_> {
113 fn wants_file(&mut self, path: &Path) -> bool {
114 opencv_module_from_path(path) == Some(self.module)
115 }
116
117 fn visit_module_comment(&mut self, comment: String) {
118 self.comment = strip_doxygen_comment_markers(&comment);
119 }
120
121 fn visit_const(&mut self, cnst: Const) {
122 self.emit_debug_log(&cnst);
123 self.consts.push((
124 cnst.rust_name(NameStyle::decl()).into_owned(),
125 cnst.gen_rust(self.opencv_version),
126 ));
127 }
128
129 fn visit_enum(&mut self, enm: Enum) {
130 self.emit_debug_log(&enm);
131 self.enums.push((
132 enm.rust_name(NameStyle::decl()).into_owned(),
133 enm.gen_rust(self.opencv_version),
134 ));
135 }
136
137 fn visit_func(&mut self, func: Func) {
138 self.emit_debug_log(&func);
139 for func in func.with_companion_functions() {
140 let name = func.identifier();
141 self.rust_funcs.push((name.clone(), func.gen_rust(self.opencv_version)));
142 self.extern_funcs.push((name.clone(), func.gen_rust_externs()));
143 self.cpp_funcs.push((name, func.gen_cpp()));
144 }
145 }
146
147 fn visit_typedef(&mut self, typedef: Typedef) {
148 self.emit_debug_log(&typedef);
149 let opencv_version = self.opencv_version;
150 let cpp_refname = typedef.cpp_name(CppNameStyle::Reference);
151 if !self.rust_typedefs.contains_key(cpp_refname.as_ref()) {
152 self
153 .rust_typedefs
154 .insert(cpp_refname.into_owned(), typedef.gen_rust(opencv_version));
155 }
156 }
157
158 fn visit_class(&mut self, class: Class) {
159 self.emit_debug_log(&class);
160 if class.kind().is_trait() {
161 self
162 .prelude_traits
163 .push(class.rust_trait_name(NameStyle::decl(), Constness::Const).into_owned());
164 self
165 .prelude_traits
166 .push(class.rust_trait_name(NameStyle::decl(), Constness::Mut).into_owned());
167 }
168 let name = class.cpp_name(CppNameStyle::Reference).into_owned();
169 self.rust_classes.push((name.clone(), class.gen_rust(self.opencv_version)));
170 self.extern_classes.push((name.clone(), class.gen_rust_externs()));
171 self.cpp_classes.push((name, class.gen_cpp()));
172 }
173
174 fn visit_generated_type(&mut self, typ: GeneratedType) {
175 let typ = typ.as_ref();
176 let safe_id = typ.element_safe_id();
177
178 fn write_generated_type(types_dir: &Path, typ: &str, safe_id: &str, generator: impl FnOnce() -> String) {
179 let suffix = format!(".type.{typ}");
180 let mut file_name = format!("050-{safe_id}");
181 ensure_filename_length(&mut file_name, suffix.len());
182 file_name.push_str(&suffix);
183 let path = types_dir.join(file_name);
184 let file = OpenOptions::new().create_new(true).write(true).open(&path);
185 match file {
186 Ok(mut file) => {
187 let gen = generator();
188 if !gen.is_empty() {
189 file
190 .write_all(gen.as_bytes())
191 .unwrap_or_else(|e| panic!("Can't write to {typ} file: {e}"));
192 } else {
193 drop(file);
194 fs::remove_file(&path).expect("Can't remove empty file");
195 }
196 }
197 Err(e) if e.kind() == ErrorKind::AlreadyExists => { }
198 Err(e) if e.kind() == ErrorKind::PermissionDenied => { }
199 Err(e) => panic!("Error while creating file: {} for {typ} generated type: {e}", path.display()),
200 }
201 }
202
203 write_generated_type(&self.out_dir, "rs", &safe_id, || typ.gen_rust(self.opencv_version));
204 write_generated_type(&self.out_dir, "externs.rs", &safe_id, || typ.gen_rust_externs());
205 write_generated_type(&self.out_dir, "cpp", &safe_id, || typ.gen_cpp());
206 }
207
208 fn goodbye(mut self) {
209 static RUST_HDR: Lazy<CompiledInterpolation> =
210 Lazy::new(|| include_str!("tpl/module/rust_hdr.tpl").compile_interpolation());
211
212 static RUST_PRELUDE: Lazy<CompiledInterpolation> =
213 Lazy::new(|| include_str!("tpl/module/prelude.tpl.rs").compile_interpolation());
214
215 static CPP_HDR: Lazy<CompiledInterpolation> =
216 Lazy::new(|| include_str!("tpl/module/cpp_hdr.tpl.cpp").compile_interpolation());
217
218 let pub_use_traits = if self.prelude_traits.is_empty() {
219 "".to_string()
220 } else {
221 self.prelude_traits.sort_unstable();
222 format!("pub use super::{{{}}};", self.prelude_traits.join(", "))
223 };
224 let prelude = RUST_PRELUDE.interpolate(&HashMap::from([("pub_use_traits", pub_use_traits)]));
225 let comment = RenderComment::new(&self.comment, self.opencv_version);
226 let comment = comment.render_with_comment_marker("//!");
227 let rust_path = self.out_dir.join(format!("{}.rs", self.module));
228 {
229 let mut rust = BufWriter::new(File::create(rust_path).expect("Can't create rust file"));
230 rust
231 .write_all(
232 RUST_HDR
233 .interpolate(&HashMap::from([
234 ("static_modules", settings::STATIC_MODULES.iter().join(", ").as_str()),
235 ("comment", comment.as_ref()),
236 ("prelude", &prelude),
237 ]))
238 .as_bytes(),
239 )
240 .expect("Can't write rust file");
241 write_lines(&mut rust, self.consts).expect("Can't write consts to rust file");
242 write_lines(&mut rust, self.enums).expect("Can't write enums to rust file");
243 write_lines(&mut rust, self.rust_typedefs.into_iter().collect()).expect("Can't write typedefs to rust file");
244 write_lines(&mut rust, self.rust_funcs).expect("Can't write funcs to rust file");
245 write_lines(&mut rust, self.rust_classes).expect("Can't write classes to rust file");
246 }
247
248 let includes = if self.src_cpp_dir.join(format!("{}.hpp", self.module)).exists() {
249 format!("#include \"{}.hpp\"", self.module)
250 } else {
251 format!("#include \"ocvrs_common.hpp\"\n#include <opencv2/{}.hpp>", self.module)
252 };
253 {
254 let cpp_path = self.out_dir.join(format!("{}.cpp", self.module));
255 let mut cpp = BufWriter::new(File::create(cpp_path).expect("Can't create cpp file"));
256 cpp.write_all(
257 CPP_HDR
258 .interpolate(&HashMap::from([("module", self.module), ("includes", &includes)]))
259 .as_bytes(),
260 )
261 .expect("Can't write cpp file");
262 cpp.write_all(b"extern \"C\" {\n")
263 .expect("Can't write code wrapper begin to cpp file");
264 write_lines(&mut cpp, self.cpp_funcs).expect("Can't write cpp funcs to file");
265 write_lines(&mut cpp, self.cpp_classes).expect("Can't write cpp classes to file");
266 cpp.write_all(b"}\n").expect("Can't write code wrapper end to cpp file");
267 }
268
269 let externs_path = self.out_dir.join(format!("{}.externs.rs", self.module));
270 let mut externs_rs = BufWriter::new(File::create(externs_path).expect("Can't create rust exports file"));
271 write_lines(&mut externs_rs, self.extern_funcs).expect("Can't write extern funcs to file");
272 write_lines(&mut externs_rs, self.extern_classes).expect("Can't write extern classes to file");
273 }
274}
275
276fn write_lines<T: AsRef<[u8]>>(mut out: impl Write, mut v: Vec<(String, T)>) -> io::Result<()> {
277 v.sort_unstable_by(|(name_left, _), (name_right, _)| name_left.cmp(name_right));
278 for (_, code) in v {
279 out.write_all(code.as_ref())?;
280 }
281 Ok(())
282}
283
284fn ensure_filename_length(file_name: &mut String, reserve: usize) {
285 const MAX_FILENAME_LEN: usize = 255;
286
287 let max_length = MAX_FILENAME_LEN - reserve;
288
289 if file_name.len() > max_length {
290 *file_name = file_name[..max_length].to_string();
291 }
292}
293
294fn rust_disambiguate_names<'tu, 'ge>(
295 args: impl IntoIterator<Item = Field<'tu, 'ge>>,
296) -> impl Iterator<Item = (String, Field<'tu, 'ge>)>
297where
298 'tu: 'ge,
299{
300 let args = args.into_iter();
301 let size_hint = args.size_hint();
302 NamePool::with_capacity(size_hint.1.unwrap_or(size_hint.0)).into_disambiguator(args, |f| f.rust_leafname(FishStyle::No))
303}
304
305pub fn disambiguate_single_name(name: &str) -> impl Iterator<Item = String> + '_ {
306 let mut i = 0;
307 iter::from_fn(move || {
308 let out = format!("{}{}", name, disambiguate_num(i));
309 i += 1;
310 Some(out)
311 })
312}
313
314fn disambiguate_num(counter: usize) -> String {
315 match counter {
316 0 => "".to_string(),
317 n => format!("_{n}"),
318 }
319}