-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathlib.rs
More file actions
1584 lines (1453 loc) · 64.6 KB
/
lib.rs
File metadata and controls
1584 lines (1453 loc) · 64.6 KB
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
// Part of the Crubit project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#![allow(clippy::collapsible_else_if)]
use arc_anyhow::{anyhow, ensure, Context, Result};
use code_gen_utils::{format_cc_includes, is_cpp_reserved_keyword, make_rs_ident, CcInclude};
use cpp_type_name::format_cpp_type_with_references;
use crubit_abi_type::{
CrubitAbiType, CrubitAbiTypeToCppTokens, CrubitAbiTypeToRustExprTokens,
CrubitAbiTypeToRustTokens, FullyQualifiedPath,
};
use crubit_feature::CrubitFeature;
use database::code_snippet::{
self, integer_constant_to_token_stream, ApiSnippets, Bindings, BindingsTokens, CppDetails,
CppIncludes, Feature, GeneratedItem,
};
use database::db::{BindingsGenerator, CodegenFunctions};
use database::rs_snippet::{
BridgeRsTypeKind, Callable, FnTrait, Mutability, PassingConvention, RsTypeKind, RustPtrKind,
Safety, UniformReprTemplateType,
};
use dyn_format::Format;
use error_report::{bail, ErrorReporting, ReportFatalError};
use ffi_types::Environment;
use generate_comment::generate_top_level_comment;
use generate_comment::{generate_comment, generate_doc_comment, generate_unsupported};
use generate_struct_and_union::generate_incomplete_record;
use heck::ToSnakeCase;
use ir::*;
use itertools::Itertools;
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, ToTokens};
use rs_type_kind::rs_type_kind_with_lifetime_elision;
use std::collections::{BTreeSet, HashMap};
use std::ffi::OsStr;
use std::fmt::Write;
use std::path::Path;
use std::rc::Rc;
use token_stream_printer::{
cc_tokens_to_formatted_string, rs_tokens_to_formatted_string, RustfmtConfig,
};
mod generate_dyn_callable;
/// Deserializes IR from `json` and generates bindings source code.
pub fn generate_bindings(
json: &[u8],
crubit_support_path_format: &str,
clang_format_exe_path: &OsStr,
rustfmt_exe_path: &OsStr,
rustfmt_config_path: &OsStr,
errors: &dyn ErrorReporting,
fatal_errors: &dyn ReportFatalError,
environment: Environment,
kythe_annotations: bool,
kythe_default_corpus: &str,
) -> Result<Bindings> {
let ir = deserialize_ir(json).with_context(|| {
let ir_string = String::from_utf8_lossy(json);
format!("Failed to deserialize IR:\n{}", ir_string)
})?;
let crubit_support_path_format =
Format::parse_with_metavars(crubit_support_path_format, &["header"])?;
let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(
&ir,
crubit_support_path_format,
errors,
fatal_errors,
environment,
kythe_annotations,
)?;
let rs_api = {
let rustfmt_exe_path =
if rustfmt_exe_path.is_empty() { None } else { Some(Path::new(rustfmt_exe_path)) };
let rustfmt_config_path = if rustfmt_config_path.is_empty() {
None
} else {
Some(Path::new(rustfmt_config_path))
};
let rustfmt_config =
rustfmt_exe_path.map(|path| RustfmtConfig::new(path, rustfmt_config_path));
rs_tokens_to_formatted_string(rs_api, rustfmt_config.as_ref())?
};
let rs_api_impl: String = {
let clang_format_exe_path = if clang_format_exe_path.is_empty() {
None
} else {
Some(Path::new(clang_format_exe_path))
};
cc_tokens_to_formatted_string(rs_api_impl, clang_format_exe_path)?
};
let top_level_comment = generate_top_level_comment(&ir, environment);
// TODO(lukasza): Try to remove `#![rustfmt:skip]` - in theory it shouldn't
// be needed when `@generated` comment/keyword is present...
let rs_api = format!(
"{top_level_comment}\n\
#![rustfmt::skip]\n\
{rs_api}"
);
let rs_api_impl = format!(
"{top_level_comment}\n\
{rs_api_impl}"
);
Ok(Bindings { rs_api, rs_api_impl })
}
fn generate_type_alias(db: &BindingsGenerator, type_alias: Rc<TypeAlias>) -> Result<ApiSnippets> {
db.errors().add_category(error_report::Category::Alias);
// Skip the type alias if it maps to a bridge type.
// NOTE: rs_type_kind() gives a poor error message ("no bindings for <Alias>") if the underlying
// type is unsupported, so that most users of rs_type_kind (e.g. function definitions, structs)
// will fail with an error message about the _alias_ being unsupported, not the alias-ee.
//
// We, however, want to be more specific. To get the better error message, we call directly
// into has_bindings().
//
// Since rs_type_kind() can succeed even if this alias is unsupported (it is "seen through"),
// we only do so after rs_type_kind() fails.
let Ok(rs_type_kind) = db.rs_type_kind((&*type_alias).into()) else {
// Return the un-hidden raw error from has_bindings().
let Err(e) = db.has_bindings(ir::Item::TypeAlias(type_alias)) else {
unreachable!(
"Crubit promised to have bindings for a type alias, but didn't. This is a bug."
)
};
return Err(e.into());
};
let underlying_type = db
.rs_type_kind(type_alias.underlying_type.clone())
.with_context(|| format!("Failed to format underlying type for {type_alias}"))?;
// If this type alias refers to a record with nested types,
// we need to also re-export the generated module.
let mut underlying_nested_module_path = None;
if let RsTypeKind::Record { record, crate_path, .. } = &underlying_type
&& generate_struct_and_union::child_items(record, db).any(|child_item| child_item.is_nested)
{
let underlying_nested_module_name =
make_rs_ident(&record.rs_name.identifier.to_snake_case());
underlying_nested_module_path = Some(quote! { #crate_path #underlying_nested_module_name });
}
let generated_item = GeneratedItem::TypeAlias {
doc_comment: generate_doc_comment(
type_alias.doc_comment.as_deref(),
None,
Some(&type_alias.source_loc),
db.environment(),
db.kythe_annotations(),
),
visibility: db.type_visibility(&type_alias.owning_target, rs_type_kind).unwrap_or_default(),
ident: make_rs_ident(&type_alias.rs_name.identifier),
underlying_type: underlying_type.to_token_stream(db),
underlying_nested_module_path,
};
Ok(ApiSnippets {
generated_items: HashMap::from([(type_alias.id, generated_item)]),
..Default::default()
})
}
fn generate_constant(db: &BindingsGenerator, constant: &Constant) -> Result<ApiSnippets> {
db.errors().add_category(error_report::Category::Constant);
let type_ = db.rs_type_kind(constant.type_.clone())?;
let value = match integer_constant_to_token_stream(constant.value, &type_) {
Ok(value) => value,
Err(e) => {
return Ok(ApiSnippets {
generated_items: HashMap::from([(
constant.id,
GeneratedItem::Comment { message: e.to_string().into() },
)]),
..Default::default()
})
}
};
Ok(ApiSnippets {
generated_items: HashMap::from([(
constant.id,
GeneratedItem::Constant {
ident: make_rs_ident(&constant.rs_name.identifier),
type_tokens: type_.to_token_stream(db),
value,
},
)]),
..Default::default()
})
}
fn generate_global_var(db: &BindingsGenerator, var: &GlobalVar) -> Result<ApiSnippets> {
db.errors().add_category(error_report::Category::Variable);
let type_ = db.rs_type_kind(var.type_.clone())?;
Ok(ApiSnippets {
generated_items: HashMap::from([(
var.id,
GeneratedItem::GlobalVar {
link_name: var.mangled_name.clone(),
is_mut: !var.type_.is_const,
ident: make_rs_ident(&var.rs_name.identifier),
type_tokens: type_.to_token_stream(db),
visibility: db.type_visibility(&var.owning_target, type_).unwrap_or_default(),
},
)]),
..Default::default()
})
}
fn generate_namespace(db: &BindingsGenerator, namespace: Rc<Namespace>) -> Result<ApiSnippets> {
db.errors().add_category(error_report::Category::Namespace);
let ir = db.ir();
let mut api_snippets = ApiSnippets::default();
for &item_id in &namespace.child_item_ids {
let item = ir.find_untyped_decl(item_id);
api_snippets.append(db.generate_item(item.clone())?);
}
api_snippets.generated_items.insert(namespace.id, GeneratedItem::NonCanonicalNamespace);
api_snippets.generated_items.insert(
namespace.canonical_namespace_id,
GeneratedItem::CanonicalNamespace { items: namespace.child_item_ids.to_vec() },
);
Ok(api_snippets)
}
/// Implementation of `BindingsGenerator::generate_item`.
fn generate_item(db: &BindingsGenerator, item: Item) -> Result<ApiSnippets> {
if let Some(owning_target) = item.owning_target() {
if !db.ir().is_current_target(&owning_target) {
return Ok(ApiSnippets::default());
}
}
let _scope = item.error_scope(db.ir(), db.errors());
let err = match generate_item_impl(db, &item) {
Ok(generated) => return Ok(generated),
Err(err) => err,
};
if db.has_bindings(item.clone()).is_ok() && !matches!(item, Item::Func(_)) {
return Err(err);
}
// We didn't guarantee that bindings would exist, so it is not invalid to
// write down the error but continue.
// FIXME(cramertj): get paths here in more cases. It may be that
// `generate_item_impl` failed in such a way that the path is still available.
let unsupported_item =
UnsupportedItem::new_with_cause(db.ir(), &item, /* path= */ None, err);
Ok(generate_unsupported(db, unsupported_item.into()))
}
/// The implementation of generate_item, without the error recovery logic.
///
/// Returns Err if bindings could not be generated for this item.
fn generate_item_impl(db: &BindingsGenerator, item: &Item) -> Result<ApiSnippets> {
let generated_item = match item {
Item::Func(func) => match db.generate_function(func.clone(), None)? {
None => ApiSnippets::default(),
Some(generated_function) => {
if let Err(e) = &generated_function.status {
// Add any non-fatal errors to the error report.
// These won't result in an UnsupportedItem since we *did* generate an
// uncallable function item.
db.errors().report(e);
}
if db.is_ambiguous_function(&generated_function.id, func.id) {
bail!("Cannot generate bindings for overloaded function")
} else {
(*generated_function.snippets).clone()
}
}
},
Item::IncompleteRecord(incomplete_record) => {
generate_incomplete_record(db, incomplete_record.clone())?
}
Item::Record(record) => db.generate_record(record.clone())?,
Item::Enum(enum_) => db.generate_enum(enum_.clone())?,
Item::Constant(constant) => generate_constant(db, constant)?,
Item::GlobalVar(var) => generate_global_var(db, var)?,
Item::TypeAlias(type_alias) => generate_type_alias(db, type_alias.clone())?,
Item::UnsupportedItem(unsupported) => {
// Categorize unsupported items directly produced from the C++ importer.
// We let generate_record, generate_enum, etc. handle categorization when the item
// had a more specific type, which is why this categorization goes here, and not
// in generate_unsupported.
use UnsupportedItemKind::*;
match unsupported.kind {
Func | Constructor => {
db.errors().add_category(error_report::Category::Function);
}
GlobalVar => {
db.errors().add_category(error_report::Category::Variable);
}
Class | Struct | Union | Enum => {
db.errors().add_category(error_report::Category::Type);
}
TypeAlias => {
db.errors().add_category(error_report::Category::Alias);
}
Namespace | Other => {}
}
generate_unsupported(db, unsupported.clone())
}
Item::Comment(comment) => generate_comment(comment.clone()),
Item::Namespace(namespace) => generate_namespace(db, namespace.clone())?,
Item::UseMod(use_mod) => {
let UseMod { path, mod_name, .. } = &**use_mod;
let mod_name = make_rs_ident(&mod_name.identifier);
// TODO(b/308949532): Skip re-export if the module being used is empty
// (transitively).
ApiSnippets {
generated_items: HashMap::from([(
use_mod.id,
GeneratedItem::UseMod { path: path.clone(), mod_name },
)]),
..Default::default()
}
}
Item::ExistingRustType(existing_rust_type) => {
let rs_type_kind = db.rs_type_kind((&**existing_rust_type).into())?;
let disable_comment = format!(
"Type bindings for {cpp_type} suppressed due to being mapped to \
an existing Rust type ({rs_type_kind})",
cpp_type = existing_rust_type.debug_name(db.ir()),
rs_type_kind = rs_type_kind.display(db),
);
let assertions = existing_rust_type
.size_align
.as_ref()
.map(|size_align| {
generate_struct_and_union::rs_size_align_assertions(
rs_type_kind.to_token_stream(db),
size_align,
)
})
.into_iter()
.collect_vec();
ApiSnippets {
generated_items: HashMap::from([(
existing_rust_type.id,
GeneratedItem::Comment { message: disable_comment.into() },
)]),
assertions,
..Default::default()
}
}
};
// Suppress bindings at the last minute, to collect other errors first.
let _ = db.has_bindings(item.clone())?;
Ok(generated_item)
}
/// Creates a new database. Public for testing.
pub fn new_database<'db>(
ir: &'db IR,
errors: &'db dyn ErrorReporting,
fatal_errors: &'db dyn ReportFatalError,
environment: Environment,
kythe_annotations: bool,
) -> BindingsGenerator<'db> {
BindingsGenerator::new(
ir,
errors,
fatal_errors,
environment,
kythe_annotations,
CodegenFunctions {
generate_enum: generate_enum::generate_enum,
generate_item,
generate_record: generate_struct_and_union::generate_record,
},
rs_type_kind_safety,
record_field_safety,
record_safety,
has_bindings::has_bindings,
rs_type_kind_with_lifetime_elision,
generate_function::generate_function,
generate_function::overload_sets,
generate_function::is_record_clonable,
generate_function::get_binding,
generate_struct_and_union::collect_unqualified_member_functions,
crubit_abi_type,
has_bindings::type_target_restriction,
has_bindings::resolve_type_names,
is_default_initialized,
)
}
/// Returns the Rust code implementing bindings, plus any auxiliary C++ code
/// needed to support it.
//
/// Public for use in `generate_bindings_tokens_for_test`.
pub fn generate_bindings_tokens(
ir: &IR,
crubit_support_path_format: Format<1>,
errors: &dyn ErrorReporting,
fatal_errors: &dyn ReportFatalError,
environment: Environment,
kythe_annotations: bool,
) -> Result<BindingsTokens> {
let db = new_database(ir, errors, fatal_errors, environment, kythe_annotations);
let mut snippets = ApiSnippets::default();
// For #![rustfmt::skip].
snippets.features |= Feature::custom_inner_attributes;
// For the `vector` in `cc_std`.
snippets.features |= Feature::allocator_api;
snippets.features |= Feature::cfg_sanitize;
for top_level_item_id in ir.top_level_item_ids() {
let item = ir.find_untyped_decl(*top_level_item_id);
snippets.append(db.generate_item(item.clone())?);
}
// Since Idents are not free, we reuse them across records.
let mut param_idents_buffer = vec![];
let (dyn_callable_cpp_decls, dyn_callable_rust_impls): (Vec<TokenStream>, Vec<TokenStream>) =
ir.records()
.filter_map(|record| {
// If the record doesn't belong to a target with the Callables feature, skip.
if !ir
.target_crubit_features(&record.owning_target)
.contains(CrubitFeature::Callables)
{
return None;
}
// It doesn't matter since we're just checking for presence of DynCallable.
let has_reference_param = false;
// Find records that are template instantiations of `rs_std::DynCallable`.
let Ok(Some(BridgeRsTypeKind::Callable(callable))) =
BridgeRsTypeKind::new(record, has_reference_param, &db)
else {
return None;
};
// The parameters shall be named `param_0`, `param_1`, etc.
// These names can be reused across different dyn callables, so we reuse the same vec
// and just grow it when we need more Idents than it currently contains.
while callable.param_types.len() > param_idents_buffer.len() {
param_idents_buffer.push(format_ident!("param_{}", param_idents_buffer.len()));
}
// Only take as many filled in names as we need.
let param_idents = ¶m_idents_buffer[..callable.param_types.len()];
// If generate_dyn_callable_cpp_thunk fails, skip. We don't need to generate a nice
// error because whoever uses this will also fail and generate an error at the relevant
// site.
let callable_cpp_decl =
generate_dyn_callable_cpp_thunk(&db, &callable, param_idents)?;
let callable_rust_impl =
generate_dyn_callable_rust_thunk_impl(&db, callable.clone(), param_idents)?;
Some((callable_cpp_decl, callable_rust_impl))
})
.unzip();
let has_callables = !dyn_callable_rust_impls.is_empty();
// Callables use `Box<dyn F>`.
let extern_crate_alloc =
has_callables.then(|| quote! { extern crate alloc; __NEWLINE__ __NEWLINE__ });
// when we go through the main_api, we want to go through one at a time.
// if the parent is none, we're responsible.
// each thing needs to go through all its children.
let ApiSnippets {
generated_items,
thunks,
assertions,
cc_details,
features,
member_functions: _,
} = snippets;
let main_api = code_snippet::generated_items_to_token_stream(
&generated_items,
ir,
ir.top_level_item_ids(),
);
let cc_details = CppDetails {
includes: generate_rs_api_impl_includes(&db, crubit_support_path_format, has_callables),
dyn_callable_cpp_decls,
thunks: cc_details,
};
let thunks = if thunks.is_empty() {
None
} else {
Some(quote! {
unsafe extern "C" {
#( #thunks )*
}
})
};
let dyn_callable_rust_impls = if dyn_callable_rust_impls.is_empty() {
None
} else {
Some(quote! { #( #dyn_callable_rust_impls )* })
};
let mod_detail = if thunks.is_none() && dyn_callable_rust_impls.is_none() {
None
} else {
Some(quote! {
mod detail {
#[allow(unused_imports)]
use super::*;
#thunks
__NEWLINE__
#dyn_callable_rust_impls
}
})
};
let features = if features.is_empty() {
quote! {}
} else {
let feature_iter = features.into_iter();
quote! {
#![feature( #(#feature_iter),* )] __NEWLINE__
#![allow(stable_features)]
}
};
let assertions = if assertions.is_empty() {
quote! {}
} else {
quote! {
const _: () = { __NEWLINE__
#( #assertions __NEWLINE__ )*
}; __NEWLINE__
}
};
Ok(BindingsTokens {
rs_api: quote! {
#features __NEWLINE__
// `rust_builtin_type_abi_assumptions.md` documents why the generated
// bindings need to relax the `improper_ctypes_definitions` warning
// for `char` (and possibly for other built-in types in the future).
#![allow(improper_ctypes)] __NEWLINE__
// C++ names don't follow Rust guidelines:
#![allow(nonstandard_style)] __NEWLINE__
// Parts of our generated code are sometimes considered dead
// (b/349776381).
#![allow(dead_code, unused_mut)] __NEWLINE__
#![deny(warnings)] __NEWLINE__ __NEWLINE__
#extern_crate_alloc
#main_api
#mod_detail __NEWLINE__ __NEWLINE__
#assertions
},
rs_api_impl: cc_details.into_token_stream(),
})
}
/// Implementation of `BindingsGenerator::rs_type_kind_safety`.
fn rs_type_kind_safety(db: &BindingsGenerator, rs_type_kind: RsTypeKind) -> Safety {
match rs_type_kind {
RsTypeKind::Error { error, .. } => {
Safety::unsafe_because(format!("Crubit cannot assume unknown types are safe: {error}"))
}
RsTypeKind::Pointer { .. } => Safety::unsafe_because("raw pointer"),
RsTypeKind::Reference { referent: t, .. }
| RsTypeKind::RvalueReference { referent: t, .. }
| RsTypeKind::TypeAlias { underlying_type: t, .. } => {
db.rs_type_kind_safety(t.as_ref().clone())
}
RsTypeKind::FuncPtr { return_type, param_types, .. } => {
callable_safety(db, ¶m_types, &return_type)
}
RsTypeKind::IncompleteRecord { .. } => {
// TODO(b/390474240): Add a way to mark a forward declaration as being an unsafe
// type.
Safety::Safe
}
RsTypeKind::Enum { .. }
| RsTypeKind::Primitive(..)
| RsTypeKind::ExistingRustType { .. } => Safety::Safe,
RsTypeKind::BridgeType { bridge_type, original_type } => match bridge_type {
// TODO(b/390621592): Should bridge types just delegate to the underlying type?
BridgeRsTypeKind::BridgeVoidConverters { .. } | BridgeRsTypeKind::Bridge { .. } => {
if record_safety(db, original_type.clone()).is_safe() {
Safety::Safe
} else {
// Full unsafe reason is not shown here, it's documented on the type instead.
Safety::unsafe_because("unsafe bridge type")
}
}
BridgeRsTypeKind::ProtoMessageBridge { .. } => {
if record_safety(db, original_type.clone()).is_safe() {
Safety::Safe
} else {
// Full unsafe reason is not shown here, it's documented on the type instead.
Safety::unsafe_because("unsafe proto message type")
}
}
BridgeRsTypeKind::StdOptional(t) => db.rs_type_kind_safety(t.as_ref().clone()),
BridgeRsTypeKind::StdPair(t1, t2) => {
let s1 = db.rs_type_kind_safety(t1.as_ref().clone());
let s2 = db.rs_type_kind_safety(t2.as_ref().clone());
let r1 = s1
.unsafe_reason()
.map(|reason| format!("pair's first element is unsafe: {reason}"));
let r2 = s2
.unsafe_reason()
.map(|reason| format!("pair's second element is unsafe: {reason}"));
if let (Some(r1), Some(r2)) = (&r1, &r2) {
Safety::unsafe_because(format!("{r1}; {r2}"))
} else if let Some(r1) = r1 {
Safety::unsafe_because(r1)
} else if let Some(r2) = r2 {
Safety::unsafe_because(r2)
} else {
Safety::Safe
}
}
BridgeRsTypeKind::StdString { .. } => Safety::Safe,
BridgeRsTypeKind::Callable(callable) => {
callable_safety(db, &callable.param_types, &callable.return_type)
}
BridgeRsTypeKind::C9Co { result_type, .. } => {
// A Co<T> logically produces a T, so it is unsafe iff T is unsafe.
db.rs_type_kind_safety(result_type.as_ref().clone())
}
},
RsTypeKind::Record { record, .. } => {
if record_safety(db, record.clone()).is_safe() {
Safety::Safe
} else {
// Full unsafe reason is not shown here, it's documented on the type instead.
Safety::unsafe_because("unsafe struct or union")
}
}
}
}
/// Helper function for `rs_type_kind_safety`.
/// Returns whether a callable is unsafe due to its parameters or return type.
fn callable_safety(
db: &BindingsGenerator,
param_types: &[RsTypeKind],
return_type: &RsTypeKind,
) -> Safety {
let param_reasons = param_types
.iter()
.cloned()
.enumerate()
.filter_map(|(i, param_type)| {
let safety = db.rs_type_kind_safety(param_type);
let reason = safety.unsafe_reason()?;
let i = i + 1;
Some(format!("param {i} is of unsafe type {reason}"))
})
.collect_vec();
let return_safety = db.rs_type_kind_safety(return_type.clone());
if param_reasons.is_empty() && return_safety.is_safe() {
return Safety::Safe;
}
let mut reasons = if param_reasons.is_empty() {
String::new()
} else {
format!("Callable takes unsafe parameters: {}", param_reasons.join(", "))
};
if let Some(return_reason) = return_safety.unsafe_reason() {
if reasons.is_empty() {
reasons = format!("Callable return type is unsafe: {return_reason}");
} else {
reasons = format!("{reasons}; and return type is unsafe: {return_reason}")
}
}
Safety::unsafe_because(reasons)
}
/// Implementation of `BindingsGenerator::record_field_safety`.
fn record_field_safety(db: &BindingsGenerator, field: Field) -> Safety {
if field.access != AccessSpecifier::Public {
return Safety::Safe;
}
let field_rs_type_kind = match db.rs_type_kind(field.type_.clone()) {
Ok(field_rs_type_kind) => field_rs_type_kind,
Err(err) => {
// If we can't get the RsTypeKind for a public field, we assume it's unsafe.
return Safety::unsafe_because(
format!("Rust type is unknown; safety requirements cannot be automatically generated: {err}"),
);
}
};
db.rs_type_kind_safety(field_rs_type_kind)
}
/// Implementation of `BindingsGenerator::record_safety`.
fn record_safety(db: &BindingsGenerator, record: Rc<Record>) -> Safety {
let mut doc = String::new();
match record.safety_annotation {
SafetyAnnotation::DisableUnsafe => {
return Safety::Safe;
}
SafetyAnnotation::Unsafe => {
// TODO(b/480191443): allow C++ annotations to provide a specific reason.
doc += "* The C++ type is explicitly annotated as unsafe. Ensure that its safety requirements are upheld.";
}
SafetyAnnotation::Unannotated => {}
}
if record.is_union() {
doc += "* The callee does not read an incorrect field out of the union.\n";
}
let reasons: Vec<_> = record
.fields
.iter()
.filter_map(|field| {
let reason = db.record_field_safety(field.clone()).unsafe_reason()?;
// TODO(nicholasbishop): handle unnamed better.
let mut name = field
.rust_identifier
.as_ref()
.map(|i| format!("`{}`", i.as_str()))
.unwrap_or("unnamed field".to_owned());
write!(name, ": {reason}").unwrap();
Some(name)
})
.collect();
if matches!(record.safety_annotation, SafetyAnnotation::Unannotated)
&& !record.is_union()
&& reasons.is_empty()
{
return Safety::Safe;
}
if !reasons.is_empty() {
doc += "* Document why the following public unsafe fields of this type cannot be misused by callee:\n";
for reason in reasons {
writeln!(doc, " * {reason}").unwrap();
}
}
// Verify that we didn't generate an empty safety doc.
assert!(!doc.is_empty());
Safety::unsafe_because(format!(
"To call a function that accepts this type, you must uphold these requirements:\n{doc}"
))
}
fn generate_rs_api_impl_includes(
db: &BindingsGenerator,
crubit_support_path_format: Format<1>,
has_callables: bool,
) -> CppIncludes {
let ir = db.ir();
let mut internal_includes = BTreeSet::new();
internal_includes.insert(CcInclude::memory()); // ubiquitous.
if ir.records().next().is_some() {
internal_includes.insert(CcInclude::cstddef());
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"internal/sizeof.h".into(),
));
};
if has_callables {
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"rs_std/dyn_callable.h".into(),
));
}
let crubit_any_invocable_support_header =
generate_dyn_callable::CRUBIT_ANY_INVOCABLE_SUPPORT_HEADER.map(Rc::<str>::from);
for record in ir.records() {
// We don't actually use the possible c9::Co, but need to pass in something to `new`.
let has_reference_param = false;
// Err means that this bridge type has some issues. For the purpose of generating includes,
// we can ignore it.
if let Ok(Some(bridge_type)) = BridgeRsTypeKind::new(record, has_reference_param, db) {
match bridge_type {
BridgeRsTypeKind::BridgeVoidConverters { .. } => {
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"internal/lazy_init.h".into(),
));
}
BridgeRsTypeKind::C9Co { .. } => {
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"bridge.h".into(),
));
internal_includes.insert(CcInclude::user_header(
"util/c9/internal/rust/co_crubit_abi.h".into(),
));
}
BridgeRsTypeKind::Callable(callable)
if callable.backing_type == BackingType::AnyInvocable =>
{
if let Some(crubit_any_invocable_support_header) =
&crubit_any_invocable_support_header
{
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"bridge.h".into(),
));
internal_includes.insert(CcInclude::user_header(Rc::clone(
crubit_any_invocable_support_header,
)));
} else {
// absl::AnyInvocable will not receieve bridge bindings.
}
}
_ => {
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"bridge.h".into(),
));
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"internal/slot.h".into(),
));
}
}
}
if ir
.target_crubit_features(&record.owning_target)
.contains(crubit_feature::CrubitFeature::Fmt)
&& record.detected_formatter
{
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"rs_std/lossy_formatter_for_bindings.h".into(),
));
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"internal/fmt.h".into(),
));
}
}
for e in ir.enums() {
if ir.target_crubit_features(&e.owning_target).contains(crubit_feature::CrubitFeature::Fmt)
&& e.detected_formatter
{
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"rs_std/lossy_formatter_for_bindings.h".into(),
));
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"internal/fmt.h".into(),
));
}
}
for type_alias in ir.type_aliases() {
let Ok(rs_type_kind) = db.rs_type_kind((&**type_alias).into()) else {
continue;
};
if let RsTypeKind::BridgeType { bridge_type, .. } = rs_type_kind.unalias() {
if bridge_type.is_void_converters_bridge_type() {
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"internal/lazy_init.h".into(),
));
} else {
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"bridge.h".into(),
));
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
"internal/slot.h".into(),
));
}
}
}
for crubit_header in ["internal/cxx20_backports.h", "internal/offsetof.h"] {
internal_includes.insert(CcInclude::SupportLibHeader(
crubit_support_path_format.clone(),
crubit_header.into(),
));
}
let internal_includes = format_cc_includes(&internal_includes);
// In order to generate C++ thunk in all the cases Clang needs to be able to
// access declarations from public headers of the C++ library. We don't
// process these includes via `format_cc_includes` to preserve their
// original order (some libraries require certain headers to be included
// first - e.g. `config.h`).
let ir_includes =
ir.public_headers().map(|hdr| CcInclude::user_header(hdr.name.clone())).collect_vec();
CppIncludes { internal_includes, ir_includes }
}
/// Implementation of `BindingsGenerator::crubit_abi_type`.
fn crubit_abi_type(db: &BindingsGenerator, rs_type_kind: RsTypeKind) -> Result<CrubitAbiType> {
match rs_type_kind {
RsTypeKind::Error { error, .. } => {
bail!("Type has an error and cannot be bridged: {error}")
}
RsTypeKind::TypeAlias { underlying_type, .. } => {
// We don't actually _have_ to expand the type alias here
db.crubit_abi_type(underlying_type.as_ref().clone())
}
RsTypeKind::Pointer { pointee, kind, mutability } => {
let rust_tokens = pointee.to_token_stream(db);
let cpp_tokens = format_cpp_type_with_references(&pointee, db.ir())?;
Ok(CrubitAbiType::Ptr {
is_const: mutability == Mutability::Const,
is_rust_slice: kind == RustPtrKind::Slice,
rust_type: rust_tokens,
cpp_type: cpp_tokens,
})
}
RsTypeKind::Enum { ref enum_, .. } => {
let cpp_type =
make_cpp_type_from_item(enum_.as_ref(), enum_.cc_name.identifier.as_ref(), db)?;
Ok(CrubitAbiType::Transmute { rust_type: rs_type_kind.to_token_stream(db), cpp_type })
}
RsTypeKind::ExistingRustType(ref existing_rust_type) => {
let cpp_type = make_cpp_type_from_item(
existing_rust_type.as_ref(),
existing_rust_type.cc_name.as_ref(),
db,
)?;
Ok(CrubitAbiType::Transmute { rust_type: rs_type_kind.to_token_stream(db), cpp_type })
}
RsTypeKind::Primitive(primitive) => Ok(match primitive {
Primitive::Bool => CrubitAbiType::transmute("bool", "bool"),
Primitive::Void => bail!("values of type `void` cannot be bridged by value"),
Primitive::Float => CrubitAbiType::transmute("f32", "float"),
Primitive::Double => CrubitAbiType::transmute("f64", "double"),
Primitive::Char => CrubitAbiType::transmute("::core::ffi::c_char", "char"),
Primitive::SignedChar => CrubitAbiType::SignedChar,
Primitive::UnsignedChar => CrubitAbiType::UnsignedChar,
Primitive::Short => CrubitAbiType::transmute("::core::ffi::c_short", "short"),
Primitive::Int => CrubitAbiType::transmute("::core::ffi::c_int", "int"),
Primitive::Long => CrubitAbiType::transmute("::core::ffi::c_long", "long"),
Primitive::LongLong => CrubitAbiType::LongLong,
Primitive::UnsignedShort => CrubitAbiType::UnsignedShort,
Primitive::UnsignedInt => CrubitAbiType::UnsignedInt,
Primitive::UnsignedLong => CrubitAbiType::UnsignedLong,
Primitive::UnsignedLongLong => CrubitAbiType::UnsignedLongLong,
Primitive::Char16T => CrubitAbiType::transmute("u16", "char16_t"),
Primitive::Char32T => CrubitAbiType::transmute("u32", "char32_t"),
Primitive::PtrdiffT => CrubitAbiType::transmute("isize", "ptrdiff_t"),
Primitive::IntptrT => CrubitAbiType::transmute("isize", "intptr_t"),
Primitive::StdPtrdiffT => CrubitAbiType::transmute("isize", "std::ptrdiff_t"),
Primitive::StdIntptrT => CrubitAbiType::transmute("isize", "std::intptr_t"),
Primitive::SizeT => CrubitAbiType::transmute("usize", "size_t"),
Primitive::UintptrT => CrubitAbiType::transmute("usize", "uintptr_t"),
Primitive::StdSizeT => CrubitAbiType::transmute("usize", "std::size_t"),
Primitive::StdUintptrT => CrubitAbiType::transmute("usize", "std::uintptr_t"),
Primitive::Int8T => CrubitAbiType::transmute("i8", "int8_t"),
Primitive::Int16T => CrubitAbiType::transmute("i16", "int16_t"),
Primitive::Int32T => CrubitAbiType::transmute("i32", "int32_t"),
Primitive::Int64T => CrubitAbiType::transmute("i64", "int64_t"),
Primitive::StdInt8T => CrubitAbiType::transmute("i8", "std::int8_t"),
Primitive::StdInt16T => CrubitAbiType::transmute("i16", "std::int16_t"),
Primitive::StdInt32T => CrubitAbiType::transmute("i32", "std::int32_t"),