blob: a74833fcc0bb051e9d1925bb23f97c5f5adca626 [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use crate::gen::out::OutFile;
David Tolnay33d30292020-03-18 18:02:02 -07002use crate::gen::{include, Opt};
David Tolnay7db73692019-10-20 14:51:12 -04003use crate::syntax::atom::Atom::{self, *};
Myron Ahneba35cf2020-02-05 19:41:51 +07004use crate::syntax::mangled::ToMangled;
David Tolnay08419302020-04-19 20:38:20 -07005use crate::syntax::namespace::Namespace;
David Tolnay891061b2020-04-19 22:42:33 -07006use crate::syntax::symbol::Symbol;
Myron Ahneba35cf2020-02-05 19:41:51 +07007use crate::syntax::typename::ToTypename;
David Tolnaya73853b2020-04-20 01:19:56 -07008use crate::syntax::{mangle, Api, ExternFn, ExternType, Signature, Struct, Type, Types, Var};
David Tolnay7db73692019-10-20 14:51:12 -04009use proc_macro2::Ident;
David Tolnayf94bef12020-04-17 14:46:42 -070010use std::collections::HashMap;
David Tolnay7db73692019-10-20 14:51:12 -040011
David Tolnay33d30292020-03-18 18:02:02 -070012pub(super) fn gen(
David Tolnay754e21c2020-03-29 20:58:46 -070013 namespace: Namespace,
David Tolnay33d30292020-03-18 18:02:02 -070014 apis: &[Api],
15 types: &Types,
16 opt: Opt,
17 header: bool,
18) -> OutFile {
David Tolnay7db73692019-10-20 14:51:12 -040019 let mut out_file = OutFile::new(namespace.clone(), header);
20 let out = &mut out_file;
21
22 if header {
23 writeln!(out, "#pragma once");
24 }
25
David Tolnay33d30292020-03-18 18:02:02 -070026 out.include.extend(opt.include);
David Tolnay7db73692019-10-20 14:51:12 -040027 for api in apis {
28 if let Api::Include(include) = api {
David Tolnay9c68b1a2020-03-06 11:12:55 -080029 out.include.insert(include.value());
David Tolnay7db73692019-10-20 14:51:12 -040030 }
31 }
32
33 write_includes(out, types);
David Tolnayf51447e2020-03-06 14:14:27 -080034 write_include_cxxbridge(out, apis, types);
David Tolnay7db73692019-10-20 14:51:12 -040035
David Tolnay7db73692019-10-20 14:51:12 -040036 out.next_section();
37 for name in &namespace {
38 writeln!(out, "namespace {} {{", name);
39 }
40
David Tolnay7db73692019-10-20 14:51:12 -040041 out.next_section();
42 for api in apis {
43 match api {
44 Api::Struct(strct) => write_struct_decl(out, &strct.ident),
David Tolnay8861bee2020-01-20 18:39:24 -080045 Api::CxxType(ety) => write_struct_using(out, &ety.ident),
46 Api::RustType(ety) => write_struct_decl(out, &ety.ident),
Myron Ahneba35cf2020-02-05 19:41:51 +070047 _ => (),
David Tolnay7db73692019-10-20 14:51:12 -040048 }
49 }
50
David Tolnayf94bef12020-04-17 14:46:42 -070051 let mut methods_for_type = HashMap::new();
52 for api in apis {
53 if let Api::RustFunction(efn) = api {
54 if let Some(receiver) = &efn.sig.receiver {
55 methods_for_type
David Tolnay05e11cc2020-04-20 02:13:56 -070056 .entry(&receiver.ty)
David Tolnayf94bef12020-04-17 14:46:42 -070057 .or_insert_with(Vec::new)
58 .push(efn);
59 }
60 }
61 }
Joel Galenson968738f2020-04-15 14:19:33 -070062
David Tolnay7db73692019-10-20 14:51:12 -040063 for api in apis {
Joel Galensonc1c4e7a2020-04-15 10:21:00 -070064 match api {
65 Api::Struct(strct) => {
66 out.next_section();
67 write_struct(out, strct);
68 }
David Tolnayc1fe0052020-04-17 15:15:06 -070069 Api::RustType(ety) => {
70 if let Some(methods) = methods_for_type.get(&ety.ident) {
David Tolnay46a54e72020-04-17 14:48:21 -070071 out.next_section();
72 write_struct_with_methods(out, ety, methods);
Joel Galensonc1c4e7a2020-04-15 10:21:00 -070073 }
David Tolnayc1fe0052020-04-17 15:15:06 -070074 }
Joel Galensonc1c4e7a2020-04-15 10:21:00 -070075 _ => {}
David Tolnay7db73692019-10-20 14:51:12 -040076 }
77 }
78
79 if !header {
80 out.begin_block("extern \"C\"");
David Tolnayebef4a22020-03-17 15:33:47 -070081 write_exception_glue(out, apis);
David Tolnay7db73692019-10-20 14:51:12 -040082 for api in apis {
83 let (efn, write): (_, fn(_, _, _)) = match api {
84 Api::CxxFunction(efn) => (efn, write_cxx_function_shim),
85 Api::RustFunction(efn) => (efn, write_rust_function_decl),
86 _ => continue,
87 };
88 out.next_section();
89 write(out, efn, types);
90 }
David Tolnay9ad1fbc2020-03-01 14:01:24 -080091 out.end_block("extern \"C\"");
David Tolnay7db73692019-10-20 14:51:12 -040092 }
93
94 for api in apis {
95 if let Api::RustFunction(efn) = api {
96 out.next_section();
97 write_rust_function_shim(out, efn, types);
98 }
99 }
100
101 out.next_section();
102 for name in namespace.iter().rev() {
103 writeln!(out, "}} // namespace {}", name);
104 }
105
106 if !header {
107 out.next_section();
108 write_generic_instantiations(out, types);
109 }
110
David Tolnay9c68b1a2020-03-06 11:12:55 -0800111 out.prepend(out.include.to_string());
112
David Tolnay7db73692019-10-20 14:51:12 -0400113 out_file
114}
115
116fn write_includes(out: &mut OutFile, types: &Types) {
David Tolnay7db73692019-10-20 14:51:12 -0400117 for ty in types {
118 match ty {
119 Type::Ident(ident) => match Atom::from(ident) {
David Tolnay30430f12020-03-19 20:49:00 -0700120 Some(U8) | Some(U16) | Some(U32) | Some(U64) | Some(I8) | Some(I16) | Some(I32)
121 | Some(I64) => out.include.cstdint = true,
122 Some(Usize) => out.include.cstddef = true,
David Tolnay9c68b1a2020-03-06 11:12:55 -0800123 Some(CxxString) => out.include.string = true,
David Tolnay30430f12020-03-19 20:49:00 -0700124 Some(Bool) | Some(Isize) | Some(F32) | Some(F64) | Some(RustString) | None => {}
David Tolnay7db73692019-10-20 14:51:12 -0400125 },
David Tolnay9c68b1a2020-03-06 11:12:55 -0800126 Type::RustBox(_) => out.include.type_traits = true,
127 Type::UniquePtr(_) => out.include.memory = true,
Myron Ahneba35cf2020-02-05 19:41:51 +0700128 Type::Vector(_) => out.include.vector = true,
David Tolnay4770b472020-04-14 16:32:59 -0700129 Type::SliceRefU8(_) => out.include.cstdint = true,
Myron Ahneba35cf2020-02-05 19:41:51 +0700130 _ => (),
David Tolnay7db73692019-10-20 14:51:12 -0400131 }
132 }
David Tolnay7db73692019-10-20 14:51:12 -0400133}
134
David Tolnayf51447e2020-03-06 14:14:27 -0800135fn write_include_cxxbridge(out: &mut OutFile, apis: &[Api], types: &Types) {
David Tolnayb7a7cb62020-03-17 21:18:40 -0700136 let mut needs_rust_string = false;
137 let mut needs_rust_str = false;
David Tolnay4770b472020-04-14 16:32:59 -0700138 let mut needs_rust_slice = false;
David Tolnay7db73692019-10-20 14:51:12 -0400139 let mut needs_rust_box = false;
Myron Ahneba35cf2020-02-05 19:41:51 +0700140 let mut needs_rust_vec = false;
David Tolnay75dca2e2020-03-25 20:17:52 -0700141 let mut needs_rust_fn = false;
David Tolnay7db73692019-10-20 14:51:12 -0400142 for ty in types {
David Tolnayb7a7cb62020-03-17 21:18:40 -0700143 match ty {
144 Type::RustBox(_) => {
145 out.include.type_traits = true;
146 needs_rust_box = true;
147 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700148 Type::RustVec(_) => {
149 out.include.type_traits = true;
150 needs_rust_vec = true;
151 }
David Tolnayb7a7cb62020-03-17 21:18:40 -0700152 Type::Str(_) => {
153 out.include.cstdint = true;
154 out.include.string = true;
155 needs_rust_str = true;
156 }
David Tolnay75dca2e2020-03-25 20:17:52 -0700157 Type::Fn(_) => {
158 needs_rust_fn = true;
159 }
David Tolnay4770b472020-04-14 16:32:59 -0700160 Type::Slice(_) | Type::SliceRefU8(_) => {
161 needs_rust_slice = true;
162 }
David Tolnayb7a7cb62020-03-17 21:18:40 -0700163 ty if ty == RustString => {
164 out.include.array = true;
165 out.include.cstdint = true;
166 out.include.string = true;
167 needs_rust_string = true;
168 }
169 _ => {}
David Tolnay7db73692019-10-20 14:51:12 -0400170 }
171 }
172
David Tolnayb7a7cb62020-03-17 21:18:40 -0700173 let mut needs_rust_error = false;
174 let mut needs_unsafe_bitcopy = false;
David Tolnayf51447e2020-03-06 14:14:27 -0800175 let mut needs_manually_drop = false;
David Tolnay09011c32020-03-06 14:40:28 -0800176 let mut needs_maybe_uninit = false;
David Tolnay5d121442020-03-17 22:14:40 -0700177 let mut needs_trycatch = false;
David Tolnay09011c32020-03-06 14:40:28 -0800178 for api in apis {
David Tolnayb7a7cb62020-03-17 21:18:40 -0700179 match api {
180 Api::CxxFunction(efn) if !out.header => {
David Tolnay5d121442020-03-17 22:14:40 -0700181 if efn.throws {
182 needs_trycatch = true;
183 }
David Tolnayb7a7cb62020-03-17 21:18:40 -0700184 for arg in &efn.args {
185 if arg.ty == RustString {
186 needs_unsafe_bitcopy = true;
187 break;
188 }
David Tolnay09011c32020-03-06 14:40:28 -0800189 }
190 }
David Tolnayb7a7cb62020-03-17 21:18:40 -0700191 Api::RustFunction(efn) if !out.header => {
192 if efn.throws {
193 out.include.exception = true;
194 needs_rust_error = true;
195 }
196 for arg in &efn.args {
197 if arg.ty != RustString && types.needs_indirect_abi(&arg.ty) {
198 needs_manually_drop = true;
199 break;
200 }
201 }
202 if let Some(ret) = &efn.ret {
203 if types.needs_indirect_abi(ret) {
204 needs_maybe_uninit = true;
205 }
David Tolnayf51447e2020-03-06 14:14:27 -0800206 }
207 }
David Tolnayb7a7cb62020-03-17 21:18:40 -0700208 _ => {}
David Tolnayf51447e2020-03-06 14:14:27 -0800209 }
210 }
211
David Tolnay750755e2020-03-01 13:04:08 -0800212 out.begin_block("namespace rust");
David Tolnay8c730492020-03-13 01:29:06 -0700213 out.begin_block("inline namespace cxxbridge02");
David Tolnayf51447e2020-03-06 14:14:27 -0800214
David Tolnayb7a7cb62020-03-17 21:18:40 -0700215 if needs_rust_string
216 || needs_rust_str
David Tolnay4770b472020-04-14 16:32:59 -0700217 || needs_rust_slice
David Tolnayb7a7cb62020-03-17 21:18:40 -0700218 || needs_rust_box
Myron Ahneba35cf2020-02-05 19:41:51 +0700219 || needs_rust_vec
David Tolnay75dca2e2020-03-25 20:17:52 -0700220 || needs_rust_fn
David Tolnayb7a7cb62020-03-17 21:18:40 -0700221 || needs_rust_error
222 || needs_unsafe_bitcopy
223 || needs_manually_drop
224 || needs_maybe_uninit
David Tolnay5d121442020-03-17 22:14:40 -0700225 || needs_trycatch
David Tolnayb7a7cb62020-03-17 21:18:40 -0700226 {
David Tolnay736cbca2020-03-11 16:49:18 -0700227 writeln!(out, "// #include \"rust/cxx.h\"");
David Tolnayf51447e2020-03-06 14:14:27 -0800228 }
229
David Tolnayd1402742020-03-25 22:21:42 -0700230 if needs_rust_string {
231 out.next_section();
232 writeln!(out, "struct unsafe_bitcopy_t;");
233 }
234
David Tolnayb7a7cb62020-03-17 21:18:40 -0700235 write_header_section(out, needs_rust_string, "CXXBRIDGE02_RUST_STRING");
236 write_header_section(out, needs_rust_str, "CXXBRIDGE02_RUST_STR");
David Tolnay4770b472020-04-14 16:32:59 -0700237 write_header_section(out, needs_rust_slice, "CXXBRIDGE02_RUST_SLICE");
David Tolnayb7a7cb62020-03-17 21:18:40 -0700238 write_header_section(out, needs_rust_box, "CXXBRIDGE02_RUST_BOX");
Myron Ahneba35cf2020-02-05 19:41:51 +0700239 write_header_section(out, needs_rust_vec, "CXXBRIDGE02_RUST_VEC");
David Tolnay75dca2e2020-03-25 20:17:52 -0700240 write_header_section(out, needs_rust_fn, "CXXBRIDGE02_RUST_FN");
David Tolnayb7a7cb62020-03-17 21:18:40 -0700241 write_header_section(out, needs_rust_error, "CXXBRIDGE02_RUST_ERROR");
242 write_header_section(out, needs_unsafe_bitcopy, "CXXBRIDGE02_RUST_BITCOPY");
David Tolnayf51447e2020-03-06 14:14:27 -0800243
244 if needs_manually_drop {
245 out.next_section();
David Tolnay4791f1c2020-03-17 21:53:16 -0700246 out.include.utility = true;
David Tolnayf51447e2020-03-06 14:14:27 -0800247 writeln!(out, "template <typename T>");
248 writeln!(out, "union ManuallyDrop {{");
249 writeln!(out, " T value;");
250 writeln!(
251 out,
252 " ManuallyDrop(T &&value) : value(::std::move(value)) {{}}",
253 );
254 writeln!(out, " ~ManuallyDrop() {{}}");
255 writeln!(out, "}};");
256 }
257
David Tolnay09011c32020-03-06 14:40:28 -0800258 if needs_maybe_uninit {
259 out.next_section();
260 writeln!(out, "template <typename T>");
261 writeln!(out, "union MaybeUninit {{");
262 writeln!(out, " T value;");
263 writeln!(out, " MaybeUninit() {{}}");
264 writeln!(out, " ~MaybeUninit() {{}}");
265 writeln!(out, "}};");
266 }
267
David Tolnay3e3e0af2020-03-17 22:42:49 -0700268 out.end_block("namespace cxxbridge02");
269
David Tolnay5d121442020-03-17 22:14:40 -0700270 if needs_trycatch {
David Tolnay3e3e0af2020-03-17 22:42:49 -0700271 out.begin_block("namespace behavior");
David Tolnay5d121442020-03-17 22:14:40 -0700272 out.include.exception = true;
David Tolnay04722332020-03-18 11:31:54 -0700273 out.include.type_traits = true;
274 out.include.utility = true;
275 writeln!(out, "class missing {{}};");
276 writeln!(out, "missing trycatch(...);");
David Tolnay3e3e0af2020-03-17 22:42:49 -0700277 writeln!(out);
David Tolnay04722332020-03-18 11:31:54 -0700278 writeln!(out, "template <typename Try, typename Fail>");
279 writeln!(out, "static typename std::enable_if<");
David Tolnay3e3e0af2020-03-17 22:42:49 -0700280 writeln!(
281 out,
David Tolnay04722332020-03-18 11:31:54 -0700282 " std::is_same<decltype(trycatch(std::declval<Try>(), std::declval<Fail>())),",
David Tolnay3e3e0af2020-03-17 22:42:49 -0700283 );
David Tolnay04722332020-03-18 11:31:54 -0700284 writeln!(out, " missing>::value>::type");
285 writeln!(out, "trycatch(Try &&func, Fail &&fail) noexcept try {{");
David Tolnay5d121442020-03-17 22:14:40 -0700286 writeln!(out, " func();");
287 writeln!(out, "}} catch (const ::std::exception &e) {{");
288 writeln!(out, " fail(e.what());");
289 writeln!(out, "}}");
David Tolnay3e3e0af2020-03-17 22:42:49 -0700290 out.end_block("namespace behavior");
David Tolnay5d121442020-03-17 22:14:40 -0700291 }
292
David Tolnay9ad1fbc2020-03-01 14:01:24 -0800293 out.end_block("namespace rust");
David Tolnay7db73692019-10-20 14:51:12 -0400294}
295
David Tolnayb7a7cb62020-03-17 21:18:40 -0700296fn write_header_section(out: &mut OutFile, needed: bool, section: &str) {
David Tolnay8e086612020-04-10 12:20:46 -0700297 let section = include::get(section);
David Tolnayb7a7cb62020-03-17 21:18:40 -0700298 if needed {
299 out.next_section();
David Tolnay8e086612020-04-10 12:20:46 -0700300 for line in section.lines() {
David Tolnayb7a7cb62020-03-17 21:18:40 -0700301 if !line.trim_start().starts_with("//") {
302 writeln!(out, "{}", line);
303 }
304 }
305 }
306}
307
David Tolnay7db73692019-10-20 14:51:12 -0400308fn write_struct(out: &mut OutFile, strct: &Struct) {
309 for line in strct.doc.to_string().lines() {
310 writeln!(out, "//{}", line);
311 }
312 writeln!(out, "struct {} final {{", strct.ident);
313 for field in &strct.fields {
314 write!(out, " ");
315 write_type_space(out, &field.ty);
316 writeln!(out, "{};", field.ident);
317 }
318 writeln!(out, "}};");
319}
320
321fn write_struct_decl(out: &mut OutFile, ident: &Ident) {
322 writeln!(out, "struct {};", ident);
323}
324
David Tolnay8861bee2020-01-20 18:39:24 -0800325fn write_struct_using(out: &mut OutFile, ident: &Ident) {
326 writeln!(out, "using {} = {};", ident, ident);
327}
328
David Tolnayc1fe0052020-04-17 15:15:06 -0700329fn write_struct_with_methods(out: &mut OutFile, ety: &ExternType, methods: &[&ExternFn]) {
Joel Galensonc1c4e7a2020-04-15 10:21:00 -0700330 for line in ety.doc.to_string().lines() {
331 writeln!(out, "//{}", line);
332 }
333 writeln!(out, "struct {} final {{", ety.ident);
Joel Galenson187588e2020-04-17 16:19:54 -0700334 writeln!(out, " {}() = delete;", ety.ident);
David Tolnay44395e32020-04-19 14:52:49 -0700335 writeln!(out, " {}(const {} &) = delete;", ety.ident, ety.ident);
Joel Galenson968738f2020-04-15 14:19:33 -0700336 for method in methods {
Joel Galensonc1c4e7a2020-04-15 10:21:00 -0700337 write!(out, " ");
338 let sig = &method.sig;
David Tolnaya73853b2020-04-20 01:19:56 -0700339 let local_name = method.ident.to_string();
340 write_rust_function_shim_decl(out, &local_name, sig, false);
Joel Galensonc1c4e7a2020-04-15 10:21:00 -0700341 writeln!(out, ";");
342 }
343 writeln!(out, "}};");
344}
345
David Tolnayebef4a22020-03-17 15:33:47 -0700346fn write_exception_glue(out: &mut OutFile, apis: &[Api]) {
347 let mut has_cxx_throws = false;
348 for api in apis {
349 if let Api::CxxFunction(efn) = api {
350 if efn.throws {
351 has_cxx_throws = true;
352 break;
353 }
354 }
355 }
356
357 if has_cxx_throws {
358 out.next_section();
David Tolnaye68634c2020-03-18 12:03:40 -0700359 writeln!(
David Tolnayebef4a22020-03-17 15:33:47 -0700360 out,
361 "const char *cxxbridge02$exception(const char *, size_t);",
362 );
363 }
364}
365
David Tolnay7db73692019-10-20 14:51:12 -0400366fn write_cxx_function_shim(out: &mut OutFile, efn: &ExternFn, types: &Types) {
David Tolnayebef4a22020-03-17 15:33:47 -0700367 if efn.throws {
368 write!(out, "::rust::Str::Repr ");
369 } else {
David Tolnay99642622020-03-25 13:07:35 -0700370 write_extern_return_type_space(out, &efn.ret, types);
David Tolnayebef4a22020-03-17 15:33:47 -0700371 }
David Tolnay3caa50a2020-04-19 21:25:34 -0700372 let mangled = mangle::extern_fn(&out.namespace, efn);
373 write!(out, "{}(", mangled);
David Tolnaye439c772020-04-20 00:23:55 -0700374 if let Some(receiver) = &efn.receiver {
David Tolnay86710612020-04-20 00:30:32 -0700375 if receiver.mutability.is_none() {
376 write!(out, "const ");
377 }
David Tolnay05e11cc2020-04-20 02:13:56 -0700378 write!(out, "{} &self", receiver.ty);
Joel Galenson3d4f6122020-04-07 15:54:05 -0700379 }
David Tolnay7db73692019-10-20 14:51:12 -0400380 for (i, arg) in efn.args.iter().enumerate() {
Joel Galenson3d4f6122020-04-07 15:54:05 -0700381 if i > 0 || efn.receiver.is_some() {
David Tolnay7db73692019-10-20 14:51:12 -0400382 write!(out, ", ");
383 }
David Tolnaya46a2372020-03-06 10:03:48 -0800384 if arg.ty == RustString {
385 write!(out, "const ");
386 }
David Tolnay7db73692019-10-20 14:51:12 -0400387 write_extern_arg(out, arg, types);
388 }
David Tolnay277e3cc2020-03-17 00:11:01 -0700389 let indirect_return = indirect_return(efn, types);
David Tolnay7db73692019-10-20 14:51:12 -0400390 if indirect_return {
391 if !efn.args.is_empty() {
392 write!(out, ", ");
393 }
David Tolnay99642622020-03-25 13:07:35 -0700394 write_indirect_return_type_space(out, efn.ret.as_ref().unwrap());
David Tolnay7db73692019-10-20 14:51:12 -0400395 write!(out, "*return$");
396 }
397 writeln!(out, ") noexcept {{");
398 write!(out, " ");
399 write_return_type(out, &efn.ret);
Joel Galenson3d4f6122020-04-07 15:54:05 -0700400 match &efn.receiver {
401 None => write!(out, "(*{}$)(", efn.ident),
David Tolnay05e11cc2020-04-20 02:13:56 -0700402 Some(receiver) => write!(out, "({}::*{}$)(", receiver.ty, efn.ident),
Joel Galenson3d4f6122020-04-07 15:54:05 -0700403 }
David Tolnay7db73692019-10-20 14:51:12 -0400404 for (i, arg) in efn.args.iter().enumerate() {
405 if i > 0 {
406 write!(out, ", ");
407 }
408 write_type(out, &arg.ty);
409 }
Joel Galenson3d4f6122020-04-07 15:54:05 -0700410 write!(out, ")");
David Tolnay4e7123f2020-04-19 21:11:37 -0700411 if let Some(receiver) = &efn.receiver {
412 if receiver.mutability.is_none() {
413 write!(out, " const");
414 }
Joel Galenson3d4f6122020-04-07 15:54:05 -0700415 }
416 write!(out, " = ");
417 match &efn.receiver {
418 None => write!(out, "{}", efn.ident),
David Tolnay05e11cc2020-04-20 02:13:56 -0700419 Some(receiver) => write!(out, "&{}::{}", receiver.ty, efn.ident),
Joel Galenson3d4f6122020-04-07 15:54:05 -0700420 }
421 writeln!(out, ";");
David Tolnay7db73692019-10-20 14:51:12 -0400422 write!(out, " ");
David Tolnayebef4a22020-03-17 15:33:47 -0700423 if efn.throws {
424 writeln!(out, "::rust::Str::Repr throw$;");
David Tolnay3e3e0af2020-03-17 22:42:49 -0700425 writeln!(out, " ::rust::behavior::trycatch(");
David Tolnay5d121442020-03-17 22:14:40 -0700426 writeln!(out, " [&] {{");
427 write!(out, " ");
David Tolnayebef4a22020-03-17 15:33:47 -0700428 }
David Tolnay7db73692019-10-20 14:51:12 -0400429 if indirect_return {
430 write!(out, "new (return$) ");
David Tolnay99642622020-03-25 13:07:35 -0700431 write_indirect_return_type(out, efn.ret.as_ref().unwrap());
David Tolnay7db73692019-10-20 14:51:12 -0400432 write!(out, "(");
David Tolnay99642622020-03-25 13:07:35 -0700433 } else if efn.ret.is_some() {
David Tolnay7db73692019-10-20 14:51:12 -0400434 write!(out, "return ");
David Tolnay99642622020-03-25 13:07:35 -0700435 }
436 match &efn.ret {
437 Some(Type::Ref(_)) => write!(out, "&"),
438 Some(Type::Str(_)) if !indirect_return => write!(out, "::rust::Str::Repr("),
David Tolnayeb952ba2020-04-14 15:02:24 -0700439 Some(Type::SliceRefU8(_)) if !indirect_return => {
440 write!(out, "::rust::Slice<uint8_t>::Repr(")
441 }
David Tolnay99642622020-03-25 13:07:35 -0700442 _ => {}
David Tolnay7db73692019-10-20 14:51:12 -0400443 }
Joel Galenson3d4f6122020-04-07 15:54:05 -0700444 match &efn.receiver {
445 None => write!(out, "{}$(", efn.ident),
David Tolnay41909e62020-04-20 00:55:15 -0700446 Some(_) => write!(out, "(self.*{}$)(", efn.ident),
Joel Galenson3d4f6122020-04-07 15:54:05 -0700447 }
David Tolnay7db73692019-10-20 14:51:12 -0400448 for (i, arg) in efn.args.iter().enumerate() {
449 if i > 0 {
450 write!(out, ", ");
451 }
452 if let Type::RustBox(_) = &arg.ty {
453 write_type(out, &arg.ty);
454 write!(out, "::from_raw({})", arg.ident);
455 } else if let Type::UniquePtr(_) = &arg.ty {
456 write_type(out, &arg.ty);
457 write!(out, "({})", arg.ident);
David Tolnaya46a2372020-03-06 10:03:48 -0800458 } else if arg.ty == RustString {
David Tolnaycc3767f2020-03-06 10:41:51 -0800459 write!(
460 out,
461 "::rust::String(::rust::unsafe_bitcopy, *{})",
462 arg.ident,
463 );
David Tolnay7db73692019-10-20 14:51:12 -0400464 } else if types.needs_indirect_abi(&arg.ty) {
David Tolnay4791f1c2020-03-17 21:53:16 -0700465 out.include.utility = true;
David Tolnay7e219b82020-03-01 13:14:51 -0800466 write!(out, "::std::move(*{})", arg.ident);
David Tolnay7db73692019-10-20 14:51:12 -0400467 } else {
468 write!(out, "{}", arg.ident);
469 }
470 }
471 write!(out, ")");
472 match &efn.ret {
473 Some(Type::RustBox(_)) => write!(out, ".into_raw()"),
474 Some(Type::UniquePtr(_)) => write!(out, ".release()"),
Myron Ahneba35cf2020-02-05 19:41:51 +0700475 Some(Type::Vector(_)) => write!(
476 out,
477 " /* Use RVO to convert to r-value and move construct */"
478 ),
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700479 Some(Type::Str(_)) | Some(Type::SliceRefU8(_)) if !indirect_return => write!(out, ")"),
David Tolnay7db73692019-10-20 14:51:12 -0400480 _ => {}
481 }
482 if indirect_return {
483 write!(out, ")");
484 }
485 writeln!(out, ";");
David Tolnayebef4a22020-03-17 15:33:47 -0700486 if efn.throws {
487 out.include.cstring = true;
David Tolnay5d121442020-03-17 22:14:40 -0700488 writeln!(out, " throw$.ptr = nullptr;");
489 writeln!(out, " }},");
David Tolnay82c16172020-03-17 22:54:12 -0700490 writeln!(out, " [&](const char *catch$) noexcept {{");
David Tolnay5d121442020-03-17 22:14:40 -0700491 writeln!(out, " throw$.len = ::std::strlen(catch$);");
David Tolnayebef4a22020-03-17 15:33:47 -0700492 writeln!(
493 out,
David Tolnay5d121442020-03-17 22:14:40 -0700494 " throw$.ptr = cxxbridge02$exception(catch$, throw$.len);",
David Tolnayebef4a22020-03-17 15:33:47 -0700495 );
David Tolnay5d121442020-03-17 22:14:40 -0700496 writeln!(out, " }});");
David Tolnayebef4a22020-03-17 15:33:47 -0700497 writeln!(out, " return throw$;");
498 }
David Tolnay7db73692019-10-20 14:51:12 -0400499 writeln!(out, "}}");
David Tolnay75dca2e2020-03-25 20:17:52 -0700500 for arg in &efn.args {
501 if let Type::Fn(f) = &arg.ty {
502 let var = &arg.ident;
503 write_function_pointer_trampoline(out, efn, var, f, types);
504 }
505 }
506}
507
508fn write_function_pointer_trampoline(
509 out: &mut OutFile,
510 efn: &ExternFn,
511 var: &Ident,
512 f: &Signature,
513 types: &Types,
514) {
515 out.next_section();
David Tolnay891061b2020-04-19 22:42:33 -0700516 let r_trampoline = mangle::r_trampoline(&out.namespace, efn, var);
David Tolnay75dca2e2020-03-25 20:17:52 -0700517 let indirect_call = true;
518 write_rust_function_decl_impl(out, &r_trampoline, f, types, indirect_call);
519
520 out.next_section();
David Tolnaya73853b2020-04-20 01:19:56 -0700521 let c_trampoline = mangle::c_trampoline(&out.namespace, efn, var).to_string();
David Tolnay75dca2e2020-03-25 20:17:52 -0700522 write_rust_function_shim_impl(out, &c_trampoline, f, types, &r_trampoline, indirect_call);
David Tolnay7db73692019-10-20 14:51:12 -0400523}
524
525fn write_rust_function_decl(out: &mut OutFile, efn: &ExternFn, types: &Types) {
David Tolnay3caa50a2020-04-19 21:25:34 -0700526 let link_name = mangle::extern_fn(&out.namespace, efn);
David Tolnay75dca2e2020-03-25 20:17:52 -0700527 let indirect_call = false;
528 write_rust_function_decl_impl(out, &link_name, efn, types, indirect_call);
529}
530
531fn write_rust_function_decl_impl(
532 out: &mut OutFile,
David Tolnay891061b2020-04-19 22:42:33 -0700533 link_name: &Symbol,
David Tolnay75dca2e2020-03-25 20:17:52 -0700534 sig: &Signature,
535 types: &Types,
536 indirect_call: bool,
537) {
538 if sig.throws {
David Tolnay1e548172020-03-16 13:37:09 -0700539 write!(out, "::rust::Str::Repr ");
540 } else {
David Tolnay75dca2e2020-03-25 20:17:52 -0700541 write_extern_return_type_space(out, &sig.ret, types);
David Tolnay1e548172020-03-16 13:37:09 -0700542 }
David Tolnay75dca2e2020-03-25 20:17:52 -0700543 write!(out, "{}(", link_name);
544 let mut needs_comma = false;
David Tolnaye439c772020-04-20 00:23:55 -0700545 if let Some(receiver) = &sig.receiver {
David Tolnay86710612020-04-20 00:30:32 -0700546 if receiver.mutability.is_none() {
547 write!(out, "const ");
548 }
David Tolnay05e11cc2020-04-20 02:13:56 -0700549 write!(out, "{} &self", receiver.ty);
Joel Galensonc1c4e7a2020-04-15 10:21:00 -0700550 needs_comma = true;
551 }
David Tolnay75dca2e2020-03-25 20:17:52 -0700552 for arg in &sig.args {
553 if needs_comma {
David Tolnay7db73692019-10-20 14:51:12 -0400554 write!(out, ", ");
555 }
556 write_extern_arg(out, arg, types);
David Tolnay75dca2e2020-03-25 20:17:52 -0700557 needs_comma = true;
David Tolnay7db73692019-10-20 14:51:12 -0400558 }
David Tolnay75dca2e2020-03-25 20:17:52 -0700559 if indirect_return(sig, types) {
560 if needs_comma {
David Tolnay7db73692019-10-20 14:51:12 -0400561 write!(out, ", ");
562 }
David Tolnay75dca2e2020-03-25 20:17:52 -0700563 write_return_type(out, &sig.ret);
David Tolnay7db73692019-10-20 14:51:12 -0400564 write!(out, "*return$");
David Tolnay75dca2e2020-03-25 20:17:52 -0700565 needs_comma = true;
566 }
567 if indirect_call {
568 if needs_comma {
569 write!(out, ", ");
570 }
571 write!(out, "void *");
David Tolnay7db73692019-10-20 14:51:12 -0400572 }
573 writeln!(out, ") noexcept;");
574}
575
576fn write_rust_function_shim(out: &mut OutFile, efn: &ExternFn, types: &Types) {
David Tolnay7db73692019-10-20 14:51:12 -0400577 for line in efn.doc.to_string().lines() {
578 writeln!(out, "//{}", line);
579 }
David Tolnaya73853b2020-04-20 01:19:56 -0700580 let local_name = match &efn.sig.receiver {
581 None => efn.ident.to_string(),
David Tolnay05e11cc2020-04-20 02:13:56 -0700582 Some(receiver) => format!("{}::{}", receiver.ty, efn.ident),
David Tolnaya73853b2020-04-20 01:19:56 -0700583 };
David Tolnay3caa50a2020-04-19 21:25:34 -0700584 let invoke = mangle::extern_fn(&out.namespace, efn);
David Tolnay75dca2e2020-03-25 20:17:52 -0700585 let indirect_call = false;
586 write_rust_function_shim_impl(out, &local_name, efn, types, &invoke, indirect_call);
587}
588
Joel Galensonc1c4e7a2020-04-15 10:21:00 -0700589fn write_rust_function_shim_decl(
David Tolnay75dca2e2020-03-25 20:17:52 -0700590 out: &mut OutFile,
David Tolnaya73853b2020-04-20 01:19:56 -0700591 local_name: &str,
David Tolnay75dca2e2020-03-25 20:17:52 -0700592 sig: &Signature,
David Tolnay75dca2e2020-03-25 20:17:52 -0700593 indirect_call: bool,
594) {
595 write_return_type(out, &sig.ret);
596 write!(out, "{}(", local_name);
597 for (i, arg) in sig.args.iter().enumerate() {
David Tolnay7db73692019-10-20 14:51:12 -0400598 if i > 0 {
599 write!(out, ", ");
600 }
601 write_type_space(out, &arg.ty);
602 write!(out, "{}", arg.ident);
603 }
David Tolnay75dca2e2020-03-25 20:17:52 -0700604 if indirect_call {
605 if !sig.args.is_empty() {
606 write!(out, ", ");
607 }
608 write!(out, "void *extern$");
609 }
David Tolnay1e548172020-03-16 13:37:09 -0700610 write!(out, ")");
David Tolnay86710612020-04-20 00:30:32 -0700611 if let Some(receiver) = &sig.receiver {
612 if receiver.mutability.is_none() {
613 write!(out, " const");
614 }
615 }
David Tolnay75dca2e2020-03-25 20:17:52 -0700616 if !sig.throws {
David Tolnay1e548172020-03-16 13:37:09 -0700617 write!(out, " noexcept");
618 }
Joel Galensonc1c4e7a2020-04-15 10:21:00 -0700619}
620
621fn write_rust_function_shim_impl(
622 out: &mut OutFile,
David Tolnaya73853b2020-04-20 01:19:56 -0700623 local_name: &str,
Joel Galensonc1c4e7a2020-04-15 10:21:00 -0700624 sig: &Signature,
625 types: &Types,
David Tolnay891061b2020-04-19 22:42:33 -0700626 invoke: &Symbol,
Joel Galensonc1c4e7a2020-04-15 10:21:00 -0700627 indirect_call: bool,
628) {
629 if out.header && sig.receiver.is_some() {
630 // We've already defined this inside the struct.
631 return;
632 }
David Tolnaya73853b2020-04-20 01:19:56 -0700633 write_rust_function_shim_decl(out, local_name, sig, indirect_call);
David Tolnay7db73692019-10-20 14:51:12 -0400634 if out.header {
635 writeln!(out, ";");
David Tolnay439cde22020-04-20 00:46:25 -0700636 return;
David Tolnay7db73692019-10-20 14:51:12 -0400637 }
David Tolnay439cde22020-04-20 00:46:25 -0700638 writeln!(out, " {{");
639 for arg in &sig.args {
640 if arg.ty != RustString && types.needs_indirect_abi(&arg.ty) {
641 out.include.utility = true;
642 write!(out, " ::rust::ManuallyDrop<");
643 write_type(out, &arg.ty);
644 writeln!(out, "> {}$(::std::move({0}));", arg.ident);
645 }
646 }
647 write!(out, " ");
648 let indirect_return = indirect_return(sig, types);
649 if indirect_return {
650 write!(out, "::rust::MaybeUninit<");
651 write_type(out, sig.ret.as_ref().unwrap());
652 writeln!(out, "> return$;");
653 write!(out, " ");
654 } else if let Some(ret) = &sig.ret {
655 write!(out, "return ");
656 match ret {
657 Type::RustBox(_) => {
658 write_type(out, ret);
659 write!(out, "::from_raw(");
660 }
661 Type::UniquePtr(_) => {
662 write_type(out, ret);
663 write!(out, "(");
664 }
665 Type::Ref(_) => write!(out, "*"),
666 _ => {}
667 }
668 }
669 if sig.throws {
670 write!(out, "::rust::Str::Repr error$ = ");
671 }
672 write!(out, "{}(", invoke);
673 if sig.receiver.is_some() {
674 write!(out, "*this");
675 }
676 for (i, arg) in sig.args.iter().enumerate() {
677 if i > 0 || sig.receiver.is_some() {
678 write!(out, ", ");
679 }
680 match &arg.ty {
681 Type::Str(_) => write!(out, "::rust::Str::Repr("),
682 Type::SliceRefU8(_) => write!(out, "::rust::Slice<uint8_t>::Repr("),
683 ty if types.needs_indirect_abi(ty) => write!(out, "&"),
684 _ => {}
685 }
686 write!(out, "{}", arg.ident);
687 match &arg.ty {
688 Type::RustBox(_) => write!(out, ".into_raw()"),
689 Type::UniquePtr(_) => write!(out, ".release()"),
690 Type::Str(_) | Type::SliceRefU8(_) => write!(out, ")"),
691 ty if ty != RustString && types.needs_indirect_abi(ty) => write!(out, "$.value"),
692 _ => {}
693 }
694 }
695 if indirect_return {
696 if !sig.args.is_empty() {
697 write!(out, ", ");
698 }
699 write!(out, "&return$.value");
700 }
701 if indirect_call {
702 if !sig.args.is_empty() || indirect_return {
703 write!(out, ", ");
704 }
705 write!(out, "extern$");
706 }
707 write!(out, ")");
708 if let Some(ret) = &sig.ret {
709 if let Type::RustBox(_) | Type::UniquePtr(_) = ret {
710 write!(out, ")");
711 }
712 }
713 writeln!(out, ";");
714 if sig.throws {
715 writeln!(out, " if (error$.ptr) {{");
716 writeln!(out, " throw ::rust::Error(error$);");
717 writeln!(out, " }}");
718 }
719 if indirect_return {
720 out.include.utility = true;
721 writeln!(out, " return ::std::move(return$.value);");
722 }
723 writeln!(out, "}}");
David Tolnay7db73692019-10-20 14:51:12 -0400724}
725
726fn write_return_type(out: &mut OutFile, ty: &Option<Type>) {
727 match ty {
728 None => write!(out, "void "),
729 Some(ty) => write_type_space(out, ty),
730 }
731}
732
David Tolnay75dca2e2020-03-25 20:17:52 -0700733fn indirect_return(sig: &Signature, types: &Types) -> bool {
734 sig.ret
David Tolnay277e3cc2020-03-17 00:11:01 -0700735 .as_ref()
David Tolnay75dca2e2020-03-25 20:17:52 -0700736 .map_or(false, |ret| sig.throws || types.needs_indirect_abi(ret))
David Tolnay277e3cc2020-03-17 00:11:01 -0700737}
738
David Tolnay99642622020-03-25 13:07:35 -0700739fn write_indirect_return_type(out: &mut OutFile, ty: &Type) {
740 match ty {
741 Type::RustBox(ty) | Type::UniquePtr(ty) => {
742 write_type_space(out, &ty.inner);
743 write!(out, "*");
744 }
745 Type::Ref(ty) => {
746 if ty.mutability.is_none() {
747 write!(out, "const ");
748 }
749 write_type(out, &ty.inner);
750 write!(out, " *");
751 }
752 Type::Str(_) => write!(out, "::rust::Str::Repr"),
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700753 Type::SliceRefU8(_) => write!(out, "::rust::Slice<uint8_t>::Repr"),
David Tolnay99642622020-03-25 13:07:35 -0700754 _ => write_type(out, ty),
755 }
756}
757
758fn write_indirect_return_type_space(out: &mut OutFile, ty: &Type) {
759 write_indirect_return_type(out, ty);
760 match ty {
761 Type::RustBox(_) | Type::UniquePtr(_) | Type::Ref(_) => {}
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700762 Type::Str(_) | Type::SliceRefU8(_) => write!(out, " "),
David Tolnay99642622020-03-25 13:07:35 -0700763 _ => write_space_after_type(out, ty),
764 }
765}
766
767fn write_extern_return_type_space(out: &mut OutFile, ty: &Option<Type>, types: &Types) {
David Tolnay7db73692019-10-20 14:51:12 -0400768 match ty {
769 Some(Type::RustBox(ty)) | Some(Type::UniquePtr(ty)) => {
770 write_type_space(out, &ty.inner);
771 write!(out, "*");
772 }
David Tolnay4a441222020-01-25 16:24:27 -0800773 Some(Type::Ref(ty)) => {
774 if ty.mutability.is_none() {
775 write!(out, "const ");
776 }
777 write_type(out, &ty.inner);
778 write!(out, " *");
779 }
David Tolnay750755e2020-03-01 13:04:08 -0800780 Some(Type::Str(_)) => write!(out, "::rust::Str::Repr "),
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700781 Some(Type::SliceRefU8(_)) => write!(out, "::rust::Slice<uint8_t>::Repr "),
David Tolnay7db73692019-10-20 14:51:12 -0400782 Some(ty) if types.needs_indirect_abi(ty) => write!(out, "void "),
783 _ => write_return_type(out, ty),
784 }
785}
786
787fn write_extern_arg(out: &mut OutFile, arg: &Var, types: &Types) {
788 match &arg.ty {
Myron Ahneba35cf2020-02-05 19:41:51 +0700789 Type::RustBox(ty) | Type::UniquePtr(ty) | Type::Vector(ty) => {
David Tolnay7db73692019-10-20 14:51:12 -0400790 write_type_space(out, &ty.inner);
791 write!(out, "*");
792 }
David Tolnay750755e2020-03-01 13:04:08 -0800793 Type::Str(_) => write!(out, "::rust::Str::Repr "),
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700794 Type::SliceRefU8(_) => write!(out, "::rust::Slice<uint8_t>::Repr "),
David Tolnay7db73692019-10-20 14:51:12 -0400795 _ => write_type_space(out, &arg.ty),
796 }
797 if types.needs_indirect_abi(&arg.ty) {
798 write!(out, "*");
799 }
800 write!(out, "{}", arg.ident);
801}
802
803fn write_type(out: &mut OutFile, ty: &Type) {
804 match ty {
805 Type::Ident(ident) => match Atom::from(ident) {
Myron Ahneba35cf2020-02-05 19:41:51 +0700806 Some(a) => write!(out, "{}", a.to_cxx()),
David Tolnay7db73692019-10-20 14:51:12 -0400807 None => write!(out, "{}", ident),
808 },
809 Type::RustBox(ty) => {
David Tolnay750755e2020-03-01 13:04:08 -0800810 write!(out, "::rust::Box<");
David Tolnay7db73692019-10-20 14:51:12 -0400811 write_type(out, &ty.inner);
812 write!(out, ">");
813 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700814 Type::RustVec(ty) => {
815 write!(out, "::rust::Vec<");
816 write_type(out, &ty.inner);
817 write!(out, ">");
818 }
David Tolnay7db73692019-10-20 14:51:12 -0400819 Type::UniquePtr(ptr) => {
David Tolnay7e219b82020-03-01 13:14:51 -0800820 write!(out, "::std::unique_ptr<");
David Tolnay7db73692019-10-20 14:51:12 -0400821 write_type(out, &ptr.inner);
822 write!(out, ">");
823 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700824 Type::Vector(ty) => {
825 write!(out, "::std::vector<");
826 write_type(out, &ty.inner);
827 write!(out, ">");
828 }
David Tolnay7db73692019-10-20 14:51:12 -0400829 Type::Ref(r) => {
830 if r.mutability.is_none() {
831 write!(out, "const ");
832 }
833 write_type(out, &r.inner);
834 write!(out, " &");
835 }
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700836 Type::Slice(_) => {
837 // For now, only U8 slices are supported, which are covered separately below
838 unreachable!()
839 }
David Tolnay7db73692019-10-20 14:51:12 -0400840 Type::Str(_) => {
David Tolnay750755e2020-03-01 13:04:08 -0800841 write!(out, "::rust::Str");
David Tolnay7db73692019-10-20 14:51:12 -0400842 }
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700843 Type::SliceRefU8(_) => {
844 write!(out, "::rust::Slice<uint8_t>");
845 }
David Tolnay75dca2e2020-03-25 20:17:52 -0700846 Type::Fn(f) => {
847 write!(out, "::rust::{}<", if f.throws { "TryFn" } else { "Fn" });
848 match &f.ret {
849 Some(ret) => write_type(out, ret),
850 None => write!(out, "void"),
851 }
852 write!(out, "(");
853 for (i, arg) in f.args.iter().enumerate() {
854 if i > 0 {
855 write!(out, ", ");
856 }
857 write_type(out, &arg.ty);
858 }
859 write!(out, ")>");
860 }
David Tolnay2fb14e92020-03-15 23:11:38 -0700861 Type::Void(_) => unreachable!(),
David Tolnay7db73692019-10-20 14:51:12 -0400862 }
863}
864
865fn write_type_space(out: &mut OutFile, ty: &Type) {
866 write_type(out, ty);
David Tolnay99642622020-03-25 13:07:35 -0700867 write_space_after_type(out, ty);
868}
869
870fn write_space_after_type(out: &mut OutFile, ty: &Type) {
David Tolnay7db73692019-10-20 14:51:12 -0400871 match ty {
David Tolnayeb952ba2020-04-14 15:02:24 -0700872 Type::Ident(_)
873 | Type::RustBox(_)
874 | Type::UniquePtr(_)
875 | Type::Str(_)
Myron Ahneba35cf2020-02-05 19:41:51 +0700876 | Type::Vector(_)
877 | Type::RustVec(_)
David Tolnayeb952ba2020-04-14 15:02:24 -0700878 | Type::SliceRefU8(_)
879 | Type::Fn(_) => write!(out, " "),
David Tolnay7db73692019-10-20 14:51:12 -0400880 Type::Ref(_) => {}
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700881 Type::Void(_) | Type::Slice(_) => unreachable!(),
David Tolnay7db73692019-10-20 14:51:12 -0400882 }
883}
884
885fn write_generic_instantiations(out: &mut OutFile, types: &Types) {
886 fn allow_unique_ptr(ident: &Ident) -> bool {
887 Atom::from(ident).is_none()
888 }
889
Myron Ahneba35cf2020-02-05 19:41:51 +0700890 fn allow_vector(ident: &Ident) -> bool {
891 // Note: built-in types such as u8 are already defined in cxx.cc
892 Atom::from(ident).is_none()
893 }
894
David Tolnay7db73692019-10-20 14:51:12 -0400895 out.begin_block("extern \"C\"");
896 for ty in types {
897 if let Type::RustBox(ty) = ty {
898 if let Type::Ident(inner) = &ty.inner {
899 out.next_section();
900 write_rust_box_extern(out, inner);
901 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700902 } else if let Type::RustVec(ty) = ty {
903 if let Type::Ident(_) = &ty.inner {
904 out.next_section();
905 write_rust_vec_extern(out, &ty.inner);
906 }
David Tolnay7db73692019-10-20 14:51:12 -0400907 } else if let Type::UniquePtr(ptr) = ty {
908 if let Type::Ident(inner) = &ptr.inner {
909 if allow_unique_ptr(inner) {
910 out.next_section();
Myron Ahneba35cf2020-02-05 19:41:51 +0700911 write_unique_ptr(out, &ptr.inner, types);
912 }
913 } else if let Type::Vector(ptr1) = &ptr.inner {
914 if let Type::Ident(inner) = &ptr1.inner {
915 if allow_vector(inner) {
916 out.next_section();
917 write_unique_ptr(out, &ptr.inner, types);
918 }
919 }
920 }
921 } else if let Type::Vector(ptr) = ty {
922 if let Type::Ident(inner) = &ptr.inner {
923 if allow_vector(inner) {
924 out.next_section();
925 write_vector(out, inner);
David Tolnay7db73692019-10-20 14:51:12 -0400926 }
927 }
928 }
929 }
David Tolnay9ad1fbc2020-03-01 14:01:24 -0800930 out.end_block("extern \"C\"");
David Tolnay7db73692019-10-20 14:51:12 -0400931
David Tolnay750755e2020-03-01 13:04:08 -0800932 out.begin_block("namespace rust");
David Tolnay8c730492020-03-13 01:29:06 -0700933 out.begin_block("inline namespace cxxbridge02");
David Tolnay7db73692019-10-20 14:51:12 -0400934 for ty in types {
935 if let Type::RustBox(ty) = ty {
936 if let Type::Ident(inner) = &ty.inner {
937 write_rust_box_impl(out, inner);
938 }
Myron Ahneba35cf2020-02-05 19:41:51 +0700939 } else if let Type::RustVec(ty) = ty {
940 if let Type::Ident(_) = &ty.inner {
941 write_rust_vec_impl(out, &ty.inner);
942 }
David Tolnay7db73692019-10-20 14:51:12 -0400943 }
944 }
David Tolnay8c730492020-03-13 01:29:06 -0700945 out.end_block("namespace cxxbridge02");
David Tolnay9ad1fbc2020-03-01 14:01:24 -0800946 out.end_block("namespace rust");
David Tolnay7db73692019-10-20 14:51:12 -0400947}
948
949fn write_rust_box_extern(out: &mut OutFile, ident: &Ident) {
950 let mut inner = String::new();
951 for name in &out.namespace {
952 inner += name;
953 inner += "::";
954 }
955 inner += &ident.to_string();
956 let instance = inner.replace("::", "$");
957
David Tolnay8c730492020-03-13 01:29:06 -0700958 writeln!(out, "#ifndef CXXBRIDGE02_RUST_BOX_{}", instance);
959 writeln!(out, "#define CXXBRIDGE02_RUST_BOX_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400960 writeln!(
961 out,
David Tolnay8c730492020-03-13 01:29:06 -0700962 "void cxxbridge02$box${}$uninit(::rust::Box<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400963 instance, inner,
964 );
965 writeln!(
966 out,
David Tolnay8c730492020-03-13 01:29:06 -0700967 "void cxxbridge02$box${}$drop(::rust::Box<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400968 instance, inner,
969 );
David Tolnay8c730492020-03-13 01:29:06 -0700970 writeln!(out, "#endif // CXXBRIDGE02_RUST_BOX_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400971}
972
Myron Ahneba35cf2020-02-05 19:41:51 +0700973fn write_rust_vec_extern(out: &mut OutFile, ty: &Type) {
974 let namespace = out.namespace.iter().cloned().collect::<Vec<String>>();
975 let inner = ty.to_typename(&namespace);
976 let instance = ty.to_mangled(&namespace);
977
978 writeln!(out, "#ifndef CXXBRIDGE02_RUST_VEC_{}", instance);
979 writeln!(out, "#define CXXBRIDGE02_RUST_VEC_{}", instance);
980 writeln!(
981 out,
982 "void cxxbridge02$rust_vec${}$drop(::rust::Vec<{}> *ptr) noexcept;",
983 instance, inner,
984 );
985 writeln!(
986 out,
987 "void cxxbridge02$rust_vec${}$vector_from(const ::rust::Vec<{}> *ptr, const std::vector<{}> &vector) noexcept;",
988 instance, inner, inner
989 );
990 writeln!(
991 out,
992 "size_t cxxbridge02$rust_vec${}$len(const ::rust::Vec<{}> *ptr) noexcept;",
993 instance, inner,
994 );
995 writeln!(out, "#endif // CXXBRIDGE02_RUST_VEC_{}", instance);
996}
997
David Tolnay7db73692019-10-20 14:51:12 -0400998fn write_rust_box_impl(out: &mut OutFile, ident: &Ident) {
999 let mut inner = String::new();
1000 for name in &out.namespace {
1001 inner += name;
1002 inner += "::";
1003 }
1004 inner += &ident.to_string();
1005 let instance = inner.replace("::", "$");
1006
1007 writeln!(out, "template <>");
David Tolnay324437a2020-03-01 13:02:24 -08001008 writeln!(out, "void Box<{}>::uninit() noexcept {{", inner);
David Tolnay737e02e2020-04-04 21:52:46 -07001009 writeln!(out, " cxxbridge02$box${}$uninit(this);", instance);
David Tolnay7db73692019-10-20 14:51:12 -04001010 writeln!(out, "}}");
1011
1012 writeln!(out, "template <>");
David Tolnay324437a2020-03-01 13:02:24 -08001013 writeln!(out, "void Box<{}>::drop() noexcept {{", inner);
David Tolnay737e02e2020-04-04 21:52:46 -07001014 writeln!(out, " cxxbridge02$box${}$drop(this);", instance);
David Tolnay7db73692019-10-20 14:51:12 -04001015 writeln!(out, "}}");
David Tolnay7db73692019-10-20 14:51:12 -04001016}
1017
Myron Ahneba35cf2020-02-05 19:41:51 +07001018fn write_rust_vec_impl(out: &mut OutFile, ty: &Type) {
1019 let namespace = out.namespace.iter().cloned().collect::<Vec<String>>();
1020 let inner = ty.to_typename(&namespace);
1021 let instance = ty.to_mangled(&namespace);
David Tolnay4791f1c2020-03-17 21:53:16 -07001022
Myron Ahneba35cf2020-02-05 19:41:51 +07001023 writeln!(out, "template <>");
1024 writeln!(out, "void Vec<{}>::drop() noexcept {{", inner);
1025 writeln!(
1026 out,
1027 " return cxxbridge02$rust_vec${}$drop(this);",
1028 instance
1029 );
1030 writeln!(out, "}}");
1031
1032 writeln!(out, "template <>");
1033 writeln!(out, "size_t Vec<{}>::size() const noexcept {{", inner);
1034 writeln!(out, " return cxxbridge02$rust_vec${}$len(this);", instance);
1035 writeln!(out, "}}");
1036
1037 writeln!(out, "template <>");
1038 writeln!(
1039 out,
1040 "Vec<{}>::operator std::vector<{}>() const noexcept {{",
1041 inner, inner
1042 );
1043 writeln!(
1044 out,
1045 " std::vector<{}> v; v.reserve(this->size()); cxxbridge02$rust_vec${}$vector_from(this, v); return v;",
1046 inner, instance,
1047 );
1048 writeln!(out, "}}");
1049}
1050
1051fn write_unique_ptr(out: &mut OutFile, ty: &Type, types: &Types) {
1052 out.include.utility = true;
1053 let namespace = out.namespace.iter().cloned().collect::<Vec<String>>();
1054 let inner = ty.to_typename(&namespace);
1055 let instance = ty.to_mangled(&namespace);
David Tolnay7db73692019-10-20 14:51:12 -04001056
David Tolnay8c730492020-03-13 01:29:06 -07001057 writeln!(out, "#ifndef CXXBRIDGE02_UNIQUE_PTR_{}", instance);
1058 writeln!(out, "#define CXXBRIDGE02_UNIQUE_PTR_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -04001059 writeln!(
1060 out,
David Tolnay7e219b82020-03-01 13:14:51 -08001061 "static_assert(sizeof(::std::unique_ptr<{}>) == sizeof(void *), \"\");",
David Tolnay7db73692019-10-20 14:51:12 -04001062 inner,
1063 );
1064 writeln!(
1065 out,
David Tolnay7e219b82020-03-01 13:14:51 -08001066 "static_assert(alignof(::std::unique_ptr<{}>) == alignof(void *), \"\");",
David Tolnay7db73692019-10-20 14:51:12 -04001067 inner,
1068 );
1069 writeln!(
1070 out,
David Tolnay8c730492020-03-13 01:29:06 -07001071 "void cxxbridge02$unique_ptr${}$null(::std::unique_ptr<{}> *ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -04001072 instance, inner,
1073 );
David Tolnay7e219b82020-03-01 13:14:51 -08001074 writeln!(out, " new (ptr) ::std::unique_ptr<{}>();", inner);
David Tolnay7db73692019-10-20 14:51:12 -04001075 writeln!(out, "}}");
Myron Ahneba35cf2020-02-05 19:41:51 +07001076 match ty {
1077 Type::Ident(ident) if types.structs.contains_key(ident) => {
1078 writeln!(
David Tolnay53838912020-04-09 20:56:44 -07001079 out,
1080 "void cxxbridge02$unique_ptr${}$new(::std::unique_ptr<{}> *ptr, {} *value) noexcept {{",
1081 instance, inner, inner,
1082 );
Myron Ahneba35cf2020-02-05 19:41:51 +07001083 writeln!(
1084 out,
1085 " new (ptr) ::std::unique_ptr<{}>(new {}(::std::move(*value)));",
1086 inner, inner,
1087 );
1088 writeln!(out, "}}");
1089 }
1090 _ => (),
David Tolnay53838912020-04-09 20:56:44 -07001091 }
David Tolnay7db73692019-10-20 14:51:12 -04001092 writeln!(
1093 out,
David Tolnay8c730492020-03-13 01:29:06 -07001094 "void cxxbridge02$unique_ptr${}$raw(::std::unique_ptr<{}> *ptr, {} *raw) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -04001095 instance, inner, inner,
1096 );
David Tolnay7e219b82020-03-01 13:14:51 -08001097 writeln!(out, " new (ptr) ::std::unique_ptr<{}>(raw);", inner);
David Tolnay7db73692019-10-20 14:51:12 -04001098 writeln!(out, "}}");
1099 writeln!(
1100 out,
David Tolnay8c730492020-03-13 01:29:06 -07001101 "const {} *cxxbridge02$unique_ptr${}$get(const ::std::unique_ptr<{}>& ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -04001102 inner, instance, inner,
1103 );
1104 writeln!(out, " return ptr.get();");
1105 writeln!(out, "}}");
1106 writeln!(
1107 out,
David Tolnay8c730492020-03-13 01:29:06 -07001108 "{} *cxxbridge02$unique_ptr${}$release(::std::unique_ptr<{}>& ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -04001109 inner, instance, inner,
1110 );
1111 writeln!(out, " return ptr.release();");
1112 writeln!(out, "}}");
1113 writeln!(
1114 out,
David Tolnay8c730492020-03-13 01:29:06 -07001115 "void cxxbridge02$unique_ptr${}$drop(::std::unique_ptr<{}> *ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -04001116 instance, inner,
1117 );
1118 writeln!(out, " ptr->~unique_ptr();");
1119 writeln!(out, "}}");
David Tolnay8c730492020-03-13 01:29:06 -07001120 writeln!(out, "#endif // CXXBRIDGE02_UNIQUE_PTR_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -04001121}
Myron Ahneba35cf2020-02-05 19:41:51 +07001122
1123fn write_vector(out: &mut OutFile, ident: &Ident) {
1124 let mut inner = String::new();
1125 // Do not apply namespace to built-in type
1126 let is_user_type = Atom::from(ident).is_none();
1127 if is_user_type {
1128 for name in &out.namespace {
1129 inner += name;
1130 inner += "::";
1131 }
1132 }
1133 let mut instance = inner.clone();
1134 if let Some(ti) = Atom::from(ident) {
1135 inner += ti.to_cxx();
1136 } else {
1137 inner += &ident.to_string();
1138 };
1139 instance += &ident.to_string();
1140 let instance = instance.replace("::", "$");
1141
1142 writeln!(out, "#ifndef CXXBRIDGE02_vector_{}", instance);
1143 writeln!(out, "#define CXXBRIDGE02_vector_{}", instance);
1144 writeln!(
1145 out,
1146 "size_t cxxbridge02$std$vector${}$length(const std::vector<{}> &s) noexcept {{",
1147 instance, inner,
1148 );
1149 writeln!(out, " return s.size();");
1150 writeln!(out, "}}");
1151
1152 writeln!(
1153 out,
1154 "void cxxbridge02$std$vector${}$push_back(std::vector<{}> &s, const {} &item) noexcept {{",
1155 instance, inner, inner
1156 );
1157 writeln!(out, " s.push_back(item);");
1158 writeln!(out, "}}");
1159
1160 writeln!(
1161 out,
1162 "const {} *cxxbridge02$std$vector${}$get_unchecked(const std::vector<{}> &s, size_t pos) noexcept {{",
1163 inner, instance, inner,
1164 );
1165 writeln!(out, " return &s[pos];");
1166 writeln!(out, "}}");
1167 writeln!(out, "#endif // CXXBRIDGE02_vector_{}", instance);
1168}