cxx_gen/gen/
write.rs

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