-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathmod.rs
2372 lines (2261 loc) · 96.6 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
mod bridge_name_tracker;
pub(crate) mod function_wrapper;
mod implicit_constructors;
mod overload_tracker;
mod subclass;
use crate::{
conversion::{
analysis::{
fun::function_wrapper::{CppConversionType, CppFunctionKind},
type_converter::{self, add_analysis, TypeConversionContext, TypeConverter},
},
api::{
ApiName, CastMutability, FuncToConvert, NullPhase, Provenance, SubclassName,
TraitImplSignature, TraitSynthesis, UnsafetyNeeded,
},
apivec::ApiVec,
convert_error::{ConvertErrorWithContext, ErrorContext, ErrorContextType},
error_reporter::{convert_apis, report_any_error},
type_helpers::{type_is_reference, unwrap_has_opaque},
CppEffectiveName, CppOriginalName,
},
known_types::known_types,
minisyn::{minisynize_punctuated, FnArg},
types::validate_ident_ok_for_rust,
};
use autocxx_bindgen::callbacks::Visibility as CppVisibility;
use autocxx_bindgen::callbacks::{Explicitness, SpecialMemberKind, Virtualness};
use indexmap::map::IndexMap as HashMap;
use indexmap::set::IndexSet as HashSet;
use autocxx_parser::{ExternCppType, IncludeCppConfig, UnsafePolicy};
use function_wrapper::{CppFunction, CppFunctionBody, TypeConversionPolicy};
use itertools::Itertools;
use proc_macro2::Span;
use quote::quote;
use syn::{
parse_quote, punctuated::Punctuated, token::Comma, Ident, Pat, PatType, ReturnType, Type,
TypePath, TypePtr, TypeReference, Visibility,
};
use crate::{
conversion::{
api::{AnalysisPhase, Api, TypeKind},
ConvertErrorFromCpp,
},
types::{make_ident, validate_ident_ok_for_cxx, Namespace, QualifiedName},
};
use self::{
bridge_name_tracker::BridgeNameTracker,
function_wrapper::RustConversionType,
implicit_constructors::{find_constructors_present, ItemsFound},
overload_tracker::OverloadTracker,
subclass::{
create_subclass_constructor, create_subclass_fn_wrapper, create_subclass_function,
create_subclass_trait_item,
},
};
use super::{
depth_first::HasFieldsAndBases,
doc_label::make_doc_attrs,
pod::{PodAnalysis, PodPhase},
tdef::TypedefAnalysis,
type_converter::Annotated,
};
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub(crate) enum ReceiverMutability {
Const,
Mutable,
}
#[derive(Clone, Debug)]
pub(crate) enum MethodKind {
Normal,
Constructor { is_default: bool },
Static,
Virtual(ReceiverMutability),
PureVirtual(ReceiverMutability),
}
#[derive(Clone, Debug)]
pub(crate) enum TraitMethodKind {
CopyConstructor,
MoveConstructor,
Cast,
Destructor,
Alloc,
Dealloc,
}
#[derive(Clone, Debug)]
pub(crate) struct TraitMethodDetails {
pub(crate) trt: TraitImplSignature,
pub(crate) avoid_self: bool,
pub(crate) method_name: crate::minisyn::Ident,
/// For traits, where we're trying to implement a specific existing
/// interface, we may need to reorder the parameters to fit that
/// interface.
pub(crate) parameter_reordering: Option<Vec<usize>>,
}
#[derive(Clone, Debug)]
pub(crate) enum FnKind {
Function,
Method {
method_kind: MethodKind,
impl_for: QualifiedName,
},
TraitMethod {
kind: TraitMethodKind,
/// The name of the type T for which we're implementing a trait,
/// though we may be actually implementing the trait for &mut T or
/// similar, so we store more details of both the type and the
/// method in `details`
impl_for: QualifiedName,
details: Box<TraitMethodDetails>,
},
}
/// Strategy for ensuring that the final, callable, Rust name
/// is what the user originally expected.
#[derive(Clone, Debug)]
pub(crate) enum RustRenameStrategy {
/// cxx::bridge name matches user expectations
None,
/// Even the #[rust_name] attribute would cause conflicts, and we need
/// to use a 'use XYZ as ABC'
RenameInOutputMod(crate::minisyn::Ident),
/// This function requires us to generate a Rust function to do
/// parameter conversion.
RenameUsingWrapperFunction,
}
#[derive(Clone, Debug)]
pub(crate) struct FnAnalysis {
/// Each entry in the cxx::bridge needs to have a unique name, even if
/// (from the perspective of Rust and C++) things are in different
/// namespaces/mods.
pub(crate) cxxbridge_name: crate::minisyn::Ident,
/// ... so record also the name under which we wish to expose it in Rust.
pub(crate) rust_name: String,
/// And also the name of the underlying C++ function if it differs
/// from the cxxbridge_name.
pub(crate) cpp_call_name: Option<CppOriginalName>,
pub(crate) rust_rename_strategy: RustRenameStrategy,
pub(crate) params: Punctuated<FnArg, Comma>,
pub(crate) kind: FnKind,
pub(crate) ret_type: crate::minisyn::ReturnType,
pub(crate) param_details: Vec<ArgumentAnalysis>,
pub(crate) ret_conversion: Option<TypeConversionPolicy>,
pub(crate) requires_unsafe: UnsafetyNeeded,
pub(crate) vis: Visibility,
pub(crate) cpp_wrapper: Option<CppFunction>,
pub(crate) deps: HashSet<QualifiedName>,
/// Some methods still need to be recorded because we want
/// to (a) generate the ability to call superclasses, (b) create
/// subclass entries for them. But we do not want to have them
/// be externally callable.
pub(crate) ignore_reason: Result<(), ConvertErrorWithContext>,
/// Whether this can be called by external code. Not so for
/// protected methods.
pub(crate) externally_callable: bool,
/// Whether we need to generate a Rust-side calling function
pub(crate) rust_wrapper_needed: bool,
}
#[derive(Clone, Debug)]
pub(crate) struct ArgumentAnalysis {
pub(crate) conversion: TypeConversionPolicy,
pub(crate) name: crate::minisyn::Pat,
pub(crate) self_type: Option<(QualifiedName, ReceiverMutability)>,
pub(crate) has_lifetime: bool,
pub(crate) is_mutable_reference: bool,
pub(crate) deps: HashSet<QualifiedName>,
pub(crate) requires_unsafe: UnsafetyNeeded,
pub(crate) is_placement_return_destination: bool,
}
pub(crate) struct ReturnTypeAnalysis {
rt: ReturnType,
conversion: Option<TypeConversionPolicy>,
was_reference: bool,
was_mutable_reference: bool,
deps: HashSet<QualifiedName>,
placement_param_needed: Option<(FnArg, ArgumentAnalysis)>,
}
impl Default for ReturnTypeAnalysis {
fn default() -> Self {
Self {
rt: parse_quote! {},
conversion: None,
was_reference: false,
was_mutable_reference: false,
deps: Default::default(),
placement_param_needed: None,
}
}
}
#[derive(std::fmt::Debug)]
pub(crate) struct PodAndConstructorAnalysis {
pub(crate) pod: PodAnalysis,
pub(crate) constructors: PublicConstructors,
}
/// An analysis phase where we've analyzed each function, but
/// haven't yet determined which constructors/etc. belong to each type.
#[derive(std::fmt::Debug)]
pub(crate) struct FnPrePhase1;
impl AnalysisPhase for FnPrePhase1 {
type TypedefAnalysis = TypedefAnalysis;
type StructAnalysis = PodAnalysis;
type FunAnalysis = FnAnalysis;
}
/// An analysis phase where we've analyzed each function, and identified
/// what implicit constructors/destructors are present in each type.
#[derive(std::fmt::Debug)]
pub(crate) struct FnPrePhase2;
impl AnalysisPhase for FnPrePhase2 {
type TypedefAnalysis = TypedefAnalysis;
type StructAnalysis = PodAndConstructorAnalysis;
type FunAnalysis = FnAnalysis;
}
#[derive(Debug)]
pub(crate) struct PodAndDepAnalysis {
pub(crate) pod: PodAnalysis,
pub(crate) constructor_and_allocator_deps: Vec<QualifiedName>,
pub(crate) constructors: PublicConstructors,
}
/// Analysis phase after we've finished analyzing functions and determined
/// which constructors etc. belong to them.
#[derive(std::fmt::Debug)]
pub(crate) struct FnPhase;
/// Indicates which kinds of public constructors are known to exist for a type.
#[derive(Debug, Default, Copy, Clone)]
pub(crate) struct PublicConstructors {
pub(crate) move_constructor: bool,
pub(crate) destructor: bool,
}
impl PublicConstructors {
fn from_items_found(items_found: &ItemsFound) -> Self {
Self {
move_constructor: items_found.move_constructor.callable_any(),
destructor: items_found.destructor.callable_any(),
}
}
}
impl AnalysisPhase for FnPhase {
type TypedefAnalysis = TypedefAnalysis;
type StructAnalysis = PodAndDepAnalysis;
type FunAnalysis = FnAnalysis;
}
/// Whether to allow highly optimized calls because this is a simple Rust->C++ call,
/// or to use a simpler set of policies because this is a subclass call where
/// we may have C++->Rust->C++ etc.
#[derive(Copy, Clone)]
enum TypeConversionSophistication {
Regular,
SimpleForSubclasses,
}
pub(crate) struct FnAnalyzer<'a> {
unsafe_policy: &'a UnsafePolicy,
extra_apis: ApiVec<NullPhase>,
type_converter: TypeConverter<'a>,
bridge_name_tracker: BridgeNameTracker,
pod_safe_types: HashSet<QualifiedName>,
moveit_safe_types: HashSet<QualifiedName>,
config: &'a IncludeCppConfig,
overload_trackers_by_mod: HashMap<Namespace, OverloadTracker>,
subclasses_by_superclass: HashMap<QualifiedName, Vec<SubclassName>>,
nested_type_name_map: HashMap<QualifiedName, String>,
generic_types: HashSet<QualifiedName>,
types_in_anonymous_namespace: HashSet<QualifiedName>,
existing_superclass_trait_api_names: HashSet<QualifiedName>,
force_wrapper_generation: bool,
}
impl<'a> FnAnalyzer<'a> {
pub(crate) fn analyze_functions(
apis: ApiVec<PodPhase>,
unsafe_policy: &'a UnsafePolicy,
config: &'a IncludeCppConfig,
force_wrapper_generation: bool,
) -> ApiVec<FnPrePhase2> {
let mut me = Self {
unsafe_policy,
extra_apis: ApiVec::new(),
type_converter: TypeConverter::new(config, &apis),
bridge_name_tracker: BridgeNameTracker::new(),
config,
overload_trackers_by_mod: HashMap::new(),
pod_safe_types: Self::build_pod_safe_type_set(&apis),
moveit_safe_types: Self::build_correctly_sized_type_set(&apis),
subclasses_by_superclass: subclass::subclasses_by_superclass(&apis),
nested_type_name_map: Self::build_nested_type_map(&apis),
generic_types: Self::build_generic_type_set(&apis),
existing_superclass_trait_api_names: HashSet::new(),
types_in_anonymous_namespace: Self::build_types_in_anonymous_namespace(&apis),
force_wrapper_generation,
};
let mut results = ApiVec::new();
convert_apis(
apis,
&mut results,
|name, fun, _| me.analyze_foreign_fn_and_subclasses(name, fun),
Api::struct_unchanged,
Api::enum_unchanged,
Api::typedef_unchanged,
);
let mut results = me.add_constructors_present(results);
me.add_subclass_constructors(&mut results);
results.extend(me.extra_apis.into_iter().map(add_analysis));
results
}
fn build_pod_safe_type_set(apis: &ApiVec<PodPhase>) -> HashSet<QualifiedName> {
apis.iter()
.filter_map(|api| match api {
Api::Struct {
analysis:
PodAnalysis {
kind: TypeKind::Pod,
..
},
..
} => Some(api.name().clone()),
Api::Enum { .. } => Some(api.name().clone()),
Api::ExternCppType { pod: true, .. } => Some(api.name().clone()),
_ => None,
})
.chain(
known_types()
.get_pod_safe_types()
.filter_map(
|(tn, is_pod_safe)| {
if is_pod_safe {
Some(tn)
} else {
None
}
},
),
)
.collect()
}
/// Return the set of 'moveit safe' types. That must include only types where
/// the size is known to be correct.
fn build_correctly_sized_type_set(apis: &ApiVec<PodPhase>) -> HashSet<QualifiedName> {
apis.iter()
.filter(|api| {
matches!(
api,
Api::Struct { .. }
| Api::Enum { .. }
| Api::ExternCppType {
details: ExternCppType { opaque: false, .. },
..
}
)
})
.map(|api| api.name().clone())
.chain(known_types().get_moveit_safe_types())
.collect()
}
fn build_generic_type_set(apis: &ApiVec<PodPhase>) -> HashSet<QualifiedName> {
apis.iter()
.filter_map(|api| match api {
Api::Struct {
analysis: PodAnalysis { num_generics, .. },
..
} if *num_generics > 0 => Some(api.name().clone()),
_ => None,
})
.collect()
}
fn build_types_in_anonymous_namespace(apis: &ApiVec<PodPhase>) -> HashSet<QualifiedName> {
apis.iter()
.filter_map(|api| match api {
Api::Struct {
analysis:
PodAnalysis {
in_anonymous_namespace: true,
..
},
..
} => Some(api.name().clone()),
_ => None,
})
.collect()
}
/// Builds a mapping from a qualified type name to the last 'nest'
/// of its name, if it has multiple elements.
fn build_nested_type_map(apis: &ApiVec<PodPhase>) -> HashMap<QualifiedName, String> {
apis.iter()
.filter_map(|api| match api {
Api::Struct { name, .. } | Api::Enum { name, .. } => name
.cpp_name()
.final_segment_if_any()
.map(|suffix| (name.name.clone(), suffix.to_string())),
_ => None,
})
.collect()
}
fn convert_boxed_type(
&mut self,
ty: Box<Type>,
ns: &Namespace,
) -> Result<Annotated<Box<Type>>, ConvertErrorFromCpp> {
let ctx = TypeConversionContext::OuterType {};
let mut annotated = self.type_converter.convert_boxed_type(ty, ns, &ctx)?;
self.extra_apis.append(&mut annotated.extra_apis);
Ok(annotated)
}
fn get_cxx_bridge_name(
&mut self,
type_name: Option<&str>,
found_name: &str,
ns: &Namespace,
) -> String {
self.bridge_name_tracker
.get_unique_cxx_bridge_name(type_name, found_name, ns)
}
fn is_on_allowlist(&self, type_name: &QualifiedName) -> bool {
self.config.is_on_allowlist(&type_name.to_cpp_name())
}
fn is_generic_type(&self, type_name: &QualifiedName) -> bool {
self.generic_types.contains(type_name)
}
#[allow(clippy::if_same_then_else)] // clippy bug doesn't notice the two
// closures below are different.
fn should_be_unsafe(
&self,
param_details: &[ArgumentAnalysis],
kind: &FnKind,
) -> UnsafetyNeeded {
let unsafest_non_placement_param = UnsafetyNeeded::from_param_details(param_details, true);
let unsafest_param = UnsafetyNeeded::from_param_details(param_details, false);
match kind {
// Trait unsafety must always correspond to the norms for the
// trait we're implementing.
FnKind::TraitMethod {
kind:
TraitMethodKind::CopyConstructor
| TraitMethodKind::MoveConstructor
| TraitMethodKind::Alloc
| TraitMethodKind::Dealloc,
..
} => UnsafetyNeeded::Always,
FnKind::TraitMethod { .. } => match unsafest_param {
UnsafetyNeeded::Always => UnsafetyNeeded::JustBridge,
_ => unsafest_param,
},
_ if matches!(self.unsafe_policy, UnsafePolicy::AllFunctionsUnsafe) => {
UnsafetyNeeded::Always
}
_ => match unsafest_non_placement_param {
UnsafetyNeeded::Always => UnsafetyNeeded::Always,
UnsafetyNeeded::JustBridge => match unsafest_param {
UnsafetyNeeded::Always => UnsafetyNeeded::JustBridge,
_ => unsafest_non_placement_param,
},
UnsafetyNeeded::None => match unsafest_param {
UnsafetyNeeded::Always => UnsafetyNeeded::JustBridge,
_ => unsafest_param,
},
},
}
}
fn add_subclass_constructors(&mut self, apis: &mut ApiVec<FnPrePhase2>) {
let mut results = ApiVec::new();
// Pre-assemble a list of types with known destructors, to avoid having to
// do a O(n^2) nested loop.
let types_with_destructors: HashSet<_> = apis
.iter()
.filter_map(|api| match api {
Api::Function {
fun,
analysis:
FnAnalysis {
kind: FnKind::TraitMethod { impl_for, .. },
..
},
..
} if matches!(
**fun,
FuncToConvert {
special_member: Some(SpecialMemberKind::Destructor),
is_deleted: None | Some(Explicitness::Defaulted),
cpp_vis: CppVisibility::Public,
..
}
) =>
{
Some(impl_for)
}
_ => None,
})
.cloned()
.collect();
for api in apis.iter() {
if let Api::Function {
fun,
analysis:
analysis @ FnAnalysis {
kind:
FnKind::Method {
impl_for: sup,
method_kind: MethodKind::Constructor { .. },
..
},
..
},
..
} = api
{
// If we don't have an accessible destructor, then std::unique_ptr cannot be
// instantiated for this C++ type.
if !types_with_destructors.contains(sup) {
continue;
}
for sub in self.subclasses_by_superclass(sup) {
// Create a subclass constructor. This is a synthesized function
// which didn't exist in the original C++.
let (subclass_constructor_func, subclass_constructor_name) =
create_subclass_constructor(sub, analysis, sup, fun);
self.analyze_and_add(
subclass_constructor_name.clone(),
subclass_constructor_func.clone(),
&mut results,
TypeConversionSophistication::Regular,
);
}
}
}
apis.extend(results.into_iter());
}
/// Analyze a given function, and any permutations of that function which
/// we might additionally generate (e.g. for subclasses.)
///
/// Leaves the [`FnKind::Method::type_constructors`] at its default for [`add_constructors_present`]
/// to fill out.
fn analyze_foreign_fn_and_subclasses(
&mut self,
name: ApiName,
fun: Box<FuncToConvert>,
) -> Result<Box<dyn Iterator<Item = Api<FnPrePhase1>>>, ConvertErrorWithContext> {
let (analysis, name) =
self.analyze_foreign_fn(name, &fun, TypeConversionSophistication::Regular, None);
let mut results = ApiVec::new();
// Consider whether we need to synthesize subclass items.
if let FnKind::Method {
impl_for: sup,
method_kind:
MethodKind::Virtual(receiver_mutability) | MethodKind::PureVirtual(receiver_mutability),
..
} = &analysis.kind
{
let (simpler_analysis, _) = self.analyze_foreign_fn(
name.clone(),
&fun,
TypeConversionSophistication::SimpleForSubclasses,
Some(analysis.rust_name.clone()),
);
for sub in self.subclasses_by_superclass(sup) {
// For each subclass, we need to create a plain-C++ method to call its superclass
// and a Rust/C++ bridge API to call _that_.
// What we're generating here is entirely about the subclass, so the
// superclass's namespace is irrelevant. We generate
// all subclasses in the root namespace.
let is_pure_virtual = matches!(
&simpler_analysis.kind,
FnKind::Method {
method_kind: MethodKind::PureVirtual(..),
..
}
);
let super_fn_call_name =
SubclassName::get_super_fn_name(&Namespace::new(), &analysis.rust_name);
let super_fn_api_name = SubclassName::get_super_fn_name(
&Namespace::new(),
&analysis.cxxbridge_name.to_string(),
);
let trait_api_name = SubclassName::get_trait_api_name(sup, &analysis.rust_name);
let mut subclass_fn_deps = vec![trait_api_name.clone()];
if !is_pure_virtual {
// Create a C++ API representing the superclass implementation (allowing
// calls from Rust->C++)
let maybe_wrap = create_subclass_fn_wrapper(&sub, &super_fn_call_name, &fun);
let super_fn_name = ApiName::new_from_qualified_name(super_fn_api_name);
let super_fn_call_api_name = self.analyze_and_add(
super_fn_name,
maybe_wrap,
&mut results,
TypeConversionSophistication::SimpleForSubclasses,
);
subclass_fn_deps.push(super_fn_call_api_name);
}
// Create the Rust API representing the subclass implementation (allowing calls
// from C++ -> Rust)
results.push(create_subclass_function(
// RustSubclassFn
&sub,
&simpler_analysis,
&name,
receiver_mutability,
sup,
subclass_fn_deps,
self.unsafe_policy,
));
// Create the trait item for the <superclass>_methods and <superclass>_supers
// traits. This is required per-superclass, not per-subclass, so don't
// create it if it already exists.
if !self
.existing_superclass_trait_api_names
.contains(&trait_api_name)
{
self.existing_superclass_trait_api_names
.insert(trait_api_name.clone());
results.push(create_subclass_trait_item(
ApiName::new_from_qualified_name(trait_api_name),
&simpler_analysis,
receiver_mutability,
sup.clone(),
is_pure_virtual,
self.unsafe_policy,
));
}
}
}
results.push(Api::Function {
fun,
analysis,
name,
});
Ok(Box::new(results.into_iter()))
}
/// Adds an API, usually a synthesized API. Returns the final calculated API name, which can be used
/// for others to depend on this.
fn analyze_and_add<P: AnalysisPhase<FunAnalysis = FnAnalysis>>(
&mut self,
name: ApiName,
new_func: Box<FuncToConvert>,
results: &mut ApiVec<P>,
sophistication: TypeConversionSophistication,
) -> QualifiedName {
let (analysis, name) = self.analyze_foreign_fn(name, &new_func, sophistication, None);
results.push(Api::Function {
fun: new_func,
analysis,
name: name.clone(),
});
name.name
}
/// Determine how to materialize a function.
///
/// The main job here is to determine whether a function can simply be noted
/// in the [cxx::bridge] mod and passed directly to cxx, or if it needs a Rust-side
/// wrapper function, or if it needs a C++-side wrapper function, or both.
/// We aim for the simplest case but, for example:
/// * We'll need a C++ wrapper for static methods
/// * We'll need a C++ wrapper for parameters which need to be wrapped and unwrapped
/// to [cxx::UniquePtr]
/// * We'll need a Rust wrapper if we've got a C++ wrapper and it's a method.
/// * We may need wrappers if names conflict.
/// * etc.
///
/// The other major thing we do here is figure out naming for the function.
/// This depends on overloads, and what other functions are floating around.
/// The output of this analysis phase is used by both Rust and C++ codegen.
fn analyze_foreign_fn(
&mut self,
name: ApiName,
fun: &FuncToConvert,
sophistication: TypeConversionSophistication,
predetermined_rust_name: Option<String>,
) -> (FnAnalysis, ApiName) {
let cpp_original_name = name.cpp_name_if_present();
let ns = name.name.get_namespace();
// Let's gather some pre-wisdom about the name of the function.
// We're shortly going to plunge into analyzing the parameters,
// and it would be nice to have some idea of the function name
// for diagnostics whilst we do that.
let initial_rust_name = fun.ident.to_string();
let diagnostic_name = cpp_original_name
.as_ref()
.map(|n| n.diagnostic_display_name())
.unwrap_or(&initial_rust_name);
let diagnostic_name = QualifiedName::new(ns, make_ident(diagnostic_name));
// Now let's analyze all the parameters.
// See if any have annotations which our fork of bindgen has craftily inserted...
let (param_details, bads): (Vec<_>, Vec<_>) = fun
.inputs
.iter()
.map(|i| {
self.convert_fn_arg(
i,
ns,
&diagnostic_name,
&fun.synthesized_this_type,
true,
false,
None,
sophistication,
false,
)
.map_err(|err| ConvertErrorFromCpp::Argument {
arg: describe_arg(i),
err: Box::new(err),
})
})
.partition(Result::is_ok);
let (mut params, mut param_details): (Punctuated<_, Comma>, Vec<_>) =
param_details.into_iter().map(Result::unwrap).unzip();
let params_deps: HashSet<_> = param_details
.iter()
.flat_map(|p| p.deps.iter().cloned())
.collect();
let self_ty = param_details
.iter()
.filter_map(|pd| pd.self_type.as_ref())
.next()
.cloned();
// End of parameter processing.
// Work out naming, part one.
// bindgen may have mangled the name either because it's invalid Rust
// syntax (e.g. a keyword like 'async') or it's an overload.
// If the former, we respect that mangling. If the latter, we don't,
// because we'll add our own overload counting mangling later.
// Cases:
// function, IRN=foo, CN=<none> output: foo case 1
// function, IRN=move_, CN=move (keyword problem) output: move_ case 2
// function, IRN=foo1, CN=foo (overload) output: foo case 3
// method, IRN=A_foo, CN=foo output: foo case 4
// method, IRN=A_move, CN=move (keyword problem) output: move_ case 5
// method, IRN=A_foo1, CN=foo (overload) output: foo case 6
let ideal_rust_name = match cpp_original_name {
None => initial_rust_name, // case 1
Some(cpp_original_name) => {
if initial_rust_name.ends_with('_') {
initial_rust_name // case 2
} else if validate_ident_ok_for_rust(cpp_original_name).is_err() {
format!("{}_", cpp_original_name.to_string_for_rust_name()) // case 5
} else {
cpp_original_name.to_string_for_rust_name() // cases 3, 4, 6
}
}
};
// Let's spend some time figuring out the kind of this function (i.e. method,
// virtual function, etc.)
// Part one, work out if this is a static method.
let (is_static_method, self_ty, receiver_mutability) = match self_ty {
None => {
// Even if we can't find a 'self' parameter this could conceivably
// be a static method.
let self_ty = fun.self_ty.clone();
(self_ty.is_some(), self_ty, None)
}
Some((self_ty, receiver_mutability)) => {
(false, Some(self_ty), Some(receiver_mutability))
}
};
// Part two, work out if this is a function, or method, or whatever.
// First determine if this is actually a trait implementation.
let trait_details = self.trait_creation_details_for_synthetic_function(
&fun.add_to_trait,
ns,
&ideal_rust_name,
&self_ty,
);
let (kind, error_context, rust_name) = if let Some(trait_details) = trait_details {
trait_details
} else if let Some(self_ty) = self_ty {
// Some kind of method or static method.
let type_ident = self_ty.get_final_item();
// bindgen generates methods with the name:
// {class}_{method name}
// It then generates an impl section for the Rust type
// with the original name, but we currently discard that impl section.
// We want to feed cxx methods with just the method name, so let's
// strip off the class name.
let mut rust_name = ideal_rust_name;
let nested_type_ident = self
.nested_type_name_map
.get(&self_ty)
.map(|s| s.as_str())
.unwrap_or_else(|| self_ty.get_final_item());
if matches!(
fun.special_member,
Some(SpecialMemberKind::CopyConstructor | SpecialMemberKind::MoveConstructor)
) {
let is_move =
matches!(fun.special_member, Some(SpecialMemberKind::MoveConstructor));
if let Some(constructor_suffix) = rust_name.strip_prefix(nested_type_ident) {
rust_name = format!("new{constructor_suffix}");
}
rust_name = predetermined_rust_name
.unwrap_or_else(|| self.get_overload_name(ns, type_ident, rust_name));
let error_context = self.error_context_for_method(&self_ty, &rust_name);
// If this is 'None', then something weird is going on. We'll check for that
// later when we have enough context to generate useful errors.
let arg_is_reference = matches!(
param_details
.get(1)
.map(|param| param.conversion.cxxbridge_type()),
Some(Type::Reference(_))
);
// Some exotic forms of copy constructor have const and/or volatile qualifiers.
// These are not sufficient to implement CopyNew, so we just treat them as regular
// constructors. We detect them by their argument being translated to Pin at this
// point.
if is_move || arg_is_reference {
let (kind, method_name, trait_id) = if is_move {
(
TraitMethodKind::MoveConstructor,
"move_new",
quote! { MoveNew },
)
} else {
(
TraitMethodKind::CopyConstructor,
"copy_new",
quote! { CopyNew },
)
};
let ty = Type::Path(self_ty.to_type_path());
(
FnKind::TraitMethod {
kind,
impl_for: self_ty,
details: Box::new(TraitMethodDetails {
trt: TraitImplSignature {
ty: ty.into(),
trait_signature: parse_quote! {
autocxx::moveit::new:: #trait_id
},
unsafety: Some(parse_quote! { unsafe }),
},
avoid_self: true,
method_name: make_ident(method_name),
parameter_reordering: Some(vec![1, 0]),
}),
},
error_context,
rust_name,
)
} else {
(
FnKind::Method {
impl_for: self_ty,
method_kind: MethodKind::Constructor { is_default: false },
},
error_context,
rust_name,
)
}
} else if matches!(fun.special_member, Some(SpecialMemberKind::Destructor)) {
rust_name = predetermined_rust_name
.unwrap_or_else(|| self.get_overload_name(ns, type_ident, rust_name));
let error_context = self.error_context_for_method(&self_ty, &rust_name);
let ty = Type::Path(self_ty.to_type_path());
(
FnKind::TraitMethod {
kind: TraitMethodKind::Destructor,
impl_for: self_ty,
details: Box::new(TraitMethodDetails {
trt: TraitImplSignature {
ty: ty.into(),
trait_signature: parse_quote! {
Drop
},
unsafety: None,
},
avoid_self: false,
method_name: make_ident("drop"),
parameter_reordering: None,
}),
},
error_context,
rust_name,
)
} else {
let method_kind = if let Some(constructor_suffix) =
constructor_with_suffix(&rust_name, nested_type_ident)
{
// It's a constructor. bindgen generates
// fn Type(this: *mut Type, ...args)
// We want
// fn new(this: *mut Type, ...args)
// Later code will spot this and re-enter us, and we'll make
// a duplicate function in the above 'if' clause like this:
// fn make_unique(...args) -> Type
// which later code will convert to
// fn make_unique(...args) -> UniquePtr<Type>
// If there are multiple constructors, bindgen generates
// new, new1, new2 etc. and we'll keep those suffixes.
rust_name = format!("new{constructor_suffix}");
MethodKind::Constructor {
is_default: matches!(
fun.special_member,
Some(SpecialMemberKind::DefaultConstructor)
),
}
} else if is_static_method {
MethodKind::Static
} else {
let receiver_mutability =
receiver_mutability.expect("Failed to find receiver details");
match fun.virtualness {
None => MethodKind::Normal,
Some(Virtualness::Virtual) => MethodKind::Virtual(receiver_mutability),
Some(Virtualness::PureVirtual) => {
MethodKind::PureVirtual(receiver_mutability)
}
}
};
// Disambiguate overloads.
let rust_name = predetermined_rust_name
.unwrap_or_else(|| self.get_overload_name(ns, type_ident, rust_name));
let error_context = self.error_context_for_method(&self_ty, &rust_name);
(
FnKind::Method {
impl_for: self_ty,
method_kind,
},
error_context,
rust_name,
)
}
} else {
// Not a method.
// What shall we call this function? It may be overloaded.
let rust_name = self.get_function_overload_name(ns, ideal_rust_name);
(
FnKind::Function,
ErrorContext::new_for_item(make_ident(&rust_name)),
rust_name,
)
};
// If we encounter errors from here on, we can give some context around
// where the error occurred such that we can put a marker in the output
// Rust code to indicate that a problem occurred (benefiting people using
// rust-analyzer or similar). Make a closure to make this easy.
let mut ignore_reason = Ok(());
let mut set_ignore_reason =
|err| ignore_reason = Err(ConvertErrorWithContext(err, Some(error_context.clone())));