-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathlib.rs
More file actions
3639 lines (3449 loc) · 145 KB
/
lib.rs
File metadata and controls
3639 lines (3449 loc) · 145 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
use anyhow::bail;
use heck::{ToPascalCase, ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
use std::{
collections::{HashMap, HashSet},
fmt::{self, Display, Write as FmtWrite},
io::{Read, Write},
path::PathBuf,
process::{Command, Stdio},
str::FromStr,
};
use symbol_name::{make_external_component, make_external_symbol};
use wit_bindgen_c::to_c_ident;
use wit_bindgen_core::{
Files, InterfaceGenerator, Source, Types, WorldGenerator,
abi::{self, AbiVariant, Bindgen, Bitcast, LiftLower, WasmSignature, WasmType},
name_package_module, uwrite, uwriteln,
wit_parser::{
Alignment, ArchitectureSize, Docs, Function, FunctionKind, Handle, Int, InterfaceId, Param,
Resolve, SizeAlign, Stability, Type, TypeDef, TypeDefKind, TypeId, TypeOwner, WorldId,
WorldKey,
},
};
// mod wamr;
mod symbol_name;
pub const RESOURCE_IMPORT_BASE_CLASS_NAME: &str = "ResourceImportBase";
pub const RESOURCE_EXPORT_BASE_CLASS_NAME: &str = "ResourceExportBase";
pub const RESOURCE_TABLE_NAME: &str = "ResourceTable";
pub const OWNED_CLASS_NAME: &str = "Owned";
pub const POINTER_SIZE_EXPRESSION: &str = "sizeof(void*)";
type CppType = String;
#[derive(Clone, Copy, Debug)]
enum Flavor {
Argument(AbiVariant),
Result(AbiVariant),
InStruct,
BorrowedArgument,
}
#[derive(Default)]
struct HighlevelSignature {
/// this is a constructor or destructor without a written type
// implicit_result: bool, -> empty result
const_member: bool,
static_member: bool,
result: CppType,
arguments: Vec<(String, CppType)>,
name: String,
namespace: Vec<String>,
implicit_self: bool,
post_return: bool,
}
// follows https://google.github.io/styleguide/cppguide.html
#[derive(Default)]
struct Includes {
needs_vector: bool,
needs_expected: bool,
needs_string: bool,
needs_string_view: bool,
needs_optional: bool,
needs_cstring: bool,
needs_imported_resources: bool,
needs_exported_resources: bool,
needs_variant: bool,
needs_tuple: bool,
needs_assert: bool,
needs_bit: bool,
needs_span: bool,
// needs wit types
needs_wit: bool,
needs_memory: bool,
needs_array: bool,
}
#[derive(Default)]
struct SourceWithState {
src: Source,
namespace: Vec<String>,
}
#[derive(Eq, Hash, PartialEq, Clone, Copy, Debug)]
enum Direction {
Import,
Export,
}
#[derive(Default)]
struct Cpp {
opts: Opts,
c_src: SourceWithState,
h_src: SourceWithState,
c_src_head: Source,
extern_c_decls: Source,
dependencies: Includes,
includes: Vec<String>,
world: String,
world_id: Option<WorldId>,
imported_interfaces: HashSet<InterfaceId>,
user_class_files: HashMap<String, String>,
defined_types: HashSet<(Vec<String>, String)>,
types: Types,
// needed for symmetric disambiguation
interface_prefixes: HashMap<(Direction, WorldKey), String>,
import_prefix: Option<String>,
/// Tracks InterfaceIds whose types have already been generated (for implements dedup).
implements_types_generated: HashSet<InterfaceId>,
}
#[cfg(feature = "clap")]
fn parse_with(s: &str) -> Result<(String, String), String> {
let (k, v) = s.split_once('=').ok_or_else(|| {
format!("expected string of form `<key>=<value>[,<key>=<value>...]`; got `{s}`")
})?;
Ok((k.to_string(), v.to_string()))
}
#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "clap", derive(clap::Args))]
pub struct Opts {
/// Call clang-format on the generated code
#[cfg_attr(feature = "clap", arg(long, default_value_t = bool::default()))]
pub format: bool,
/// Place each interface in its own file,
/// this enables sharing bindings across projects
#[cfg_attr(feature = "clap", arg(long, default_value_t = bool::default()))]
pub split_interfaces: bool,
/// Optionally prefix any export names with the specified value.
///
/// This is useful to avoid name conflicts when testing.
#[cfg_attr(feature = "clap", arg(long))]
pub export_prefix: Option<String>,
/// Wrap all C++ classes inside a custom namespace.
///
/// This avoids identical names across components, useful for native
#[cfg_attr(feature = "clap", arg(long))]
pub internal_prefix: Option<String>,
/// Set API style to symmetric or asymmetric
#[cfg_attr(
feature = "clap",
arg(
long,
default_value_t = APIStyle::default(),
value_name = "STYLE",
),
)]
pub api_style: APIStyle,
/// Whether to generate owning or borrowing type definitions for `record` arguments to imported functions.
///
/// Valid values include:
///
/// - `owning`: Generated types will be composed entirely of owning fields,
/// regardless of whether they are used as parameters to imports or not.
///
/// - `coarse-borrowing`: Generated types used as parameters to imports will be
/// "deeply borrowing", i.e. contain references rather than owned values,
/// so long as they don't contain resources, in which case they will be
/// owning.
///
/// - `fine-borrowing": Generated types used as parameters to imports will be
/// "deeply borrowing", i.e. contain references rather than owned values
/// for all fields that are not resources, which will be owning.
#[cfg_attr(feature = "clap", arg(long, default_value_t = Ownership::Owning))]
pub ownership: Ownership,
/// Where to place output files
#[cfg_attr(feature = "clap", arg(skip))]
out_dir: Option<PathBuf>,
/// Importing wit interface from custom include
///
/// Argument must be of the form `k=v` and this option can be passed
/// multiple times or one option can be comma separated, for example
/// `k1=v1,k2=v2`.
#[cfg_attr(feature = "clap", arg(long, value_parser = parse_with, value_delimiter = ','))]
pub with: Vec<(String, String)>,
}
/// Supported API styles for the generated bindings.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum APIStyle {
/// Imported functions borrow arguments, while exported functions receive owned arguments. Reduces the allocation overhead for the canonical ABI.
#[default]
Asymmetric,
/// Same API for imported and exported functions. Reduces the allocation overhead for symmetric ABI.
Symmetric,
}
impl Display for APIStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
APIStyle::Asymmetric => write!(f, "asymmetric"),
APIStyle::Symmetric => write!(f, "symmetric"),
}
}
}
impl FromStr for APIStyle {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"asymmetric" => Ok(APIStyle::Asymmetric),
"symmetric" => Ok(APIStyle::Symmetric),
_ => bail!("unrecognized API style: `{s}`; expected `asymmetric` or `symmetric`"),
}
}
}
#[derive(Default, Debug, Clone, Copy)]
pub enum Ownership {
/// Generated types will be composed entirely of owning fields, regardless
/// of whether they are used as parameters to imports or not.
#[default]
Owning,
/// Generated types used as parameters to imports will be "deeply
/// borrowing", i.e. contain references rather than owned values when
/// applicable.
CoarseBorrowing,
/// Generated types used as parameters to imports will be "deeply
/// borrowing", i.e. contain references rather than owned values
/// for all fields that are not resources, which will be owning.
FineBorrowing,
}
impl FromStr for Ownership {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"owning" => Ok(Self::Owning),
"coarse-borrowing" => Ok(Self::CoarseBorrowing),
"fine-borrowing" => Ok(Self::FineBorrowing),
_ => Err(format!(
"unrecognized ownership: `{s}`; \
expected `owning`, `coarse-borrowing`, or `fine-borrowing`"
)),
}
}
}
impl fmt::Display for Ownership {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
Ownership::Owning => "owning",
Ownership::CoarseBorrowing => "coarse-borrowing",
Ownership::FineBorrowing => "fine-borrowing",
})
}
}
impl Opts {
pub fn build(mut self, out_dir: Option<&PathBuf>) -> Box<dyn WorldGenerator> {
let mut r = Cpp::new();
self.out_dir = out_dir.cloned();
r.opts = self;
Box::new(r)
}
fn is_only_handle(&self, variant: AbiVariant) -> bool {
!matches!(variant, AbiVariant::GuestExport)
}
fn ptr_type(&self) -> &'static str {
"uint8_t*"
}
}
impl Cpp {
fn new() -> Cpp {
Cpp::default()
}
pub fn is_first_definition(&mut self, ns: &Vec<String>, name: &str) -> bool {
let owned = (ns.to_owned(), name.to_owned());
if !self.defined_types.contains(&owned) {
self.defined_types.insert(owned);
true
} else {
false
}
}
fn include(&mut self, s: &str) {
self.includes.push(s.to_string());
}
/// Returns true if the function is a fallible constructor.
///
/// Fallible constructors are constructors that return `result<T, E>` instead of just `T`.
/// In the generated C++ code, these become static factory methods named `Create` that
/// return `std::expected<T, E>`, rather than regular constructors.
fn is_fallible_constructor(&self, resolve: &Resolve, func: &Function) -> bool {
matches!(&func.kind, FunctionKind::Constructor(_))
&& func.result.as_ref().is_some_and(|ty| {
if let Type::Id(id) = ty {
matches!(&resolve.types[*id].kind, TypeDefKind::Result(_))
} else {
false
}
})
}
fn interface<'a>(
&'a mut self,
resolve: &'a Resolve,
name: Option<&'a WorldKey>,
in_guest_import: bool,
wasm_import_module: Option<String>,
) -> CppInterfaceGenerator<'a> {
let mut sizes = SizeAlign::default();
sizes.fill(resolve);
CppInterfaceGenerator {
_src: Source::default(),
r#gen: self,
resolve,
interface: None,
_name: name,
sizes,
in_guest_import,
wasm_import_module,
implements_label: None,
}
}
fn clang_format(code: &mut String) {
let mut child = Command::new("clang-format")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("failed to spawn `clang-format`");
child
.stdin
.take()
.unwrap()
.write_all(code.as_bytes())
.unwrap();
code.truncate(0);
child.stdout.take().unwrap().read_to_string(code).unwrap();
let status = child.wait().unwrap();
assert!(status.success());
}
fn perform_cast(&mut self, op: &str, cast: &Bitcast) -> String {
match cast {
Bitcast::I32ToF32 | Bitcast::I64ToF32 => {
self.dependencies.needs_bit = true;
format!("std::bit_cast<float, int32_t>({op})")
}
Bitcast::F32ToI32 | Bitcast::F32ToI64 => {
self.dependencies.needs_bit = true;
format!("std::bit_cast<int32_t, float>({op})")
}
Bitcast::I64ToF64 => {
self.dependencies.needs_bit = true;
format!("std::bit_cast<double, int64_t>({op})")
}
Bitcast::F64ToI64 => {
self.dependencies.needs_bit = true;
format!("std::bit_cast<int64_t, double>({op})")
}
Bitcast::I32ToI64 | Bitcast::LToI64 | Bitcast::PToP64 => {
format!("(int64_t) {op}")
}
Bitcast::I64ToI32 | Bitcast::PToI32 | Bitcast::LToI32 => {
format!("(int32_t) {op}")
}
Bitcast::P64ToI64 | Bitcast::None | Bitcast::I64ToP64 => op.to_string(),
Bitcast::P64ToP | Bitcast::I32ToP | Bitcast::LToP => {
format!("(uint8_t*) {op}")
}
Bitcast::PToL | Bitcast::I32ToL | Bitcast::I64ToL => {
format!("(size_t) {op}")
}
Bitcast::Sequence(sequence) => {
let [first, second] = &**sequence;
let inner = self.perform_cast(op, first);
self.perform_cast(&inner, second)
}
}
}
fn finish_includes(&mut self) {
self.include("<cstdint>");
self.include("<utility>"); // for std::move
if self.dependencies.needs_string {
self.include("<string>");
}
if self.dependencies.needs_string_view {
self.include("<string_view>");
}
if self.dependencies.needs_vector {
self.include("<vector>");
}
if self.dependencies.needs_expected {
self.include("<expected>");
}
if self.dependencies.needs_optional {
self.include("<optional>");
}
if self.dependencies.needs_cstring {
self.include("<cstring>");
}
if self.dependencies.needs_imported_resources {
self.include("<cassert>");
}
if self.dependencies.needs_exported_resources {
self.include("<map>");
}
if self.dependencies.needs_variant {
self.include("<variant>");
}
if self.dependencies.needs_tuple {
self.include("<tuple>");
}
if self.dependencies.needs_wit {
self.include("\"wit.h\"");
}
if self.dependencies.needs_memory {
self.include("<memory>");
}
if self.dependencies.needs_array {
self.include("<array>");
}
if self.dependencies.needs_bit {
self.include("<bit>");
}
}
fn start_new_file(&mut self, condition: Option<bool>) -> FileContext {
if condition == Some(true) || self.opts.split_interfaces {
FileContext {
includes: std::mem::take(&mut self.includes),
src: std::mem::take(&mut self.h_src),
dependencies: std::mem::take(&mut self.dependencies),
}
} else {
Default::default()
}
}
fn finish_file(&mut self, namespace: &[String], store: FileContext) {
if !store.src.src.is_empty() {
let mut header = String::default();
self.finish_includes();
self.h_src.change_namespace(&[]);
uwriteln!(header, "#pragma once");
for include in self.includes.iter() {
uwriteln!(header, "#include {include}");
}
header.push_str(&self.h_src.src);
let mut filename = namespace.join("-");
filename.push_str(".h");
if self.opts.format {
Self::clang_format(&mut header);
}
self.user_class_files.insert(filename.clone(), header);
let _ = std::mem::replace(&mut self.includes, store.includes);
let _ = std::mem::replace(&mut self.h_src, store.src);
let _ = std::mem::replace(&mut self.dependencies, store.dependencies);
self.includes.push(String::from("\"") + &filename + "\"");
}
}
}
#[derive(Default)]
struct FileContext {
includes: Vec<String>,
src: SourceWithState,
dependencies: Includes,
}
impl WorldGenerator for Cpp {
fn preprocess(&mut self, resolve: &Resolve, world: WorldId) {
let name = &resolve.worlds[world].name;
self.world = name.to_string();
self.types.analyze(resolve);
self.world_id = Some(world);
uwriteln!(
self.c_src_head,
r#"#include "{}_cpp.h"
#include <cstdlib> // realloc
extern "C" void *cabi_realloc(void *ptr, size_t old_size, size_t align, size_t new_size);
__attribute__((__weak__, __export_name__("cabi_realloc")))
void *cabi_realloc(void *ptr, size_t old_size, size_t align, size_t new_size) {{
(void) old_size;
if (new_size == 0) return (void*) align;
void *ret = realloc(ptr, new_size);
if (!ret) abort();
return ret;
}}
"#,
self.world.to_snake_case(),
);
}
fn import_interface(
&mut self,
resolve: &Resolve,
name: &WorldKey,
id: InterfaceId,
implements: Option<InterfaceId>,
_files: &mut Files,
) -> anyhow::Result<()> {
self.imported_interfaces.insert(id);
let full_name = resolve.name_world_key(name);
match self.opts.with.iter().find(|e| e.0 == full_name) {
None => {
if let Some(prefix) = self
.interface_prefixes
.get(&(Direction::Import, name.clone()))
{
self.import_prefix = Some(prefix.clone());
}
let store = self.start_new_file(None);
let wasm_import_module =
wit_bindgen_core::wasm_import_module_name(resolve, name, implements);
let binding = Some(name);
let should_gen_types = self.implements_types_generated.insert(id);
let mut r#gen = self.interface(resolve, binding, true, Some(wasm_import_module));
r#gen.interface = Some(id);
if let (WorldKey::Name(label), Some(_)) = (name, implements) {
r#gen.implements_label = Some((label.clone(), false));
}
if should_gen_types {
r#gen.types(id);
}
let namespace = r#gen.freestanding_namespace(id, false);
for (_name, func) in resolve.interfaces[id].functions.iter() {
if matches!(func.kind, FunctionKind::Freestanding) {
r#gen.r#gen.h_src.change_namespace(&namespace);
r#gen.generate_function(
func,
&TypeOwner::Interface(id),
AbiVariant::GuestImport,
);
}
}
self.finish_file(&namespace, store);
}
Some((_, val)) => {
let with_quotes = format!("\"{val}\"");
if !self.includes.contains(&with_quotes) {
self.includes.push(with_quotes);
}
}
}
let _ = self.import_prefix.take();
Ok(())
}
fn export_interface(
&mut self,
resolve: &Resolve,
name: &WorldKey,
id: InterfaceId,
implements: Option<InterfaceId>,
_files: &mut Files,
) -> anyhow::Result<()> {
let old_prefix = self.opts.export_prefix.clone();
if let Some(prefix) = self
.interface_prefixes
.get(&(Direction::Export, name.clone()))
{
self.opts.export_prefix =
Some(prefix.clone() + old_prefix.as_ref().unwrap_or(&String::new()));
}
let store = self.start_new_file(None);
self.h_src
.src
.push_str(&format!("// export_interface {name:?}\n"));
self.imported_interfaces.remove(&id);
let wasm_import_module =
wit_bindgen_core::wasm_import_module_name(resolve, name, implements);
let binding = Some(name);
let should_gen_types = self.implements_types_generated.insert(id);
let mut r#gen = self.interface(resolve, binding, false, Some(wasm_import_module));
r#gen.interface = Some(id);
if let (WorldKey::Name(label), Some(_)) = (name, implements) {
r#gen.implements_label = Some((label.clone(), true));
}
if should_gen_types {
r#gen.types(id);
}
let namespace = r#gen.freestanding_namespace(id, true);
for (_name, func) in resolve.interfaces[id].functions.iter() {
if matches!(func.kind, FunctionKind::Freestanding) {
r#gen.r#gen.h_src.change_namespace(&namespace);
r#gen.generate_function(func, &TypeOwner::Interface(id), AbiVariant::GuestExport);
}
}
self.finish_file(&namespace, store);
self.opts.export_prefix = old_prefix;
Ok(())
}
fn import_funcs(
&mut self,
resolve: &Resolve,
world: WorldId,
funcs: &[(&str, &Function)],
_files: &mut Files,
) {
let name = WorldKey::Name("$root".to_string()); //WorldKey::Name(resolve.worlds[world].name.clone());
let wasm_import_module = resolve.name_world_key(&name);
let binding = Some(name);
let mut r#gen = self.interface(resolve, binding.as_ref(), true, Some(wasm_import_module));
let namespace = namespace(resolve, &TypeOwner::World(world), false, &r#gen.r#gen.opts);
for (_name, func) in funcs.iter() {
if matches!(func.kind, FunctionKind::Freestanding) {
r#gen.r#gen.h_src.change_namespace(&namespace);
r#gen.generate_function(func, &TypeOwner::World(world), AbiVariant::GuestImport);
}
}
}
fn export_funcs(
&mut self,
resolve: &Resolve,
world: WorldId,
funcs: &[(&str, &Function)],
_files: &mut Files,
) -> anyhow::Result<()> {
let name = WorldKey::Name(resolve.worlds[world].name.clone());
let binding = Some(name);
let mut r#gen = self.interface(resolve, binding.as_ref(), false, None);
let namespace = namespace(resolve, &TypeOwner::World(world), true, &r#gen.r#gen.opts);
for (_name, func) in funcs.iter() {
if matches!(func.kind, FunctionKind::Freestanding) {
r#gen.r#gen.h_src.change_namespace(&namespace);
r#gen.generate_function(func, &TypeOwner::World(world), AbiVariant::GuestExport);
}
}
Ok(())
}
fn import_types(
&mut self,
resolve: &Resolve,
_world: WorldId,
types: &[(&str, TypeId)],
_files: &mut Files,
) {
let mut r#gen = self.interface(resolve, None, true, Some("$root".to_string()));
for (name, id) in types.iter() {
r#gen.define_type(name, *id);
}
}
fn finish(
&mut self,
resolve: &Resolve,
world_id: WorldId,
files: &mut Files,
) -> std::result::Result<(), anyhow::Error> {
let world = &resolve.worlds[world_id];
let snake = world.name.to_snake_case();
let linking_symbol = wit_bindgen_c::component_type_object::linking_symbol(&world.name);
let mut h_str = SourceWithState::default();
let mut c_str = SourceWithState::default();
let version = env!("CARGO_PKG_VERSION");
uwriteln!(
h_str.src,
"// Generated by `wit-bindgen` {version}. DO NOT EDIT!"
);
uwrite!(
h_str.src,
"#ifndef __CPP_GUEST_BINDINGS_{0}_H
#define __CPP_GUEST_BINDINGS_{0}_H\n",
world.name.to_shouty_snake_case(),
);
self.finish_includes();
for include in self.includes.iter() {
uwriteln!(h_str.src, "#include {include}");
}
uwriteln!(
c_str.src,
"// Generated by `wit-bindgen` {version}. DO NOT EDIT!"
);
uwriteln!(
c_str.src,
"\n// Ensure that the *_component_type.o object is linked in"
);
uwrite!(
c_str.src,
"#ifdef __wasm32__
extern \"C\" void {linking_symbol}(void);
__attribute__((used))
void {linking_symbol}_public_use_in_this_compilation_unit(void) {{
{linking_symbol}();
}}
#endif
",
);
if self.dependencies.needs_assert {
uwriteln!(c_str.src, "#include <assert.h>");
}
h_str.change_namespace(&Vec::default());
self.c_src.change_namespace(&Vec::default());
c_str.src.push_str(&self.c_src_head);
c_str.src.push_str(&self.extern_c_decls);
c_str.src.push_str(&self.c_src.src);
self.h_src.change_namespace(&Vec::default());
h_str.src.push_str(&self.h_src.src);
uwriteln!(c_str.src, "\n// Component Adapters");
uwriteln!(
h_str.src,
"
#endif"
);
if self.opts.format {
Self::clang_format(c_str.src.as_mut_string());
Self::clang_format(h_str.src.as_mut_string());
}
files.push(&format!("{snake}.cpp"), c_str.src.as_bytes());
files.push(&format!("{snake}_cpp.h"), h_str.src.as_bytes());
for (name, content) in self.user_class_files.iter() {
// if the user class file exists create an updated .template
let dst = match &self.opts.out_dir {
Some(path) => path.join(name),
None => name.into(),
};
if std::path::Path::exists(&dst) {
files.push(&(String::from(name) + ".template"), content.as_bytes());
} else {
files.push(name, content.as_bytes());
}
}
files.push(
&format!("{snake}_component_type.o",),
wit_bindgen_c::component_type_object::object(
resolve,
world_id,
&world.name,
wit_component::StringEncoding::UTF8,
None,
)
.unwrap()
.as_slice(),
);
if self.dependencies.needs_wit {
files.push("wit.h", include_bytes!("../helper-types/wit.h"));
}
Ok(())
}
}
fn namespace(resolve: &Resolve, owner: &TypeOwner, guest_export: bool, opts: &Opts) -> Vec<String> {
let mut result = Vec::default();
if let Some(prefix) = &opts.internal_prefix {
result.push(prefix.clone());
}
if guest_export {
result.push(String::from("exports"));
}
match owner {
TypeOwner::World(w) => result.push(to_c_ident(&resolve.worlds[*w].name)),
TypeOwner::Interface(i) => {
let iface = &resolve.interfaces[*i];
let pkg_id = iface.package.unwrap();
let pkg = &resolve.packages[pkg_id];
result.push(to_c_ident(&pkg.name.namespace));
// Use name_package_module to get version-specific package names
result.push(to_c_ident(&name_package_module(resolve, pkg_id)));
if let Some(name) = &iface.name {
result.push(to_c_ident(name));
}
}
TypeOwner::None => (),
}
result
}
impl SourceWithState {
fn change_namespace(&mut self, target: &[String]) {
let mut same = 0;
// itertools::fold_while?
for (a, b) in self.namespace.iter().zip(target.iter()) {
if a == b {
same += 1;
} else {
break;
}
}
for _i in same..self.namespace.len() {
uwrite!(self.src, "}}\n");
}
self.namespace.truncate(same);
for i in target.iter().skip(same) {
uwrite!(self.src, "namespace {} {{\n", i);
self.namespace.push(i.clone());
}
}
fn qualify(&mut self, target: &[String]) {
let mut same = 0;
// itertools::fold_while?
for (a, b) in self.namespace.iter().zip(target.iter()) {
if a == b {
same += 1;
} else {
break;
}
}
if same == 0 && !target.is_empty() {
// if the root namespace exists below the current namespace we need to start at root
// Also ensure absolute qualification when crossing from exports to imports
if self.namespace.contains(target.first().unwrap())
|| (self.namespace.first().map(|s| s.as_str()) == Some("exports")
&& target.first().map(|s| s.as_str()) != Some("exports"))
{
self.src.push_str("::");
}
}
if same == target.len() && self.namespace.len() != target.len() && same > 0 {
// namespace is parent, qualify at least one namespace (and cross fingers)
uwrite!(self.src, "{}::", target[same - 1]);
} else {
for i in target.iter().skip(same) {
uwrite!(self.src, "{i}::");
}
}
}
}
struct CppInterfaceGenerator<'a> {
_src: Source,
r#gen: &'a mut Cpp,
resolve: &'a Resolve,
interface: Option<InterfaceId>,
_name: Option<&'a WorldKey>,
sizes: SizeAlign,
in_guest_import: bool,
pub wasm_import_module: Option<String>,
/// When generating for an implements item, the label and whether it's an export.
implements_label: Option<(String, bool)>,
}
impl CppInterfaceGenerator<'_> {
/// Compute the namespace for freestanding functions in an interface.
/// Uses `implements_label` when set, otherwise falls back to the standard
/// namespace computation.
fn freestanding_namespace(&self, iface: InterfaceId, guest_export: bool) -> Vec<String> {
if let Some((label, is_export)) = &self.implements_label {
let mut ns = Vec::new();
if let Some(prefix) = &self.r#gen.opts.internal_prefix {
ns.push(prefix.clone());
}
if *is_export {
ns.push(String::from("exports"));
}
ns.push(to_c_ident(label));
ns
} else {
namespace(
self.resolve,
&TypeOwner::Interface(iface),
guest_export,
&self.r#gen.opts,
)
}
}
fn types(&mut self, iface: InterfaceId) {
let iface_data = &self.resolve().interfaces[iface];
// First pass: emit forward declarations for all resources
// This ensures resources can reference each other in method signatures
for (name, id) in iface_data.types.iter() {
let ty = &self.resolve().types[*id];
if matches!(&ty.kind, TypeDefKind::Resource) {
let pascal = name.to_upper_camel_case();
let guest_import = self.r#gen.imported_interfaces.contains(&iface);
let namespc = namespace(self.resolve, &ty.owner, !guest_import, &self.r#gen.opts);
self.r#gen.h_src.change_namespace(&namespc);
uwriteln!(self.r#gen.h_src.src, "class {pascal};");
}
}
// Second pass: emit full type definitions
for (name, id) in iface_data.types.iter() {
self.define_type(name, *id);
}
}
fn define_type(&mut self, name: &str, id: TypeId) {
let ty = &self.resolve().types[id];
match &ty.kind {
TypeDefKind::Record(record) => self.type_record(id, name, record, &ty.docs),
TypeDefKind::Resource => self.type_resource(id, name, &ty.docs),
TypeDefKind::Flags(flags) => self.type_flags(id, name, flags, &ty.docs),
TypeDefKind::Tuple(tuple) => self.type_tuple(id, name, tuple, &ty.docs),
TypeDefKind::Enum(enum_) => self.type_enum(id, name, enum_, &ty.docs),
TypeDefKind::Variant(variant) => self.type_variant(id, name, variant, &ty.docs),
TypeDefKind::Option(t) => self.type_option(id, name, t, &ty.docs),
TypeDefKind::Result(r) => self.type_result(id, name, r, &ty.docs),
TypeDefKind::List(t) => self.type_list(id, name, t, &ty.docs),
TypeDefKind::Type(t) => self.type_alias(id, name, t, &ty.docs),
TypeDefKind::Future(_) => todo!("generate for future"),
TypeDefKind::Stream(_) => todo!("generate for stream"),
TypeDefKind::Handle(_) => todo!("generate for handle"),
TypeDefKind::FixedLengthList(_, _) => todo!(),
TypeDefKind::Map(_, _) => todo!(),
TypeDefKind::Unknown => unreachable!(),
}
}
/// This describes the C++ side name
fn func_namespace_name(
&self,
func: &Function,
guest_export: bool,
cpp_file: bool,
) -> (Vec<String>, String) {
let (object, owner) = match &func.kind {
FunctionKind::Freestanding => None,
FunctionKind::Method(i) => Some(i),
FunctionKind::Static(i) => Some(i),
FunctionKind::Constructor(i) => Some(i),
FunctionKind::AsyncFreestanding => todo!(),
FunctionKind::AsyncMethod(_id) => todo!(),
FunctionKind::AsyncStatic(_id) => todo!(),
}
.map(|i| {
let ty = &self.resolve.types[*i];
(ty.name.as_ref().unwrap().to_pascal_case(), ty.owner)
})
.unwrap_or((
Default::default(),
self.interface
.map(TypeOwner::Interface)
.unwrap_or(TypeOwner::World(self.r#gen.world_id.unwrap())),
));
let mut namespace = if let Some((label, is_export)) = &self.implements_label {
// For implements items, use the label as namespace
let mut ns = Vec::new();
if let Some(prefix) = &self.r#gen.opts.internal_prefix {
ns.push(prefix.clone());
}
if *is_export {
ns.push(String::from("exports"));
}
ns.push(to_c_ident(label));
ns
} else {
namespace(self.resolve, &owner, guest_export, &self.r#gen.opts)
};
let is_drop = is_special_method(func);
let func_name_h = if !matches!(&func.kind, FunctionKind::Freestanding) {
namespace.push(object.clone());
if let FunctionKind::Constructor(_i) = &func.kind {
// Fallible constructors return result<T, E> and are static factory methods
let is_fallible_constructor =
self.r#gen.is_fallible_constructor(self.resolve, func);
if is_fallible_constructor {
String::from("Create")
} else if guest_export && cpp_file {
String::from("New")
} else {
object.clone()
}
} else {
match is_drop {
SpecialMethod::ResourceDrop => {