1 use crate::gen::block::Block;
2 use crate::gen::nested::NamespaceEntries;
3 use crate::gen::out::OutFile;
4 use crate::gen::{builtin, include, Opt};
5 use crate::syntax::atom::Atom::{self, *};
6 use crate::syntax::instantiate::{ImplKey, NamedImplKey};
7 use crate::syntax::map::UnorderedMap as Map;
8 use crate::syntax::set::UnorderedSet;
9 use crate::syntax::symbol::Symbol;
10 use crate::syntax::trivial::{self, TrivialReason};
11 use crate::syntax::{
12     derive, mangle, Api, Enum, ExternFn, ExternType, Pair, Signature, Struct, Trait, Type,
13     TypeAlias, Types, Var,
14 };
15 use proc_macro2::Ident;
16 
gen(apis: &[Api], types: &Types, opt: &Opt, header: bool) -> Vec<u8>17 pub(super) fn gen(apis: &[Api], types: &Types, opt: &Opt, header: bool) -> Vec<u8> {
18     let mut out_file = OutFile::new(header, opt, types);
19     let out = &mut out_file;
20 
21     pick_includes_and_builtins(out, apis);
22     out.include.extend(&opt.include);
23 
24     write_forward_declarations(out, apis);
25     write_data_structures(out, apis);
26     write_functions(out, apis);
27     write_generic_instantiations(out);
28 
29     builtin::write(out);
30     include::write(out);
31 
32     out_file.content()
33 }
34 
write_forward_declarations(out: &mut OutFile, apis: &[Api])35 fn write_forward_declarations(out: &mut OutFile, apis: &[Api]) {
36     let needs_forward_declaration = |api: &&Api| match api {
37         Api::Struct(_) | Api::CxxType(_) | Api::RustType(_) => true,
38         Api::Enum(enm) => !out.types.cxx.contains(&enm.name.rust),
39         _ => false,
40     };
41 
42     let apis_by_namespace =
43         NamespaceEntries::new(apis.iter().filter(needs_forward_declaration).collect());
44 
45     write(out, &apis_by_namespace, 0);
46 
47     fn write(out: &mut OutFile, ns_entries: &NamespaceEntries, indent: usize) {
48         let apis = ns_entries.direct_content();
49 
50         for api in apis {
51             write!(out, "{:1$}", "", indent);
52             match api {
53                 Api::Struct(strct) => write_struct_decl(out, &strct.name),
54                 Api::Enum(enm) => write_enum_decl(out, enm),
55                 Api::CxxType(ety) => write_struct_using(out, &ety.name),
56                 Api::RustType(ety) => write_struct_decl(out, &ety.name),
57                 _ => unreachable!(),
58             }
59         }
60 
61         for (namespace, nested_ns_entries) in ns_entries.nested_content() {
62             writeln!(out, "{:2$}namespace {} {{", "", namespace, indent);
63             write(out, nested_ns_entries, indent + 2);
64             writeln!(out, "{:1$}}}", "", indent);
65         }
66     }
67 }
68 
write_data_structures<'a>(out: &mut OutFile<'a>, apis: &'a [Api])69 fn write_data_structures<'a>(out: &mut OutFile<'a>, apis: &'a [Api]) {
70     let mut methods_for_type = Map::new();
71     for api in apis {
72         if let Api::CxxFunction(efn) | Api::RustFunction(efn) = api {
73             if let Some(receiver) = &efn.sig.receiver {
74                 methods_for_type
75                     .entry(&receiver.ty.rust)
76                     .or_insert_with(Vec::new)
77                     .push(efn);
78             }
79         }
80     }
81 
82     let mut structs_written = UnorderedSet::new();
83     let mut toposorted_structs = out.types.toposorted_structs.iter();
84     for api in apis {
85         match api {
86             Api::Struct(strct) if !structs_written.contains(&strct.name.rust) => {
87                 for next in &mut toposorted_structs {
88                     if !out.types.cxx.contains(&strct.name.rust) {
89                         out.next_section();
90                         let methods = methods_for_type
91                             .get(&strct.name.rust)
92                             .map(Vec::as_slice)
93                             .unwrap_or_default();
94                         write_struct(out, next, methods);
95                     }
96                     structs_written.insert(&next.name.rust);
97                     if next.name.rust == strct.name.rust {
98                         break;
99                     }
100                 }
101             }
102             Api::Enum(enm) => {
103                 out.next_section();
104                 if out.types.cxx.contains(&enm.name.rust) {
105                     check_enum(out, enm);
106                 } else {
107                     write_enum(out, enm);
108                 }
109             }
110             Api::RustType(ety) => {
111                 out.next_section();
112                 let methods = methods_for_type
113                     .get(&ety.name.rust)
114                     .map(Vec::as_slice)
115                     .unwrap_or_default();
116                 write_opaque_type(out, ety, methods);
117             }
118             _ => {}
119         }
120     }
121 
122     if out.header {
123         return;
124     }
125 
126     out.set_namespace(Default::default());
127 
128     out.next_section();
129     for api in apis {
130         if let Api::TypeAlias(ety) = api {
131             if let Some(reasons) = out.types.required_trivial.get(&ety.name.rust) {
132                 check_trivial_extern_type(out, ety, reasons)
133             }
134         }
135     }
136 }
137 
write_functions<'a>(out: &mut OutFile<'a>, apis: &'a [Api])138 fn write_functions<'a>(out: &mut OutFile<'a>, apis: &'a [Api]) {
139     if !out.header {
140         for api in apis {
141             match api {
142                 Api::Struct(strct) => write_struct_operator_decls(out, strct),
143                 Api::RustType(ety) => write_opaque_type_layout_decls(out, ety),
144                 Api::CxxFunction(efn) => write_cxx_function_shim(out, efn),
145                 Api::RustFunction(efn) => write_rust_function_decl(out, efn),
146                 _ => {}
147             }
148         }
149 
150         write_std_specializations(out, apis);
151     }
152 
153     for api in apis {
154         match api {
155             Api::Struct(strct) => write_struct_operators(out, strct),
156             Api::RustType(ety) => write_opaque_type_layout(out, ety),
157             Api::RustFunction(efn) => {
158                 out.next_section();
159                 write_rust_function_shim(out, efn);
160             }
161             _ => {}
162         }
163     }
164 }
165 
write_std_specializations(out: &mut OutFile, apis: &[Api])166 fn write_std_specializations(out: &mut OutFile, apis: &[Api]) {
167     out.set_namespace(Default::default());
168     out.begin_block(Block::Namespace("std"));
169 
170     for api in apis {
171         if let Api::Struct(strct) = api {
172             if derive::contains(&strct.derives, Trait::Hash) {
173                 out.next_section();
174                 out.include.cstddef = true;
175                 out.include.functional = true;
176                 let qualified = strct.name.to_fully_qualified();
177                 writeln!(out, "template <> struct hash<{}> {{", qualified);
178                 writeln!(
179                     out,
180                     "  ::std::size_t operator()(const {} &self) const noexcept {{",
181                     qualified,
182                 );
183                 let link_name = mangle::operator(&strct.name, "hash");
184                 write!(out, "    return ::");
185                 for name in &strct.name.namespace {
186                     write!(out, "{}::", name);
187                 }
188                 writeln!(out, "{}(self);", link_name);
189                 writeln!(out, "  }}");
190                 writeln!(out, "}};");
191             }
192         }
193     }
194 
195     out.end_block(Block::Namespace("std"));
196 }
197 
pick_includes_and_builtins(out: &mut OutFile, apis: &[Api])198 fn pick_includes_and_builtins(out: &mut OutFile, apis: &[Api]) {
199     for api in apis {
200         if let Api::Include(include) = api {
201             out.include.insert(include);
202         }
203     }
204 
205     for ty in out.types {
206         match ty {
207             Type::Ident(ident) => match Atom::from(&ident.rust) {
208                 Some(U8) | Some(U16) | Some(U32) | Some(U64) | Some(I8) | Some(I16) | Some(I32)
209                 | Some(I64) => out.include.cstdint = true,
210                 Some(Usize) => out.include.cstddef = true,
211                 Some(Isize) => out.builtin.rust_isize = true,
212                 Some(CxxString) => out.include.string = true,
213                 Some(RustString) => out.builtin.rust_string = true,
214                 Some(Bool) | Some(Char) | Some(F32) | Some(F64) | None => {}
215             },
216             Type::RustBox(_) => out.builtin.rust_box = true,
217             Type::RustVec(_) => out.builtin.rust_vec = true,
218             Type::UniquePtr(_) => out.include.memory = true,
219             Type::SharedPtr(_) | Type::WeakPtr(_) => out.include.memory = true,
220             Type::Str(_) => out.builtin.rust_str = true,
221             Type::CxxVector(_) => out.include.vector = true,
222             Type::Fn(_) => out.builtin.rust_fn = true,
223             Type::SliceRef(_) => out.builtin.rust_slice = true,
224             Type::Array(_) => out.include.array = true,
225             Type::Ref(_) | Type::Void(_) | Type::Ptr(_) => {}
226         }
227     }
228 }
229 
write_struct<'a>(out: &mut OutFile<'a>, strct: &'a Struct, methods: &[&ExternFn])230 fn write_struct<'a>(out: &mut OutFile<'a>, strct: &'a Struct, methods: &[&ExternFn]) {
231     let operator_eq = derive::contains(&strct.derives, Trait::PartialEq);
232     let operator_ord = derive::contains(&strct.derives, Trait::PartialOrd);
233 
234     out.set_namespace(&strct.name.namespace);
235     let guard = format!("CXXBRIDGE1_STRUCT_{}", strct.name.to_symbol());
236     writeln!(out, "#ifndef {}", guard);
237     writeln!(out, "#define {}", guard);
238     for line in strct.doc.to_string().lines() {
239         writeln!(out, "//{}", line);
240     }
241     writeln!(out, "struct {} final {{", strct.name.cxx);
242 
243     for field in &strct.fields {
244         for line in field.doc.to_string().lines() {
245             writeln!(out, "  //{}", line);
246         }
247         write!(out, "  ");
248         write_type_space(out, &field.ty);
249         writeln!(out, "{};", field.name.cxx);
250     }
251 
252     writeln!(out);
253 
254     for method in methods {
255         write!(out, "  ");
256         let sig = &method.sig;
257         let local_name = method.name.cxx.to_string();
258         write_rust_function_shim_decl(out, &local_name, sig, false);
259         writeln!(out, ";");
260     }
261 
262     if operator_eq {
263         writeln!(
264             out,
265             "  bool operator==(const {} &) const noexcept;",
266             strct.name.cxx,
267         );
268         writeln!(
269             out,
270             "  bool operator!=(const {} &) const noexcept;",
271             strct.name.cxx,
272         );
273     }
274 
275     if operator_ord {
276         writeln!(
277             out,
278             "  bool operator<(const {} &) const noexcept;",
279             strct.name.cxx,
280         );
281         writeln!(
282             out,
283             "  bool operator<=(const {} &) const noexcept;",
284             strct.name.cxx,
285         );
286         writeln!(
287             out,
288             "  bool operator>(const {} &) const noexcept;",
289             strct.name.cxx,
290         );
291         writeln!(
292             out,
293             "  bool operator>=(const {} &) const noexcept;",
294             strct.name.cxx,
295         );
296     }
297 
298     out.include.type_traits = true;
299     writeln!(out, "  using IsRelocatable = ::std::true_type;");
300 
301     writeln!(out, "}};");
302     writeln!(out, "#endif // {}", guard);
303 }
304 
write_struct_decl(out: &mut OutFile, ident: &Pair)305 fn write_struct_decl(out: &mut OutFile, ident: &Pair) {
306     writeln!(out, "struct {};", ident.cxx);
307 }
308 
write_enum_decl(out: &mut OutFile, enm: &Enum)309 fn write_enum_decl(out: &mut OutFile, enm: &Enum) {
310     write!(out, "enum class {} : ", enm.name.cxx);
311     write_atom(out, enm.repr);
312     writeln!(out, ";");
313 }
314 
write_struct_using(out: &mut OutFile, ident: &Pair)315 fn write_struct_using(out: &mut OutFile, ident: &Pair) {
316     writeln!(out, "using {} = {};", ident.cxx, ident.to_fully_qualified());
317 }
318 
write_opaque_type<'a>(out: &mut OutFile<'a>, ety: &'a ExternType, methods: &[&ExternFn])319 fn write_opaque_type<'a>(out: &mut OutFile<'a>, ety: &'a ExternType, methods: &[&ExternFn]) {
320     out.set_namespace(&ety.name.namespace);
321     let guard = format!("CXXBRIDGE1_STRUCT_{}", ety.name.to_symbol());
322     writeln!(out, "#ifndef {}", guard);
323     writeln!(out, "#define {}", guard);
324     for line in ety.doc.to_string().lines() {
325         writeln!(out, "//{}", line);
326     }
327 
328     out.builtin.opaque = true;
329     writeln!(
330         out,
331         "struct {} final : public ::rust::Opaque {{",
332         ety.name.cxx,
333     );
334 
335     for method in methods {
336         write!(out, "  ");
337         let sig = &method.sig;
338         let local_name = method.name.cxx.to_string();
339         write_rust_function_shim_decl(out, &local_name, sig, false);
340         writeln!(out, ";");
341     }
342 
343     writeln!(out, "  ~{}() = delete;", ety.name.cxx);
344     writeln!(out);
345 
346     out.builtin.layout = true;
347     out.include.cstddef = true;
348     writeln!(out, "private:");
349     writeln!(out, "  friend ::rust::layout;");
350     writeln!(out, "  struct layout {{");
351     writeln!(out, "    static ::std::size_t size() noexcept;");
352     writeln!(out, "    static ::std::size_t align() noexcept;");
353     writeln!(out, "  }};");
354     writeln!(out, "}};");
355     writeln!(out, "#endif // {}", guard);
356 }
357 
write_enum<'a>(out: &mut OutFile<'a>, enm: &'a Enum)358 fn write_enum<'a>(out: &mut OutFile<'a>, enm: &'a Enum) {
359     out.set_namespace(&enm.name.namespace);
360     let guard = format!("CXXBRIDGE1_ENUM_{}", enm.name.to_symbol());
361     writeln!(out, "#ifndef {}", guard);
362     writeln!(out, "#define {}", guard);
363     for line in enm.doc.to_string().lines() {
364         writeln!(out, "//{}", line);
365     }
366     write!(out, "enum class {} : ", enm.name.cxx);
367     write_atom(out, enm.repr);
368     writeln!(out, " {{");
369     for variant in &enm.variants {
370         for line in variant.doc.to_string().lines() {
371             writeln!(out, "  //{}", line);
372         }
373         writeln!(out, "  {} = {},", variant.name.cxx, variant.discriminant);
374     }
375     writeln!(out, "}};");
376     writeln!(out, "#endif // {}", guard);
377 }
378 
check_enum<'a>(out: &mut OutFile<'a>, enm: &'a Enum)379 fn check_enum<'a>(out: &mut OutFile<'a>, enm: &'a Enum) {
380     out.set_namespace(&enm.name.namespace);
381     out.include.type_traits = true;
382     writeln!(
383         out,
384         "static_assert(::std::is_enum<{}>::value, \"expected enum\");",
385         enm.name.cxx,
386     );
387     write!(out, "static_assert(sizeof({}) == sizeof(", enm.name.cxx);
388     write_atom(out, enm.repr);
389     writeln!(out, "), \"incorrect size\");");
390     for variant in &enm.variants {
391         write!(out, "static_assert(static_cast<");
392         write_atom(out, enm.repr);
393         writeln!(
394             out,
395             ">({}::{}) == {}, \"disagrees with the value in #[cxx::bridge]\");",
396             enm.name.cxx, variant.name.cxx, variant.discriminant,
397         );
398     }
399 }
400 
check_trivial_extern_type(out: &mut OutFile, alias: &TypeAlias, reasons: &[TrivialReason])401 fn check_trivial_extern_type(out: &mut OutFile, alias: &TypeAlias, reasons: &[TrivialReason]) {
402     // NOTE: The following static assertion is just nice-to-have and not
403     // necessary for soundness. That's because triviality is always declared by
404     // the user in the form of an unsafe impl of cxx::ExternType:
405     //
406     //     unsafe impl ExternType for MyType {
407     //         type Id = cxx::type_id!("...");
408     //         type Kind = cxx::kind::Trivial;
409     //     }
410     //
411     // Since the user went on the record with their unsafe impl to unsafely
412     // claim they KNOW that the type is trivial, it's fine for that to be on
413     // them if that were wrong. However, in practice correctly reasoning about
414     // the relocatability of C++ types is challenging, particularly if the type
415     // definition were to change over time, so for now we add this check.
416     //
417     // There may be legitimate reasons to opt out of this assertion for support
418     // of types that the programmer knows are soundly Rust-movable despite not
419     // being recognized as such by the C++ type system due to a move constructor
420     // or destructor. To opt out of the relocatability check, they need to do
421     // one of the following things in any header used by `include!` in their
422     // bridge.
423     //
424     //      --- if they define the type:
425     //      struct MyType {
426     //        ...
427     //    +   using IsRelocatable = std::true_type;
428     //      };
429     //
430     //      --- otherwise:
431     //    + template <>
432     //    + struct rust::IsRelocatable<MyType> : std::true_type {};
433     //
434 
435     let id = alias.name.to_fully_qualified();
436     out.builtin.relocatable = true;
437     writeln!(out, "static_assert(");
438     writeln!(out, "    ::rust::IsRelocatable<{}>::value,", id);
439     writeln!(
440         out,
441         "    \"type {} should be trivially move constructible and trivially destructible in C++ to be used as {} in Rust\");",
442         id.trim_start_matches("::"),
443         trivial::as_what(&alias.name, reasons),
444     );
445 }
446 
write_struct_operator_decls<'a>(out: &mut OutFile<'a>, strct: &'a Struct)447 fn write_struct_operator_decls<'a>(out: &mut OutFile<'a>, strct: &'a Struct) {
448     out.set_namespace(&strct.name.namespace);
449     out.begin_block(Block::ExternC);
450 
451     if derive::contains(&strct.derives, Trait::PartialEq) {
452         let link_name = mangle::operator(&strct.name, "eq");
453         writeln!(
454             out,
455             "bool {}(const {1} &, const {1} &) noexcept;",
456             link_name, strct.name.cxx,
457         );
458 
459         if !derive::contains(&strct.derives, Trait::Eq) {
460             let link_name = mangle::operator(&strct.name, "ne");
461             writeln!(
462                 out,
463                 "bool {}(const {1} &, const {1} &) noexcept;",
464                 link_name, strct.name.cxx,
465             );
466         }
467     }
468 
469     if derive::contains(&strct.derives, Trait::PartialOrd) {
470         let link_name = mangle::operator(&strct.name, "lt");
471         writeln!(
472             out,
473             "bool {}(const {1} &, const {1} &) noexcept;",
474             link_name, strct.name.cxx,
475         );
476 
477         let link_name = mangle::operator(&strct.name, "le");
478         writeln!(
479             out,
480             "bool {}(const {1} &, const {1} &) noexcept;",
481             link_name, strct.name.cxx,
482         );
483 
484         if !derive::contains(&strct.derives, Trait::Ord) {
485             let link_name = mangle::operator(&strct.name, "gt");
486             writeln!(
487                 out,
488                 "bool {}(const {1} &, const {1} &) noexcept;",
489                 link_name, strct.name.cxx,
490             );
491 
492             let link_name = mangle::operator(&strct.name, "ge");
493             writeln!(
494                 out,
495                 "bool {}(const {1} &, const {1} &) noexcept;",
496                 link_name, strct.name.cxx,
497             );
498         }
499     }
500 
501     if derive::contains(&strct.derives, Trait::Hash) {
502         out.include.cstddef = true;
503         let link_name = mangle::operator(&strct.name, "hash");
504         writeln!(
505             out,
506             "::std::size_t {}(const {} &) noexcept;",
507             link_name, strct.name.cxx,
508         );
509     }
510 
511     out.end_block(Block::ExternC);
512 }
513 
write_struct_operators<'a>(out: &mut OutFile<'a>, strct: &'a Struct)514 fn write_struct_operators<'a>(out: &mut OutFile<'a>, strct: &'a Struct) {
515     if out.header {
516         return;
517     }
518 
519     out.set_namespace(&strct.name.namespace);
520 
521     if derive::contains(&strct.derives, Trait::PartialEq) {
522         out.next_section();
523         writeln!(
524             out,
525             "bool {0}::operator==(const {0} &rhs) const noexcept {{",
526             strct.name.cxx,
527         );
528         let link_name = mangle::operator(&strct.name, "eq");
529         writeln!(out, "  return {}(*this, rhs);", link_name);
530         writeln!(out, "}}");
531 
532         out.next_section();
533         writeln!(
534             out,
535             "bool {0}::operator!=(const {0} &rhs) const noexcept {{",
536             strct.name.cxx,
537         );
538         if derive::contains(&strct.derives, Trait::Eq) {
539             writeln!(out, "  return !(*this == rhs);");
540         } else {
541             let link_name = mangle::operator(&strct.name, "ne");
542             writeln!(out, "  return {}(*this, rhs);", link_name);
543         }
544         writeln!(out, "}}");
545     }
546 
547     if derive::contains(&strct.derives, Trait::PartialOrd) {
548         out.next_section();
549         writeln!(
550             out,
551             "bool {0}::operator<(const {0} &rhs) const noexcept {{",
552             strct.name.cxx,
553         );
554         let link_name = mangle::operator(&strct.name, "lt");
555         writeln!(out, "  return {}(*this, rhs);", link_name);
556         writeln!(out, "}}");
557 
558         out.next_section();
559         writeln!(
560             out,
561             "bool {0}::operator<=(const {0} &rhs) const noexcept {{",
562             strct.name.cxx,
563         );
564         let link_name = mangle::operator(&strct.name, "le");
565         writeln!(out, "  return {}(*this, rhs);", link_name);
566         writeln!(out, "}}");
567 
568         out.next_section();
569         writeln!(
570             out,
571             "bool {0}::operator>(const {0} &rhs) const noexcept {{",
572             strct.name.cxx,
573         );
574         if derive::contains(&strct.derives, Trait::Ord) {
575             writeln!(out, "  return !(*this <= rhs);");
576         } else {
577             let link_name = mangle::operator(&strct.name, "gt");
578             writeln!(out, "  return {}(*this, rhs);", link_name);
579         }
580         writeln!(out, "}}");
581 
582         out.next_section();
583         writeln!(
584             out,
585             "bool {0}::operator>=(const {0} &rhs) const noexcept {{",
586             strct.name.cxx,
587         );
588         if derive::contains(&strct.derives, Trait::Ord) {
589             writeln!(out, "  return !(*this < rhs);");
590         } else {
591             let link_name = mangle::operator(&strct.name, "ge");
592             writeln!(out, "  return {}(*this, rhs);", link_name);
593         }
594         writeln!(out, "}}");
595     }
596 }
597 
write_opaque_type_layout_decls<'a>(out: &mut OutFile<'a>, ety: &'a ExternType)598 fn write_opaque_type_layout_decls<'a>(out: &mut OutFile<'a>, ety: &'a ExternType) {
599     out.set_namespace(&ety.name.namespace);
600     out.begin_block(Block::ExternC);
601 
602     let link_name = mangle::operator(&ety.name, "sizeof");
603     writeln!(out, "::std::size_t {}() noexcept;", link_name);
604 
605     let link_name = mangle::operator(&ety.name, "alignof");
606     writeln!(out, "::std::size_t {}() noexcept;", link_name);
607 
608     out.end_block(Block::ExternC);
609 }
610 
write_opaque_type_layout<'a>(out: &mut OutFile<'a>, ety: &'a ExternType)611 fn write_opaque_type_layout<'a>(out: &mut OutFile<'a>, ety: &'a ExternType) {
612     if out.header {
613         return;
614     }
615 
616     out.set_namespace(&ety.name.namespace);
617 
618     out.next_section();
619     let link_name = mangle::operator(&ety.name, "sizeof");
620     writeln!(
621         out,
622         "::std::size_t {}::layout::size() noexcept {{",
623         ety.name.cxx,
624     );
625     writeln!(out, "  return {}();", link_name);
626     writeln!(out, "}}");
627 
628     out.next_section();
629     let link_name = mangle::operator(&ety.name, "alignof");
630     writeln!(
631         out,
632         "::std::size_t {}::layout::align() noexcept {{",
633         ety.name.cxx,
634     );
635     writeln!(out, "  return {}();", link_name);
636     writeln!(out, "}}");
637 }
638 
begin_function_definition(out: &mut OutFile)639 fn begin_function_definition(out: &mut OutFile) {
640     if let Some(annotation) = &out.opt.cxx_impl_annotations {
641         write!(out, "{} ", annotation);
642     }
643 }
644 
write_cxx_function_shim<'a>(out: &mut OutFile<'a>, efn: &'a ExternFn)645 fn write_cxx_function_shim<'a>(out: &mut OutFile<'a>, efn: &'a ExternFn) {
646     out.next_section();
647     out.set_namespace(&efn.name.namespace);
648     out.begin_block(Block::ExternC);
649     begin_function_definition(out);
650     if efn.throws {
651         out.builtin.ptr_len = true;
652         write!(out, "::rust::repr::PtrLen ");
653     } else {
654         write_extern_return_type_space(out, &efn.ret);
655     }
656     let mangled = mangle::extern_fn(efn, out.types);
657     write!(out, "{}(", mangled);
658     if let Some(receiver) = &efn.receiver {
659         if !receiver.mutable {
660             write!(out, "const ");
661         }
662         write!(
663             out,
664             "{} &self",
665             out.types.resolve(&receiver.ty).name.to_fully_qualified(),
666         );
667     }
668     for (i, arg) in efn.args.iter().enumerate() {
669         if i > 0 || efn.receiver.is_some() {
670             write!(out, ", ");
671         }
672         if arg.ty == RustString {
673             write!(out, "const ");
674         } else if let Type::RustVec(_) = arg.ty {
675             write!(out, "const ");
676         }
677         write_extern_arg(out, arg);
678     }
679     let indirect_return = indirect_return(efn, out.types);
680     if indirect_return {
681         if !efn.args.is_empty() || efn.receiver.is_some() {
682             write!(out, ", ");
683         }
684         write_indirect_return_type_space(out, efn.ret.as_ref().unwrap());
685         write!(out, "*return$");
686     }
687     writeln!(out, ") noexcept {{");
688     write!(out, "  ");
689     write_return_type(out, &efn.ret);
690     match &efn.receiver {
691         None => write!(out, "(*{}$)(", efn.name.rust),
692         Some(receiver) => write!(
693             out,
694             "({}::*{}$)(",
695             out.types.resolve(&receiver.ty).name.to_fully_qualified(),
696             efn.name.rust,
697         ),
698     }
699     for (i, arg) in efn.args.iter().enumerate() {
700         if i > 0 {
701             write!(out, ", ");
702         }
703         write_type(out, &arg.ty);
704     }
705     write!(out, ")");
706     if let Some(receiver) = &efn.receiver {
707         if !receiver.mutable {
708             write!(out, " const");
709         }
710     }
711     write!(out, " = ");
712     match &efn.receiver {
713         None => write!(out, "{}", efn.name.to_fully_qualified()),
714         Some(receiver) => write!(
715             out,
716             "&{}::{}",
717             out.types.resolve(&receiver.ty).name.to_fully_qualified(),
718             efn.name.cxx,
719         ),
720     }
721     writeln!(out, ";");
722     write!(out, "  ");
723     if efn.throws {
724         out.builtin.ptr_len = true;
725         out.builtin.trycatch = true;
726         writeln!(out, "::rust::repr::PtrLen throw$;");
727         writeln!(out, "  ::rust::behavior::trycatch(");
728         writeln!(out, "      [&] {{");
729         write!(out, "        ");
730     }
731     if indirect_return {
732         out.include.new = true;
733         write!(out, "new (return$) ");
734         write_indirect_return_type(out, efn.ret.as_ref().unwrap());
735         write!(out, "(");
736     } else if efn.ret.is_some() {
737         write!(out, "return ");
738     }
739     match &efn.ret {
740         Some(Type::Ref(_)) => write!(out, "&"),
741         Some(Type::Str(_)) if !indirect_return => {
742             out.builtin.rust_str_repr = true;
743             write!(out, "::rust::impl<::rust::Str>::repr(");
744         }
745         Some(ty @ Type::SliceRef(_)) if !indirect_return => {
746             out.builtin.rust_slice_repr = true;
747             write!(out, "::rust::impl<");
748             write_type(out, ty);
749             write!(out, ">::repr(");
750         }
751         _ => {}
752     }
753     match &efn.receiver {
754         None => write!(out, "{}$(", efn.name.rust),
755         Some(_) => write!(out, "(self.*{}$)(", efn.name.rust),
756     }
757     for (i, arg) in efn.args.iter().enumerate() {
758         if i > 0 {
759             write!(out, ", ");
760         }
761         if let Type::RustBox(_) = &arg.ty {
762             write_type(out, &arg.ty);
763             write!(out, "::from_raw({})", arg.name.cxx);
764         } else if let Type::UniquePtr(_) = &arg.ty {
765             write_type(out, &arg.ty);
766             write!(out, "({})", arg.name.cxx);
767         } else if arg.ty == RustString {
768             out.builtin.unsafe_bitcopy = true;
769             write!(
770                 out,
771                 "::rust::String(::rust::unsafe_bitcopy, *{})",
772                 arg.name.cxx,
773             );
774         } else if let Type::RustVec(_) = arg.ty {
775             out.builtin.unsafe_bitcopy = true;
776             write_type(out, &arg.ty);
777             write!(out, "(::rust::unsafe_bitcopy, *{})", arg.name.cxx);
778         } else if out.types.needs_indirect_abi(&arg.ty) {
779             out.include.utility = true;
780             write!(out, "::std::move(*{})", arg.name.cxx);
781         } else {
782             write!(out, "{}", arg.name.cxx);
783         }
784     }
785     write!(out, ")");
786     match &efn.ret {
787         Some(Type::RustBox(_)) => write!(out, ".into_raw()"),
788         Some(Type::UniquePtr(_)) => write!(out, ".release()"),
789         Some(Type::Str(_)) | Some(Type::SliceRef(_)) if !indirect_return => write!(out, ")"),
790         _ => {}
791     }
792     if indirect_return {
793         write!(out, ")");
794     }
795     writeln!(out, ";");
796     if efn.throws {
797         out.include.cstring = true;
798         out.builtin.exception = true;
799         writeln!(out, "        throw$.ptr = nullptr;");
800         writeln!(out, "      }},");
801         writeln!(out, "      [&](const char *catch$) noexcept {{");
802         writeln!(out, "        throw$.len = ::std::strlen(catch$);");
803         writeln!(
804             out,
805             "        throw$.ptr = const_cast<char *>(::cxxbridge1$exception(catch$, throw$.len));",
806         );
807         writeln!(out, "      }});");
808         writeln!(out, "  return throw$;");
809     }
810     writeln!(out, "}}");
811     for arg in &efn.args {
812         if let Type::Fn(f) = &arg.ty {
813             let var = &arg.name;
814             write_function_pointer_trampoline(out, efn, var, f);
815         }
816     }
817     out.end_block(Block::ExternC);
818 }
819 
write_function_pointer_trampoline(out: &mut OutFile, efn: &ExternFn, var: &Pair, f: &Signature)820 fn write_function_pointer_trampoline(out: &mut OutFile, efn: &ExternFn, var: &Pair, f: &Signature) {
821     let r_trampoline = mangle::r_trampoline(efn, var, out.types);
822     let indirect_call = true;
823     write_rust_function_decl_impl(out, &r_trampoline, f, indirect_call);
824 
825     out.next_section();
826     let c_trampoline = mangle::c_trampoline(efn, var, out.types).to_string();
827     write_rust_function_shim_impl(out, &c_trampoline, f, &r_trampoline, indirect_call);
828 }
829 
write_rust_function_decl<'a>(out: &mut OutFile<'a>, efn: &'a ExternFn)830 fn write_rust_function_decl<'a>(out: &mut OutFile<'a>, efn: &'a ExternFn) {
831     out.set_namespace(&efn.name.namespace);
832     out.begin_block(Block::ExternC);
833     let link_name = mangle::extern_fn(efn, out.types);
834     let indirect_call = false;
835     write_rust_function_decl_impl(out, &link_name, efn, indirect_call);
836     out.end_block(Block::ExternC);
837 }
838 
write_rust_function_decl_impl( out: &mut OutFile, link_name: &Symbol, sig: &Signature, indirect_call: bool, )839 fn write_rust_function_decl_impl(
840     out: &mut OutFile,
841     link_name: &Symbol,
842     sig: &Signature,
843     indirect_call: bool,
844 ) {
845     out.next_section();
846     if sig.throws {
847         out.builtin.ptr_len = true;
848         write!(out, "::rust::repr::PtrLen ");
849     } else {
850         write_extern_return_type_space(out, &sig.ret);
851     }
852     write!(out, "{}(", link_name);
853     let mut needs_comma = false;
854     if let Some(receiver) = &sig.receiver {
855         if !receiver.mutable {
856             write!(out, "const ");
857         }
858         write!(
859             out,
860             "{} &self",
861             out.types.resolve(&receiver.ty).name.to_fully_qualified(),
862         );
863         needs_comma = true;
864     }
865     for arg in &sig.args {
866         if needs_comma {
867             write!(out, ", ");
868         }
869         write_extern_arg(out, arg);
870         needs_comma = true;
871     }
872     if indirect_return(sig, out.types) {
873         if needs_comma {
874             write!(out, ", ");
875         }
876         match sig.ret.as_ref().unwrap() {
877             Type::Ref(ret) => {
878                 write_pointee_type(out, &ret.inner, ret.mutable);
879                 write!(out, " *");
880             }
881             ret => write_type_space(out, ret),
882         }
883         write!(out, "*return$");
884         needs_comma = true;
885     }
886     if indirect_call {
887         if needs_comma {
888             write!(out, ", ");
889         }
890         write!(out, "void *");
891     }
892     writeln!(out, ") noexcept;");
893 }
894 
write_rust_function_shim<'a>(out: &mut OutFile<'a>, efn: &'a ExternFn)895 fn write_rust_function_shim<'a>(out: &mut OutFile<'a>, efn: &'a ExternFn) {
896     out.set_namespace(&efn.name.namespace);
897     for line in efn.doc.to_string().lines() {
898         writeln!(out, "//{}", line);
899     }
900     let local_name = match &efn.sig.receiver {
901         None => efn.name.cxx.to_string(),
902         Some(receiver) => format!(
903             "{}::{}",
904             out.types.resolve(&receiver.ty).name.cxx,
905             efn.name.cxx,
906         ),
907     };
908     let invoke = mangle::extern_fn(efn, out.types);
909     let indirect_call = false;
910     write_rust_function_shim_impl(out, &local_name, efn, &invoke, indirect_call);
911 }
912 
write_rust_function_shim_decl( out: &mut OutFile, local_name: &str, sig: &Signature, indirect_call: bool, )913 fn write_rust_function_shim_decl(
914     out: &mut OutFile,
915     local_name: &str,
916     sig: &Signature,
917     indirect_call: bool,
918 ) {
919     begin_function_definition(out);
920     write_return_type(out, &sig.ret);
921     write!(out, "{}(", local_name);
922     for (i, arg) in sig.args.iter().enumerate() {
923         if i > 0 {
924             write!(out, ", ");
925         }
926         write_type_space(out, &arg.ty);
927         write!(out, "{}", arg.name.cxx);
928     }
929     if indirect_call {
930         if !sig.args.is_empty() {
931             write!(out, ", ");
932         }
933         write!(out, "void *extern$");
934     }
935     write!(out, ")");
936     if let Some(receiver) = &sig.receiver {
937         if !receiver.mutable {
938             write!(out, " const");
939         }
940     }
941     if !sig.throws {
942         write!(out, " noexcept");
943     }
944 }
945 
write_rust_function_shim_impl( out: &mut OutFile, local_name: &str, sig: &Signature, invoke: &Symbol, indirect_call: bool, )946 fn write_rust_function_shim_impl(
947     out: &mut OutFile,
948     local_name: &str,
949     sig: &Signature,
950     invoke: &Symbol,
951     indirect_call: bool,
952 ) {
953     if out.header && sig.receiver.is_some() {
954         // We've already defined this inside the struct.
955         return;
956     }
957     write_rust_function_shim_decl(out, local_name, sig, indirect_call);
958     if out.header {
959         writeln!(out, ";");
960         return;
961     }
962     writeln!(out, " {{");
963     for arg in &sig.args {
964         if arg.ty != RustString && out.types.needs_indirect_abi(&arg.ty) {
965             out.include.utility = true;
966             out.builtin.manually_drop = true;
967             write!(out, "  ::rust::ManuallyDrop<");
968             write_type(out, &arg.ty);
969             writeln!(out, "> {}$(::std::move({0}));", arg.name.cxx);
970         }
971     }
972     write!(out, "  ");
973     let indirect_return = indirect_return(sig, out.types);
974     if indirect_return {
975         out.builtin.maybe_uninit = true;
976         write!(out, "::rust::MaybeUninit<");
977         match sig.ret.as_ref().unwrap() {
978             Type::Ref(ret) => {
979                 write_pointee_type(out, &ret.inner, ret.mutable);
980                 write!(out, " *");
981             }
982             ret => write_type(out, ret),
983         }
984         writeln!(out, "> return$;");
985         write!(out, "  ");
986     } else if let Some(ret) = &sig.ret {
987         write!(out, "return ");
988         match ret {
989             Type::RustBox(_) => {
990                 write_type(out, ret);
991                 write!(out, "::from_raw(");
992             }
993             Type::UniquePtr(_) => {
994                 write_type(out, ret);
995                 write!(out, "(");
996             }
997             Type::Ref(_) => write!(out, "*"),
998             Type::Str(_) => {
999                 out.builtin.rust_str_new_unchecked = true;
1000                 write!(out, "::rust::impl<::rust::Str>::new_unchecked(");
1001             }
1002             Type::SliceRef(_) => {
1003                 out.builtin.rust_slice_new = true;
1004                 write!(out, "::rust::impl<");
1005                 write_type(out, ret);
1006                 write!(out, ">::slice(");
1007             }
1008             _ => {}
1009         }
1010     }
1011     if sig.throws {
1012         out.builtin.ptr_len = true;
1013         write!(out, "::rust::repr::PtrLen error$ = ");
1014     }
1015     write!(out, "{}(", invoke);
1016     let mut needs_comma = false;
1017     if sig.receiver.is_some() {
1018         write!(out, "*this");
1019         needs_comma = true;
1020     }
1021     for arg in &sig.args {
1022         if needs_comma {
1023             write!(out, ", ");
1024         }
1025         if out.types.needs_indirect_abi(&arg.ty) {
1026             write!(out, "&");
1027         }
1028         write!(out, "{}", arg.name.cxx);
1029         match &arg.ty {
1030             Type::RustBox(_) => write!(out, ".into_raw()"),
1031             Type::UniquePtr(_) => write!(out, ".release()"),
1032             ty if ty != RustString && out.types.needs_indirect_abi(ty) => write!(out, "$.value"),
1033             _ => {}
1034         }
1035         needs_comma = true;
1036     }
1037     if indirect_return {
1038         if needs_comma {
1039             write!(out, ", ");
1040         }
1041         write!(out, "&return$.value");
1042         needs_comma = true;
1043     }
1044     if indirect_call {
1045         if needs_comma {
1046             write!(out, ", ");
1047         }
1048         write!(out, "extern$");
1049     }
1050     write!(out, ")");
1051     if !indirect_return {
1052         if let Some(ret) = &sig.ret {
1053             if let Type::RustBox(_) | Type::UniquePtr(_) | Type::Str(_) | Type::SliceRef(_) = ret {
1054                 write!(out, ")");
1055             }
1056         }
1057     }
1058     writeln!(out, ";");
1059     if sig.throws {
1060         out.builtin.rust_error = true;
1061         writeln!(out, "  if (error$.ptr) {{");
1062         writeln!(out, "    throw ::rust::impl<::rust::Error>::error(error$);");
1063         writeln!(out, "  }}");
1064     }
1065     if indirect_return {
1066         write!(out, "  return ");
1067         match sig.ret.as_ref().unwrap() {
1068             Type::Ref(_) => write!(out, "*return$.value"),
1069             _ => {
1070                 out.include.utility = true;
1071                 write!(out, "::std::move(return$.value)");
1072             }
1073         }
1074         writeln!(out, ";");
1075     }
1076     writeln!(out, "}}");
1077 }
1078 
write_return_type(out: &mut OutFile, ty: &Option<Type>)1079 fn write_return_type(out: &mut OutFile, ty: &Option<Type>) {
1080     match ty {
1081         None => write!(out, "void "),
1082         Some(ty) => write_type_space(out, ty),
1083     }
1084 }
1085 
indirect_return(sig: &Signature, types: &Types) -> bool1086 fn indirect_return(sig: &Signature, types: &Types) -> bool {
1087     sig.ret
1088         .as_ref()
1089         .map_or(false, |ret| sig.throws || types.needs_indirect_abi(ret))
1090 }
1091 
write_indirect_return_type(out: &mut OutFile, ty: &Type)1092 fn write_indirect_return_type(out: &mut OutFile, ty: &Type) {
1093     match ty {
1094         Type::RustBox(ty) | Type::UniquePtr(ty) => {
1095             write_type_space(out, &ty.inner);
1096             write!(out, "*");
1097         }
1098         Type::Ref(ty) => {
1099             if !ty.mutable {
1100                 write!(out, "const ");
1101             }
1102             write_type(out, &ty.inner);
1103             write!(out, " *");
1104         }
1105         _ => write_type(out, ty),
1106     }
1107 }
1108 
write_indirect_return_type_space(out: &mut OutFile, ty: &Type)1109 fn write_indirect_return_type_space(out: &mut OutFile, ty: &Type) {
1110     write_indirect_return_type(out, ty);
1111     match ty {
1112         Type::RustBox(_) | Type::UniquePtr(_) | Type::Ref(_) => {}
1113         Type::Str(_) | Type::SliceRef(_) => write!(out, " "),
1114         _ => write_space_after_type(out, ty),
1115     }
1116 }
1117 
write_extern_return_type_space(out: &mut OutFile, ty: &Option<Type>)1118 fn write_extern_return_type_space(out: &mut OutFile, ty: &Option<Type>) {
1119     match ty {
1120         Some(Type::RustBox(ty)) | Some(Type::UniquePtr(ty)) => {
1121             write_type_space(out, &ty.inner);
1122             write!(out, "*");
1123         }
1124         Some(Type::Ref(ty)) => {
1125             if !ty.mutable {
1126                 write!(out, "const ");
1127             }
1128             write_type(out, &ty.inner);
1129             write!(out, " *");
1130         }
1131         Some(Type::Str(_)) | Some(Type::SliceRef(_)) => {
1132             out.builtin.repr_fat = true;
1133             write!(out, "::rust::repr::Fat ");
1134         }
1135         Some(ty) if out.types.needs_indirect_abi(ty) => write!(out, "void "),
1136         _ => write_return_type(out, ty),
1137     }
1138 }
1139 
write_extern_arg(out: &mut OutFile, arg: &Var)1140 fn write_extern_arg(out: &mut OutFile, arg: &Var) {
1141     match &arg.ty {
1142         Type::RustBox(ty) | Type::UniquePtr(ty) | Type::CxxVector(ty) => {
1143             write_type_space(out, &ty.inner);
1144             write!(out, "*");
1145         }
1146         _ => write_type_space(out, &arg.ty),
1147     }
1148     if out.types.needs_indirect_abi(&arg.ty) {
1149         write!(out, "*");
1150     }
1151     write!(out, "{}", arg.name.cxx);
1152 }
1153 
write_type(out: &mut OutFile, ty: &Type)1154 fn write_type(out: &mut OutFile, ty: &Type) {
1155     match ty {
1156         Type::Ident(ident) => match Atom::from(&ident.rust) {
1157             Some(atom) => write_atom(out, atom),
1158             None => write!(
1159                 out,
1160                 "{}",
1161                 out.types.resolve(ident).name.to_fully_qualified(),
1162             ),
1163         },
1164         Type::RustBox(ty) => {
1165             write!(out, "::rust::Box<");
1166             write_type(out, &ty.inner);
1167             write!(out, ">");
1168         }
1169         Type::RustVec(ty) => {
1170             write!(out, "::rust::Vec<");
1171             write_type(out, &ty.inner);
1172             write!(out, ">");
1173         }
1174         Type::UniquePtr(ptr) => {
1175             write!(out, "::std::unique_ptr<");
1176             write_type(out, &ptr.inner);
1177             write!(out, ">");
1178         }
1179         Type::SharedPtr(ptr) => {
1180             write!(out, "::std::shared_ptr<");
1181             write_type(out, &ptr.inner);
1182             write!(out, ">");
1183         }
1184         Type::WeakPtr(ptr) => {
1185             write!(out, "::std::weak_ptr<");
1186             write_type(out, &ptr.inner);
1187             write!(out, ">");
1188         }
1189         Type::CxxVector(ty) => {
1190             write!(out, "::std::vector<");
1191             write_type(out, &ty.inner);
1192             write!(out, ">");
1193         }
1194         Type::Ref(r) => {
1195             write_pointee_type(out, &r.inner, r.mutable);
1196             write!(out, " &");
1197         }
1198         Type::Ptr(p) => {
1199             write_pointee_type(out, &p.inner, p.mutable);
1200             write!(out, " *");
1201         }
1202         Type::Str(_) => {
1203             write!(out, "::rust::Str");
1204         }
1205         Type::SliceRef(slice) => {
1206             write!(out, "::rust::Slice<");
1207             if slice.mutability.is_none() {
1208                 write!(out, "const ");
1209             }
1210             write_type(out, &slice.inner);
1211             write!(out, ">");
1212         }
1213         Type::Fn(f) => {
1214             write!(out, "::rust::Fn<");
1215             match &f.ret {
1216                 Some(ret) => write_type(out, ret),
1217                 None => write!(out, "void"),
1218             }
1219             write!(out, "(");
1220             for (i, arg) in f.args.iter().enumerate() {
1221                 if i > 0 {
1222                     write!(out, ", ");
1223                 }
1224                 write_type(out, &arg.ty);
1225             }
1226             write!(out, ")>");
1227         }
1228         Type::Array(a) => {
1229             write!(out, "::std::array<");
1230             write_type(out, &a.inner);
1231             write!(out, ", {}>", &a.len);
1232         }
1233         Type::Void(_) => unreachable!(),
1234     }
1235 }
1236 
1237 // Write just the T type behind a &T or &mut T or *const T or *mut T.
write_pointee_type(out: &mut OutFile, inner: &Type, mutable: bool)1238 fn write_pointee_type(out: &mut OutFile, inner: &Type, mutable: bool) {
1239     if let Type::Ptr(_) = inner {
1240         write_type_space(out, inner);
1241         if !mutable {
1242             write!(out, "const");
1243         }
1244     } else {
1245         if !mutable {
1246             write!(out, "const ");
1247         }
1248         write_type(out, inner);
1249     }
1250 }
1251 
write_atom(out: &mut OutFile, atom: Atom)1252 fn write_atom(out: &mut OutFile, atom: Atom) {
1253     match atom {
1254         Bool => write!(out, "bool"),
1255         Char => write!(out, "char"),
1256         U8 => write!(out, "::std::uint8_t"),
1257         U16 => write!(out, "::std::uint16_t"),
1258         U32 => write!(out, "::std::uint32_t"),
1259         U64 => write!(out, "::std::uint64_t"),
1260         Usize => write!(out, "::std::size_t"),
1261         I8 => write!(out, "::std::int8_t"),
1262         I16 => write!(out, "::std::int16_t"),
1263         I32 => write!(out, "::std::int32_t"),
1264         I64 => write!(out, "::std::int64_t"),
1265         Isize => write!(out, "::rust::isize"),
1266         F32 => write!(out, "float"),
1267         F64 => write!(out, "double"),
1268         CxxString => write!(out, "::std::string"),
1269         RustString => write!(out, "::rust::String"),
1270     }
1271 }
1272 
write_type_space(out: &mut OutFile, ty: &Type)1273 fn write_type_space(out: &mut OutFile, ty: &Type) {
1274     write_type(out, ty);
1275     write_space_after_type(out, ty);
1276 }
1277 
write_space_after_type(out: &mut OutFile, ty: &Type)1278 fn write_space_after_type(out: &mut OutFile, ty: &Type) {
1279     match ty {
1280         Type::Ident(_)
1281         | Type::RustBox(_)
1282         | Type::UniquePtr(_)
1283         | Type::SharedPtr(_)
1284         | Type::WeakPtr(_)
1285         | Type::Str(_)
1286         | Type::CxxVector(_)
1287         | Type::RustVec(_)
1288         | Type::SliceRef(_)
1289         | Type::Fn(_)
1290         | Type::Array(_) => write!(out, " "),
1291         Type::Ref(_) | Type::Ptr(_) => {}
1292         Type::Void(_) => unreachable!(),
1293     }
1294 }
1295 
1296 #[derive(Copy, Clone)]
1297 enum UniquePtr<'a> {
1298     Ident(&'a Ident),
1299     CxxVector(&'a Ident),
1300 }
1301 
1302 trait ToTypename {
to_typename(&self, types: &Types) -> String1303     fn to_typename(&self, types: &Types) -> String;
1304 }
1305 
1306 impl ToTypename for Ident {
to_typename(&self, types: &Types) -> String1307     fn to_typename(&self, types: &Types) -> String {
1308         types.resolve(self).name.to_fully_qualified()
1309     }
1310 }
1311 
1312 impl<'a> ToTypename for UniquePtr<'a> {
to_typename(&self, types: &Types) -> String1313     fn to_typename(&self, types: &Types) -> String {
1314         match self {
1315             UniquePtr::Ident(ident) => ident.to_typename(types),
1316             UniquePtr::CxxVector(element) => {
1317                 format!("::std::vector<{}>", element.to_typename(types))
1318             }
1319         }
1320     }
1321 }
1322 
1323 trait ToMangled {
to_mangled(&self, types: &Types) -> Symbol1324     fn to_mangled(&self, types: &Types) -> Symbol;
1325 }
1326 
1327 impl ToMangled for Ident {
to_mangled(&self, types: &Types) -> Symbol1328     fn to_mangled(&self, types: &Types) -> Symbol {
1329         types.resolve(self).name.to_symbol()
1330     }
1331 }
1332 
1333 impl<'a> ToMangled for UniquePtr<'a> {
to_mangled(&self, types: &Types) -> Symbol1334     fn to_mangled(&self, types: &Types) -> Symbol {
1335         match self {
1336             UniquePtr::Ident(ident) => ident.to_mangled(types),
1337             UniquePtr::CxxVector(element) => element.to_mangled(types).prefix_with("std$vector$"),
1338         }
1339     }
1340 }
1341 
write_generic_instantiations(out: &mut OutFile)1342 fn write_generic_instantiations(out: &mut OutFile) {
1343     if out.header {
1344         return;
1345     }
1346 
1347     out.next_section();
1348     out.set_namespace(Default::default());
1349     out.begin_block(Block::ExternC);
1350     for impl_key in out.types.impls.keys() {
1351         out.next_section();
1352         match *impl_key {
1353             ImplKey::RustBox(ident) => write_rust_box_extern(out, ident),
1354             ImplKey::RustVec(ident) => write_rust_vec_extern(out, ident),
1355             ImplKey::UniquePtr(ident) => write_unique_ptr(out, ident),
1356             ImplKey::SharedPtr(ident) => write_shared_ptr(out, ident),
1357             ImplKey::WeakPtr(ident) => write_weak_ptr(out, ident),
1358             ImplKey::CxxVector(ident) => write_cxx_vector(out, ident),
1359         }
1360     }
1361     out.end_block(Block::ExternC);
1362 
1363     out.begin_block(Block::Namespace("rust"));
1364     out.begin_block(Block::InlineNamespace("cxxbridge1"));
1365     for impl_key in out.types.impls.keys() {
1366         match *impl_key {
1367             ImplKey::RustBox(ident) => write_rust_box_impl(out, ident),
1368             ImplKey::RustVec(ident) => write_rust_vec_impl(out, ident),
1369             _ => {}
1370         }
1371     }
1372     out.end_block(Block::InlineNamespace("cxxbridge1"));
1373     out.end_block(Block::Namespace("rust"));
1374 }
1375 
write_rust_box_extern(out: &mut OutFile, key: NamedImplKey)1376 fn write_rust_box_extern(out: &mut OutFile, key: NamedImplKey) {
1377     let resolve = out.types.resolve(&key);
1378     let inner = resolve.name.to_fully_qualified();
1379     let instance = resolve.name.to_symbol();
1380 
1381     writeln!(
1382         out,
1383         "{} *cxxbridge1$box${}$alloc() noexcept;",
1384         inner, instance,
1385     );
1386     writeln!(
1387         out,
1388         "void cxxbridge1$box${}$dealloc({} *) noexcept;",
1389         instance, inner,
1390     );
1391     writeln!(
1392         out,
1393         "void cxxbridge1$box${}$drop(::rust::Box<{}> *ptr) noexcept;",
1394         instance, inner,
1395     );
1396 }
1397 
write_rust_vec_extern(out: &mut OutFile, key: NamedImplKey)1398 fn write_rust_vec_extern(out: &mut OutFile, key: NamedImplKey) {
1399     let element = key.rust;
1400     let inner = element.to_typename(out.types);
1401     let instance = element.to_mangled(out.types);
1402 
1403     out.include.cstddef = true;
1404 
1405     writeln!(
1406         out,
1407         "void cxxbridge1$rust_vec${}$new(const ::rust::Vec<{}> *ptr) noexcept;",
1408         instance, inner,
1409     );
1410     writeln!(
1411         out,
1412         "void cxxbridge1$rust_vec${}$drop(::rust::Vec<{}> *ptr) noexcept;",
1413         instance, inner,
1414     );
1415     writeln!(
1416         out,
1417         "::std::size_t cxxbridge1$rust_vec${}$len(const ::rust::Vec<{}> *ptr) noexcept;",
1418         instance, inner,
1419     );
1420     writeln!(
1421         out,
1422         "::std::size_t cxxbridge1$rust_vec${}$capacity(const ::rust::Vec<{}> *ptr) noexcept;",
1423         instance, inner,
1424     );
1425     writeln!(
1426         out,
1427         "const {} *cxxbridge1$rust_vec${}$data(const ::rust::Vec<{0}> *ptr) noexcept;",
1428         inner, instance,
1429     );
1430     writeln!(
1431         out,
1432         "void cxxbridge1$rust_vec${}$reserve_total(::rust::Vec<{}> *ptr, ::std::size_t cap) noexcept;",
1433         instance, inner,
1434     );
1435     writeln!(
1436         out,
1437         "void cxxbridge1$rust_vec${}$set_len(::rust::Vec<{}> *ptr, ::std::size_t len) noexcept;",
1438         instance, inner,
1439     );
1440 }
1441 
write_rust_box_impl(out: &mut OutFile, key: NamedImplKey)1442 fn write_rust_box_impl(out: &mut OutFile, key: NamedImplKey) {
1443     let resolve = out.types.resolve(&key);
1444     let inner = resolve.name.to_fully_qualified();
1445     let instance = resolve.name.to_symbol();
1446 
1447     writeln!(out, "template <>");
1448     begin_function_definition(out);
1449     writeln!(
1450         out,
1451         "{} *Box<{}>::allocation::alloc() noexcept {{",
1452         inner, inner,
1453     );
1454     writeln!(out, "  return cxxbridge1$box${}$alloc();", instance);
1455     writeln!(out, "}}");
1456 
1457     writeln!(out, "template <>");
1458     begin_function_definition(out);
1459     writeln!(
1460         out,
1461         "void Box<{}>::allocation::dealloc({} *ptr) noexcept {{",
1462         inner, inner,
1463     );
1464     writeln!(out, "  cxxbridge1$box${}$dealloc(ptr);", instance);
1465     writeln!(out, "}}");
1466 
1467     writeln!(out, "template <>");
1468     begin_function_definition(out);
1469     writeln!(out, "void Box<{}>::drop() noexcept {{", inner);
1470     writeln!(out, "  cxxbridge1$box${}$drop(this);", instance);
1471     writeln!(out, "}}");
1472 }
1473 
write_rust_vec_impl(out: &mut OutFile, key: NamedImplKey)1474 fn write_rust_vec_impl(out: &mut OutFile, key: NamedImplKey) {
1475     let element = key.rust;
1476     let inner = element.to_typename(out.types);
1477     let instance = element.to_mangled(out.types);
1478 
1479     out.include.cstddef = true;
1480 
1481     writeln!(out, "template <>");
1482     begin_function_definition(out);
1483     writeln!(out, "Vec<{}>::Vec() noexcept {{", inner);
1484     writeln!(out, "  cxxbridge1$rust_vec${}$new(this);", instance);
1485     writeln!(out, "}}");
1486 
1487     writeln!(out, "template <>");
1488     begin_function_definition(out);
1489     writeln!(out, "void Vec<{}>::drop() noexcept {{", inner);
1490     writeln!(out, "  return cxxbridge1$rust_vec${}$drop(this);", instance);
1491     writeln!(out, "}}");
1492 
1493     writeln!(out, "template <>");
1494     begin_function_definition(out);
1495     writeln!(
1496         out,
1497         "::std::size_t Vec<{}>::size() const noexcept {{",
1498         inner,
1499     );
1500     writeln!(out, "  return cxxbridge1$rust_vec${}$len(this);", instance);
1501     writeln!(out, "}}");
1502 
1503     writeln!(out, "template <>");
1504     begin_function_definition(out);
1505     writeln!(
1506         out,
1507         "::std::size_t Vec<{}>::capacity() const noexcept {{",
1508         inner,
1509     );
1510     writeln!(
1511         out,
1512         "  return cxxbridge1$rust_vec${}$capacity(this);",
1513         instance,
1514     );
1515     writeln!(out, "}}");
1516 
1517     writeln!(out, "template <>");
1518     begin_function_definition(out);
1519     writeln!(out, "const {} *Vec<{0}>::data() const noexcept {{", inner);
1520     writeln!(out, "  return cxxbridge1$rust_vec${}$data(this);", instance);
1521     writeln!(out, "}}");
1522 
1523     writeln!(out, "template <>");
1524     begin_function_definition(out);
1525     writeln!(
1526         out,
1527         "void Vec<{}>::reserve_total(::std::size_t cap) noexcept {{",
1528         inner,
1529     );
1530     writeln!(
1531         out,
1532         "  return cxxbridge1$rust_vec${}$reserve_total(this, cap);",
1533         instance,
1534     );
1535     writeln!(out, "}}");
1536 
1537     writeln!(out, "template <>");
1538     begin_function_definition(out);
1539     writeln!(
1540         out,
1541         "void Vec<{}>::set_len(::std::size_t len) noexcept {{",
1542         inner,
1543     );
1544     writeln!(
1545         out,
1546         "  return cxxbridge1$rust_vec${}$set_len(this, len);",
1547         instance,
1548     );
1549     writeln!(out, "}}");
1550 }
1551 
write_unique_ptr(out: &mut OutFile, key: NamedImplKey)1552 fn write_unique_ptr(out: &mut OutFile, key: NamedImplKey) {
1553     let ty = UniquePtr::Ident(key.rust);
1554     write_unique_ptr_common(out, ty);
1555 }
1556 
1557 // Shared by UniquePtr<T> and UniquePtr<CxxVector<T>>.
write_unique_ptr_common(out: &mut OutFile, ty: UniquePtr)1558 fn write_unique_ptr_common(out: &mut OutFile, ty: UniquePtr) {
1559     out.include.new = true;
1560     out.include.utility = true;
1561     let inner = ty.to_typename(out.types);
1562     let instance = ty.to_mangled(out.types);
1563 
1564     let can_construct_from_value = match ty {
1565         // Some aliases are to opaque types; some are to trivial types. We can't
1566         // know at code generation time, so we generate both C++ and Rust side
1567         // bindings for a "new" method anyway. But the Rust code can't be called
1568         // for Opaque types because the 'new' method is not implemented.
1569         UniquePtr::Ident(ident) => {
1570             out.types.structs.contains_key(ident)
1571                 || out.types.enums.contains_key(ident)
1572                 || out.types.aliases.contains_key(ident)
1573         }
1574         UniquePtr::CxxVector(_) => false,
1575     };
1576 
1577     let conditional_delete = match ty {
1578         UniquePtr::Ident(ident) => {
1579             !out.types.structs.contains_key(ident) && !out.types.enums.contains_key(ident)
1580         }
1581         UniquePtr::CxxVector(_) => false,
1582     };
1583 
1584     if conditional_delete {
1585         out.builtin.is_complete = true;
1586         let definition = match ty {
1587             UniquePtr::Ident(ty) => &out.types.resolve(ty).name.cxx,
1588             UniquePtr::CxxVector(_) => unreachable!(),
1589         };
1590         writeln!(
1591             out,
1592             "static_assert(::rust::detail::is_complete<{}>::value, \"definition of {} is required\");",
1593             inner, definition,
1594         );
1595     }
1596     writeln!(
1597         out,
1598         "static_assert(sizeof(::std::unique_ptr<{}>) == sizeof(void *), \"\");",
1599         inner,
1600     );
1601     writeln!(
1602         out,
1603         "static_assert(alignof(::std::unique_ptr<{}>) == alignof(void *), \"\");",
1604         inner,
1605     );
1606     writeln!(
1607         out,
1608         "void cxxbridge1$unique_ptr${}$null(::std::unique_ptr<{}> *ptr) noexcept {{",
1609         instance, inner,
1610     );
1611     writeln!(out, "  ::new (ptr) ::std::unique_ptr<{}>();", inner);
1612     writeln!(out, "}}");
1613     if can_construct_from_value {
1614         out.builtin.maybe_uninit = true;
1615         writeln!(
1616             out,
1617             "{} *cxxbridge1$unique_ptr${}$uninit(::std::unique_ptr<{}> *ptr) noexcept {{",
1618             inner, instance, inner,
1619         );
1620         writeln!(
1621             out,
1622             "  {} *uninit = reinterpret_cast<{} *>(new ::rust::MaybeUninit<{}>);",
1623             inner, inner, inner,
1624         );
1625         writeln!(out, "  ::new (ptr) ::std::unique_ptr<{}>(uninit);", inner);
1626         writeln!(out, "  return uninit;");
1627         writeln!(out, "}}");
1628     }
1629     writeln!(
1630         out,
1631         "void cxxbridge1$unique_ptr${}$raw(::std::unique_ptr<{}> *ptr, {} *raw) noexcept {{",
1632         instance, inner, inner,
1633     );
1634     writeln!(out, "  ::new (ptr) ::std::unique_ptr<{}>(raw);", inner);
1635     writeln!(out, "}}");
1636     writeln!(
1637         out,
1638         "const {} *cxxbridge1$unique_ptr${}$get(const ::std::unique_ptr<{}>& ptr) noexcept {{",
1639         inner, instance, inner,
1640     );
1641     writeln!(out, "  return ptr.get();");
1642     writeln!(out, "}}");
1643     writeln!(
1644         out,
1645         "{} *cxxbridge1$unique_ptr${}$release(::std::unique_ptr<{}>& ptr) noexcept {{",
1646         inner, instance, inner,
1647     );
1648     writeln!(out, "  return ptr.release();");
1649     writeln!(out, "}}");
1650     writeln!(
1651         out,
1652         "void cxxbridge1$unique_ptr${}$drop(::std::unique_ptr<{}> *ptr) noexcept {{",
1653         instance, inner,
1654     );
1655     if conditional_delete {
1656         out.builtin.deleter_if = true;
1657         writeln!(
1658             out,
1659             "  ::rust::deleter_if<::rust::detail::is_complete<{}>::value>{{}}(ptr);",
1660             inner,
1661         );
1662     } else {
1663         writeln!(out, "  ptr->~unique_ptr();");
1664     }
1665     writeln!(out, "}}");
1666 }
1667 
write_shared_ptr(out: &mut OutFile, key: NamedImplKey)1668 fn write_shared_ptr(out: &mut OutFile, key: NamedImplKey) {
1669     let ident = key.rust;
1670     let resolve = out.types.resolve(ident);
1671     let inner = resolve.name.to_fully_qualified();
1672     let instance = resolve.name.to_symbol();
1673 
1674     out.include.new = true;
1675     out.include.utility = true;
1676 
1677     // Some aliases are to opaque types; some are to trivial types. We can't
1678     // know at code generation time, so we generate both C++ and Rust side
1679     // bindings for a "new" method anyway. But the Rust code can't be called for
1680     // Opaque types because the 'new' method is not implemented.
1681     let can_construct_from_value = out.types.structs.contains_key(ident)
1682         || out.types.enums.contains_key(ident)
1683         || out.types.aliases.contains_key(ident);
1684 
1685     writeln!(
1686         out,
1687         "static_assert(sizeof(::std::shared_ptr<{}>) == 2 * sizeof(void *), \"\");",
1688         inner,
1689     );
1690     writeln!(
1691         out,
1692         "static_assert(alignof(::std::shared_ptr<{}>) == alignof(void *), \"\");",
1693         inner,
1694     );
1695     writeln!(
1696         out,
1697         "void cxxbridge1$shared_ptr${}$null(::std::shared_ptr<{}> *ptr) noexcept {{",
1698         instance, inner,
1699     );
1700     writeln!(out, "  ::new (ptr) ::std::shared_ptr<{}>();", inner);
1701     writeln!(out, "}}");
1702     if can_construct_from_value {
1703         out.builtin.maybe_uninit = true;
1704         writeln!(
1705             out,
1706             "{} *cxxbridge1$shared_ptr${}$uninit(::std::shared_ptr<{}> *ptr) noexcept {{",
1707             inner, instance, inner,
1708         );
1709         writeln!(
1710             out,
1711             "  {} *uninit = reinterpret_cast<{} *>(new ::rust::MaybeUninit<{}>);",
1712             inner, inner, inner,
1713         );
1714         writeln!(out, "  ::new (ptr) ::std::shared_ptr<{}>(uninit);", inner);
1715         writeln!(out, "  return uninit;");
1716         writeln!(out, "}}");
1717     }
1718     writeln!(
1719         out,
1720         "void cxxbridge1$shared_ptr${}$clone(const ::std::shared_ptr<{}>& self, ::std::shared_ptr<{}> *ptr) noexcept {{",
1721         instance, inner, inner,
1722     );
1723     writeln!(out, "  ::new (ptr) ::std::shared_ptr<{}>(self);", inner);
1724     writeln!(out, "}}");
1725     writeln!(
1726         out,
1727         "const {} *cxxbridge1$shared_ptr${}$get(const ::std::shared_ptr<{}>& self) noexcept {{",
1728         inner, instance, inner,
1729     );
1730     writeln!(out, "  return self.get();");
1731     writeln!(out, "}}");
1732     writeln!(
1733         out,
1734         "void cxxbridge1$shared_ptr${}$drop(::std::shared_ptr<{}> *self) noexcept {{",
1735         instance, inner,
1736     );
1737     writeln!(out, "  self->~shared_ptr();");
1738     writeln!(out, "}}");
1739 }
1740 
write_weak_ptr(out: &mut OutFile, key: NamedImplKey)1741 fn write_weak_ptr(out: &mut OutFile, key: NamedImplKey) {
1742     let resolve = out.types.resolve(&key);
1743     let inner = resolve.name.to_fully_qualified();
1744     let instance = resolve.name.to_symbol();
1745 
1746     out.include.new = true;
1747     out.include.utility = true;
1748 
1749     writeln!(
1750         out,
1751         "static_assert(sizeof(::std::weak_ptr<{}>) == 2 * sizeof(void *), \"\");",
1752         inner,
1753     );
1754     writeln!(
1755         out,
1756         "static_assert(alignof(::std::weak_ptr<{}>) == alignof(void *), \"\");",
1757         inner,
1758     );
1759     writeln!(
1760         out,
1761         "void cxxbridge1$weak_ptr${}$null(::std::weak_ptr<{}> *ptr) noexcept {{",
1762         instance, inner,
1763     );
1764     writeln!(out, "  ::new (ptr) ::std::weak_ptr<{}>();", inner);
1765     writeln!(out, "}}");
1766     writeln!(
1767         out,
1768         "void cxxbridge1$weak_ptr${}$clone(const ::std::weak_ptr<{}>& self, ::std::weak_ptr<{}> *ptr) noexcept {{",
1769         instance, inner, inner,
1770     );
1771     writeln!(out, "  ::new (ptr) ::std::weak_ptr<{}>(self);", inner);
1772     writeln!(out, "}}");
1773     writeln!(
1774         out,
1775         "void cxxbridge1$weak_ptr${}$downgrade(const ::std::shared_ptr<{}>& shared, ::std::weak_ptr<{}> *weak) noexcept {{",
1776         instance, inner, inner,
1777     );
1778     writeln!(out, "  ::new (weak) ::std::weak_ptr<{}>(shared);", inner);
1779     writeln!(out, "}}");
1780     writeln!(
1781         out,
1782         "void cxxbridge1$weak_ptr${}$upgrade(const ::std::weak_ptr<{}>& weak, ::std::shared_ptr<{}> *shared) noexcept {{",
1783         instance, inner, inner,
1784     );
1785     writeln!(
1786         out,
1787         "  ::new (shared) ::std::shared_ptr<{}>(weak.lock());",
1788         inner,
1789     );
1790     writeln!(out, "}}");
1791     writeln!(
1792         out,
1793         "void cxxbridge1$weak_ptr${}$drop(::std::weak_ptr<{}> *self) noexcept {{",
1794         instance, inner,
1795     );
1796     writeln!(out, "  self->~weak_ptr();");
1797     writeln!(out, "}}");
1798 }
1799 
write_cxx_vector(out: &mut OutFile, key: NamedImplKey)1800 fn write_cxx_vector(out: &mut OutFile, key: NamedImplKey) {
1801     let element = key.rust;
1802     let inner = element.to_typename(out.types);
1803     let instance = element.to_mangled(out.types);
1804 
1805     out.include.cstddef = true;
1806 
1807     writeln!(
1808         out,
1809         "::std::size_t cxxbridge1$std$vector${}$size(const ::std::vector<{}> &s) noexcept {{",
1810         instance, inner,
1811     );
1812     writeln!(out, "  return s.size();");
1813     writeln!(out, "}}");
1814     writeln!(
1815         out,
1816         "{} *cxxbridge1$std$vector${}$get_unchecked(::std::vector<{}> *s, ::std::size_t pos) noexcept {{",
1817         inner, instance, inner,
1818     );
1819     writeln!(out, "  return &(*s)[pos];");
1820     writeln!(out, "}}");
1821 
1822     out.include.memory = true;
1823     write_unique_ptr_common(out, UniquePtr::CxxVector(element));
1824 }
1825