Skip to content

Commit cb26fc1

Browse files
committed
Deglobalize FUNC_SPECIALIZE
1 parent 948e129 commit cb26fc1

File tree

11 files changed

+107
-127
lines changed

11 files changed

+107
-127
lines changed

binding-generator/src/bin/settings-cleanup.rs

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ struct FunctionFinder<'tu, 'f> {
1818
pub func_cfg_attr_unused: RefCell<&'f mut HashSet<&'static str>>,
1919
pub func_unsafe_unused: RefCell<&'f mut HashSet<FuncId<'static>>>,
2020
pub func_replace_unused: RefCell<&'f mut HashSet<FuncId<'static>>>,
21-
pub func_specialize_unused: RefCell<&'f mut HashSet<FuncId<'static>>>,
2221
pub argument_override_unused: RefCell<&'f mut HashSet<FuncId<'static>>>,
2322
}
2423

@@ -32,7 +31,6 @@ impl<'tu, 'f> FunctionFinder<'tu, 'f> {
3231
self.func_cfg_attr_unused.borrow_mut().remove(identifier.as_str());
3332
self.func_unsafe_unused.borrow_mut().remove(&func_id);
3433
self.func_replace_unused.borrow_mut().remove(&func_id);
35-
self.func_specialize_unused.borrow_mut().remove(&func_id);
3634
self.argument_override_unused.borrow_mut().remove(&func_id);
3735
}
3836
}
@@ -93,7 +91,6 @@ fn main() {
9391
let mut func_cfg_attr_unused = settings::FUNC_CFG_ATTR.keys().copied().collect::<HashSet<_>>();
9492
let mut func_unsafe_unused = settings::FUNC_UNSAFE.clone();
9593
let mut func_replace_unused = settings::FUNC_REPLACE.keys().cloned().collect::<HashSet<_>>();
96-
let mut func_specialize_unused = settings::FUNC_SPECIALIZE.keys().cloned().collect::<HashSet<_>>();
9794
let mut argument_override_unused = settings::ARGUMENT_OVERRIDE.keys().cloned().collect::<HashSet<_>>();
9895
for opencv_header_dir in opencv_header_dirs {
9996
println!("Processing header dir: {}", opencv_header_dir.display());
@@ -120,7 +117,6 @@ fn main() {
120117
func_cfg_attr_unused: RefCell::new(&mut func_cfg_attr_unused),
121118
func_unsafe_unused: RefCell::new(&mut func_unsafe_unused),
122119
func_replace_unused: RefCell::new(&mut func_replace_unused),
123-
func_specialize_unused: RefCell::new(&mut func_specialize_unused),
124120
argument_override_unused: RefCell::new(&mut argument_override_unused),
125121
});
126122
});
@@ -136,11 +132,6 @@ fn main() {
136132
show(func_unsafe_unused);
137133
println!("Unused entries in settings::FUNC_REPLACE ({}):", func_replace_unused.len());
138134
show(func_replace_unused);
139-
println!(
140-
"Unused entries in settings::FUNC_SPECIALIZE ({}):",
141-
func_specialize_unused.len()
142-
);
143-
show(func_specialize_unused);
144135
println!(
145136
"Unused entries in settings::ARGUMENT_OVERRIDE ({}):",
146137
argument_override_unused.len()

binding-generator/src/class.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -337,12 +337,14 @@ impl<'tu, 'ge> Class<'tu, 'ge> {
337337
} else {
338338
func
339339
};
340-
if func.is_generic() {
341-
if let Some(specs) = settings::FUNC_SPECIALIZE.get(&func.func_id()) {
342-
for spec in specs {
343-
out.push(func.clone().specialize(spec));
340+
if let Self::Clang { gen_env, .. } = self {
341+
if func.is_generic() {
342+
if let Some(specs) = gen_env.settings.func_specialize.get(&func.func_id()) {
343+
for spec in specs {
344+
out.push(func.clone().specialize(spec));
345+
}
346+
return ControlFlow::Continue(());
344347
}
345-
return ControlFlow::Continue(());
346348
}
347349
}
348350
out.push(func);

binding-generator/src/func.rs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::borrow::Cow;
22
use std::borrow::Cow::{Borrowed, Owned};
3-
use std::collections::HashMap;
43
use std::fmt;
54
use std::ops::ControlFlow;
65
use std::rc::Rc;
@@ -18,8 +17,8 @@ use crate::debug::{DefinitionLocation, LocationName};
1817
use crate::element::ExcludeKind;
1918
use crate::entity::ToEntity;
2019
use crate::field::FieldDesc;
21-
use crate::settings::{TypeRefFactory, ARG_OVERRIDE_SELF};
22-
use crate::type_ref::{Constness, CppNameStyle, TypeRefDesc, TypeRefTypeHint};
20+
use crate::settings::{FuncSpec, ARG_OVERRIDE_SELF};
21+
use crate::type_ref::{Constness, CppNameStyle, FishStyle, TypeRefDesc, TypeRefTypeHint};
2322
use crate::writer::rust_native::element::RustElement;
2423
use crate::writer::rust_native::type_ref::TypeRefExt;
2524
use crate::{
@@ -87,10 +86,11 @@ impl<'tu, 'ge> Func<'tu, 'ge> {
8786
}
8887
}
8988

90-
pub fn specialize(self, spec: &HashMap<&str, TypeRefFactory>) -> Self {
89+
pub fn specialize(self, spec: &FuncSpec) -> Self {
9190
let specialized = |type_ref: &TypeRef| -> Option<TypeRef<'static, 'static>> {
9291
if type_ref.kind().is_generic() {
9392
spec
93+
.1
9494
.get(type_ref.source().cpp_name(CppNameStyle::Declaration).as_ref())
9595
.map(|spec_type| type_ref.map(|_| spec_type().with_inherent_constness(type_ref.constness())))
9696
} else {
@@ -121,16 +121,21 @@ impl<'tu, 'ge> Func<'tu, 'ge> {
121121
FuncKind::GenericInstanceMethod(cls) => FuncKind::InstanceMethod(cls),
122122
kind => kind,
123123
};
124-
let spec_values = spec.values();
124+
let spec_values = spec.1.values();
125125
let mut generic = String::with_capacity(spec_values.len() * 16);
126126
for spec in spec_values {
127-
let spec = spec();
128-
generic.extend_sep(", ", &spec.cpp_name(CppNameStyle::Reference));
127+
generic.extend_sep(", ", &spec().cpp_name(CppNameStyle::Reference));
129128
}
130129
let mut desc = self.to_desc(InheritConfig::empty().kind().arguments().return_type_ref());
130+
let rust_custom_leafname = Some(if spec.0.contains('+') {
131+
spec.0.replacen('+', &self.rust_leafname(FishStyle::No), 1).into()
132+
} else {
133+
spec.0.into()
134+
});
131135
let desc_mut = Rc::make_mut(&mut desc);
132136
desc_mut.kind = kind;
133137
desc_mut.type_hint = FuncTypeHint::Specialized;
138+
desc_mut.rust_custom_leafname = rust_custom_leafname;
134139
desc_mut.arguments = arguments;
135140
desc_mut.return_type_ref = specialized(&return_type_ref).unwrap_or_else(|| return_type_ref.into_owned());
136141
desc_mut.cpp_body = FuncCppBody::ManualCall(format!("{{{{name}}}}<{generic}>({{{{args}}}})").into());

binding-generator/src/generator.rs

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use clang::{Clang, Entity, EntityKind, Index};
1010
use dunce::canonicalize;
1111
use shlex::Shlex;
1212

13+
use crate::name_pool::NamePool;
1314
use crate::type_ref::{CppNameStyle, FishStyle, TypeRef, TypeRefKind};
1415
use crate::typedef::NewTypedefResult;
1516
use crate::writer::rust_native::element::RustElement;
@@ -81,6 +82,7 @@ pub struct OpenCvWalker<'tu, 'r, V> {
8182
module: &'r str,
8283
opencv_module_header_dir: &'r Path,
8384
visitor: V,
85+
func_names: NamePool,
8486
gen_env: GeneratorEnv<'tu>,
8587
}
8688

@@ -135,10 +137,8 @@ impl<'tu, V: GeneratorVisitor<'tu>> EntityWalkerVisitor<'tu> for OpenCvWalker<'t
135137
| EntityKind::ClassTemplatePartialSpecialization
136138
| EntityKind::StructDecl => Self::process_class(&mut self.visitor, &mut self.gen_env, entity),
137139
EntityKind::EnumDecl => Self::process_enum(&mut self.visitor, entity),
138-
EntityKind::FunctionDecl => Self::process_func(&mut self.visitor, &mut self.gen_env, entity),
139-
EntityKind::TypedefDecl | EntityKind::TypeAliasDecl => {
140-
Self::process_typedef(&mut self.visitor, &mut self.gen_env, entity)
141-
}
140+
EntityKind::FunctionDecl => Self::process_func(&mut self.visitor, &mut self.func_names, &self.gen_env, entity),
141+
EntityKind::TypedefDecl | EntityKind::TypeAliasDecl => Self::process_typedef(&mut self.visitor, &self.gen_env, entity),
142142
EntityKind::VarDecl => {
143143
if !entity.is_mutable() {
144144
Self::process_const(&mut self.visitor, entity);
@@ -210,6 +210,7 @@ impl<'tu, 'r, V: GeneratorVisitor<'tu>> OpenCvWalker<'tu, 'r, V> {
210210
module,
211211
opencv_module_header_dir,
212212
visitor,
213+
func_names: NamePool::with_capacity(512),
213214
gen_env,
214215
}
215216
}
@@ -271,51 +272,42 @@ impl<'tu, 'r, V: GeneratorVisitor<'tu>> OpenCvWalker<'tu, 'r, V> {
271272
}
272273
}
273274

274-
fn process_func(visitor: &mut V, gen_env: &mut GeneratorEnv<'tu>, func_decl: Entity<'tu>) {
275+
fn process_func(visitor: &mut V, func_names: &mut NamePool, gen_env: &GeneratorEnv<'tu>, func_decl: Entity<'tu>) {
275276
if let Some(e) = gen_env.get_export_config(func_decl) {
276277
let func = Func::new(func_decl, gen_env);
277-
let func = if let Some(func_fact) = settings::FUNC_REPLACE.get(&func.func_id()) {
278+
let func_id = func.func_id();
279+
let func: Func = if let Some(func_fact) = settings::FUNC_REPLACE.get(&func_id) {
278280
func_fact(&func)
279281
} else {
280-
func
282+
Func::new(func_decl, gen_env)
281283
};
282284
if func.exclude_kind().is_included() {
283-
let func_id = func.func_id().make_static();
284-
let mut processor = |spec| {
285-
let func = if e.only_generated_types {
286-
Func::new(func_decl, gen_env)
287-
} else {
288-
let mut name = Func::new(func_decl, gen_env).rust_leafname(FishStyle::No).into_owned().into();
289-
let mut rust_custom_leafname = None;
290-
if gen_env.func_names.make_unique_name(&mut name).is_changed() {
291-
rust_custom_leafname = Some(name.into());
292-
}
293-
Func::new_ext(func_decl, rust_custom_leafname, gen_env)
294-
};
295-
let func = if let Some(spec) = spec {
296-
func.specialize(spec)
297-
} else {
298-
func
299-
};
285+
let mut processor = |mut func: Func<'tu, '_>| {
300286
func.generated_types().into_iter().for_each(|dep| {
301287
visitor.visit_generated_type(dep);
302288
});
303289
if !e.only_generated_types {
290+
let mut name = func.rust_leafname(FishStyle::No).into_owned().into();
291+
let mut rust_custom_leafname = None;
292+
if func_names.make_unique_name(&mut name).is_changed() {
293+
rust_custom_leafname = Some(name.into());
294+
}
295+
func.set_rust_custom_leafname(rust_custom_leafname);
304296
visitor.visit_func(func);
305297
}
306298
};
307-
if let Some(specs) = settings::FUNC_SPECIALIZE.get(&func_id) {
299+
if let Some(specs) = gen_env.settings.func_specialize.get(&func_id) {
308300
for spec in specs {
309-
processor(Some(spec));
301+
processor(func.clone().specialize(spec));
310302
}
311303
} else {
312-
processor(None);
304+
processor(func);
313305
}
314306
}
315307
}
316308
}
317309

318-
fn process_typedef(visitor: &mut V, gen_env: &mut GeneratorEnv<'tu>, typedef_decl: Entity<'tu>) {
310+
fn process_typedef(visitor: &mut V, gen_env: &GeneratorEnv<'tu>, typedef_decl: Entity<'tu>) {
319311
let typedef = Typedef::try_new(typedef_decl, gen_env);
320312
if typedef.exclude_kind().is_included() {
321313
match typedef {

binding-generator/src/generator_env.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use crate::settings::Settings;
1515
use crate::type_ref::CppNameStyle;
1616
use crate::{
1717
is_opencv_path, opencv_module_from_path, settings, Class, Element, EntityWalkerExt, EntityWalkerVisitor, MemoizeMap,
18-
MemoizeMapExt, NamePool,
18+
MemoizeMapExt,
1919
};
2020

2121
#[derive(Copy, Clone, Debug)]
@@ -173,7 +173,6 @@ impl<'tu> EntityWalkerVisitor<'tu> for GeneratorEnvPopulator<'tu, '_> {
173173
pub struct GeneratorEnv<'tu> {
174174
export_map: HashMap<ExportIdx, ExportConfig>,
175175
rename_map: HashMap<ExportIdx, RenameConfig>,
176-
pub func_names: NamePool,
177176
/// Collection of function comments to be able to replace `@overload` and `@copybrief` comment markers
178177
func_comments: HashMap<String, Vec<(u32, String)>>,
179178
/// Cache of the calculated [ClassKind]s
@@ -187,7 +186,6 @@ impl<'tu> GeneratorEnv<'tu> {
187186
Self {
188187
export_map: HashMap::new(),
189188
rename_map: HashMap::new(),
190-
func_names: NamePool::with_capacity(0),
191189
func_comments: HashMap::new(),
192190
class_kind_cache: MemoizeMap::new(HashMap::new()),
193191
descendants: HashMap::new(),
@@ -200,7 +198,6 @@ impl<'tu> GeneratorEnv<'tu> {
200198
let mut out = Self {
201199
export_map: HashMap::with_capacity(1024),
202200
rename_map: HashMap::with_capacity(64),
203-
func_names: NamePool::with_capacity(512),
204201
func_comments: HashMap::with_capacity(2048),
205202
class_kind_cache: MemoizeMap::new(HashMap::with_capacity(32)),
206203
descendants: HashMap::with_capacity(16),
@@ -366,7 +363,6 @@ impl fmt::Debug for GeneratorEnv<'_> {
366363
f.debug_struct("GeneratorEnv")
367364
.field("export_map", &format!("{} elements", self.export_map.len()))
368365
.field("rename_map", &format!("{} elements", self.rename_map.len()))
369-
.field("func_names", &format!("{} elements", self.func_names.len()))
370366
.field("func_comments", &format!("{} elements", self.func_comments.len()))
371367
.field(
372368
"class_kind_cache",

binding-generator/src/name_pool.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,6 @@ impl NamePool {
1414
}
1515
}
1616

17-
pub fn len(&self) -> usize {
18-
self.names.len()
19-
}
20-
2117
pub fn make_unique_name(&mut self, name: &mut Cow<str>) -> MakeUniqueNameResult {
2218
let mut out = MakeUniqueNameResult::Unchanged;
2319
while self.names.contains(name.as_ref()) {

binding-generator/src/settings.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ pub use element_export_tweak::ELEMENT_EXPORT_TWEAK;
99
pub use force_infallible::FORCE_INFALLIBLE;
1010
pub use func_cfg_attr::FUNC_CFG_ATTR;
1111
pub use func_exclude::FUNC_EXCLUDE;
12-
pub use func_inject::{func_inject_factory, FuncFactory};
12+
pub use func_inject::{func_inject_factory, FuncFactory, FuncInject};
1313
pub use func_rename::FUNC_RENAME;
1414
pub use func_replace::{FuncInheritFactory, FUNC_REPLACE};
15-
pub use func_specialize::{TypeRefFactory, FUNC_SPECIALIZE};
15+
pub use func_specialize::{func_specialize_factory, FuncSpec, FuncSpecialize};
1616
pub use func_unsafe::FUNC_UNSAFE;
1717
pub use generator_module_tweaks::{generator_module_tweaks_factory, ModuleTweak};
1818
pub use implemented::{
@@ -21,6 +21,8 @@ pub use implemented::{
2121
};
2222
use once_cell::sync::Lazy;
2323

24+
use crate::type_ref::TypeRef;
25+
2426
mod argument_names;
2527
mod argument_override;
2628
mod element_exclude_kind;
@@ -36,24 +38,29 @@ mod func_unsafe;
3638
mod generator_module_tweaks;
3739
mod implemented;
3840

41+
pub type TypeRefFactory = fn() -> TypeRef<'static, 'static>;
42+
3943
/// Injectable global and module level overrides, todo: migrate the global statics to this over time
4044
#[derive(Debug)]
4145
pub struct Settings {
42-
pub func_inject: Vec<FuncFactory>,
46+
pub func_inject: FuncInject,
47+
pub func_specialize: FuncSpecialize,
4348
pub generator_module_tweaks: ModuleTweak<'static>,
4449
}
4550

4651
impl Settings {
4752
pub fn empty() -> Self {
4853
Self {
4954
func_inject: vec![],
55+
func_specialize: HashMap::new(),
5056
generator_module_tweaks: ModuleTweak::empty(),
5157
}
5258
}
5359

5460
pub fn for_module(module: &str) -> Self {
5561
Self {
5662
func_inject: func_inject_factory(module),
63+
func_specialize: func_specialize_factory(module),
5764
generator_module_tweaks: generator_module_tweaks_factory(module),
5865
}
5966
}

binding-generator/src/settings/func_inject.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@ use crate::type_ref::{TypeRef, TypeRefDesc, TypeRefTypeHint};
88
use crate::writer::rust_native::type_ref::Lifetime;
99
use crate::Func;
1010

11+
pub type FuncInject = Vec<FuncFactory>;
12+
1113
pub type FuncFactory = fn() -> Func<'static, 'static>;
1214

13-
pub fn func_inject_factory(module: &str) -> Vec<FuncFactory> {
15+
pub fn func_inject_factory(module: &str) -> FuncInject {
1416
match module {
1517
"core" => vec![
1618
(|| {

binding-generator/src/settings/func_rename.rs

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,6 @@ pub static FUNC_RENAME: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
4444
("cv_AsyncArray_get_const_const__OutputArrayR_int64_t", "+_with_timeout"),
4545
("cv_AsyncArray_wait_for_const_double", "+_f64"),
4646
("cv_Cholesky_floatX_size_t_int_floatX_size_t_int", "+_f32"),
47-
("cv_CommandLineParser_get_bool_const_const_StringR_bool", "+_bool"),
48-
("cv_CommandLineParser_get_bool_const_int_bool", "+_bool_idx"),
49-
("cv_CommandLineParser_get_cv_String_const_const_StringR_bool", "+_str"),
50-
("cv_CommandLineParser_get_cv_String_const_int_bool", "+_str_idx"),
51-
("cv_CommandLineParser_get_double_const_const_StringR_bool", "+_f64"),
52-
("cv_CommandLineParser_get_double_const_int_bool", "+_f64_idx"),
53-
("cv_CommandLineParser_get_int_const_const_StringR_bool", "+_i32"),
54-
("cv_CommandLineParser_get_int_const_int_bool", "+_i32_idx"),
55-
("cv_CommandLineParser_get_uint64_t_const_const_StringR_bool", "+_u64"),
56-
("cv_CommandLineParser_get_uint64_t_const_int_bool", "+_u64_idx"),
5747
("cv_DMatch_DMatch_int_int_int_float", "new_index"),
5848
("cv_FileStorage_write_const_StringR_const_MatR", "+_mat"),
5949
("cv_FileStorage_write_const_StringR_const_StringR", "+_str"),
@@ -333,14 +323,7 @@ pub static FUNC_RENAME: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
333323
("cv_dnn_DictValue_DictValue_int", "from_i32"),
334324
("cv_dnn_DictValue_DictValue_int64_t", "from_i64"),
335325
("cv_dnn_DictValue_DictValue_unsigned_int", "from_u32"),
336-
("cv_dnn_DictValue_get_cv_String_const_int", "+_str"),
337-
("cv_dnn_DictValue_get_double_const_int", "+_f64"),
338-
("cv_dnn_DictValue_get_int64_t_const_int", "+_i64"),
339-
("cv_dnn_DictValue_get_int_const_int", "+_i32"),
340326
("cv_dnn_Dict_ptr_const_StringR", "+_mut"),
341-
("cv_dnn_Dict_set_const_cv_String_const_StringR_const_StringR", "+_str"),
342-
("cv_dnn_Dict_set_const_double_const_StringR_const_doubleR", "+_f64"),
343-
("cv_dnn_Dict_set_const_int64_t_const_StringR_const_int64_tR", "+_i64"),
344327
("cv_dnn_Layer_finalize_const_vectorLMatGR", "+_mat"),
345328
("cv_dnn_Layer_finalize_const_vectorLMatGR_vectorLMatGR", "+_mat_to"),
346329
("cv_dnn_Layer_forward_vectorLMatXGR_vectorLMatGR_vectorLMatGR", "+_mat"),

0 commit comments

Comments
 (0)