blob: eb114702a6fd92b8dfd9bf22eaa095296faeb870 [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use crate::gen::include;
2use crate::gen::out::OutFile;
3use crate::syntax::atom::Atom::{self, *};
4use crate::syntax::{Api, ExternFn, Struct, Type, Types, Var};
5use proc_macro2::Ident;
6
7pub(super) fn gen(namespace: Vec<String>, apis: &[Api], types: &Types, header: bool) -> OutFile {
8 let mut out_file = OutFile::new(namespace.clone(), header);
9 let out = &mut out_file;
10
11 if header {
12 writeln!(out, "#pragma once");
13 }
14
15 for api in apis {
16 if let Api::Include(include) = api {
17 writeln!(out, "#include \"{}\"", include.value().escape_default());
18 }
19 }
20
21 write_includes(out, types);
22 write_include_cxxbridge(out, types);
23
24 if !header {
25 out.next_section();
26 write_namespace_alias(out, types);
27 }
28
29 out.next_section();
30 for name in &namespace {
31 writeln!(out, "namespace {} {{", name);
32 }
33
34 if header {
35 out.next_section();
36 write_namespace_alias(out, types);
37 }
38
39 out.next_section();
40 for api in apis {
41 match api {
42 Api::Struct(strct) => write_struct_decl(out, &strct.ident),
43 Api::CxxType(ety) | Api::RustType(ety) => write_struct_decl(out, &ety.ident),
44 _ => {}
45 }
46 }
47
48 for api in apis {
49 if let Api::Struct(strct) = api {
50 out.next_section();
51 write_struct(out, strct);
52 }
53 }
54
55 if !header {
56 out.begin_block("extern \"C\"");
57 for api in apis {
58 let (efn, write): (_, fn(_, _, _)) = match api {
59 Api::CxxFunction(efn) => (efn, write_cxx_function_shim),
60 Api::RustFunction(efn) => (efn, write_rust_function_decl),
61 _ => continue,
62 };
63 out.next_section();
64 write(out, efn, types);
65 }
66 out.end_block();
67 }
68
69 for api in apis {
70 if let Api::RustFunction(efn) = api {
71 out.next_section();
72 write_rust_function_shim(out, efn, types);
73 }
74 }
75
76 out.next_section();
77 for name in namespace.iter().rev() {
78 writeln!(out, "}} // namespace {}", name);
79 }
80
81 if !header {
82 out.next_section();
83 write_generic_instantiations(out, types);
84 }
85
86 out_file
87}
88
89fn write_includes(out: &mut OutFile, types: &Types) {
90 let mut has_int = false;
91 let mut has_unique_ptr = false;
92 let mut has_string = false;
93
94 for ty in types {
95 match ty {
96 Type::Ident(ident) => match Atom::from(ident) {
97 Some(U8) | Some(U16) | Some(U32) | Some(U64) | Some(Usize) | Some(I8)
98 | Some(I16) | Some(I32) | Some(I64) | Some(Isize) => has_int = true,
99 Some(CxxString) => has_string = true,
100 Some(Bool) | Some(RustString) | None => {}
101 },
102 Type::UniquePtr(_) => has_unique_ptr = true,
103 _ => {}
104 }
105 }
106
107 if has_int {
108 writeln!(out, "#include <cstdint>");
109 }
110 if has_unique_ptr {
111 writeln!(out, "#include <memory>");
112 }
113 if has_string {
114 writeln!(out, "#include <string>");
115 }
116}
117
118fn write_include_cxxbridge(out: &mut OutFile, types: &Types) {
119 let mut needs_rust_box = false;
120 for ty in types {
121 if let Type::RustBox(_) = ty {
122 needs_rust_box = true;
123 break;
124 }
125 }
126
David Tolnaye43b7372020-01-08 08:46:20 -0800127 out.begin_block("namespace cxxbridge01");
David Tolnay7db73692019-10-20 14:51:12 -0400128 if needs_rust_box {
129 writeln!(out, "// #include \"cxxbridge.h\"");
David Tolnaye43b7372020-01-08 08:46:20 -0800130 for line in include::get("CXXBRIDGE01_RUST_BOX").lines() {
David Tolnay7db73692019-10-20 14:51:12 -0400131 if !line.trim_start().starts_with("//") {
132 writeln!(out, "{}", line);
133 }
134 }
135 }
136 out.end_block();
137}
138
139fn write_namespace_alias(out: &mut OutFile, types: &Types) {
140 let mut needs_namespace_alias = false;
141 for ty in types {
142 if let Type::RustBox(_) = ty {
143 needs_namespace_alias = true;
144 break;
145 }
146 }
147
148 if needs_namespace_alias {
David Tolnaye43b7372020-01-08 08:46:20 -0800149 writeln!(out, "namespace cxxbridge = cxxbridge01;");
David Tolnay7db73692019-10-20 14:51:12 -0400150 }
151}
152
153fn write_struct(out: &mut OutFile, strct: &Struct) {
154 for line in strct.doc.to_string().lines() {
155 writeln!(out, "//{}", line);
156 }
157 writeln!(out, "struct {} final {{", strct.ident);
158 for field in &strct.fields {
159 write!(out, " ");
160 write_type_space(out, &field.ty);
161 writeln!(out, "{};", field.ident);
162 }
163 writeln!(out, "}};");
164}
165
166fn write_struct_decl(out: &mut OutFile, ident: &Ident) {
167 writeln!(out, "struct {};", ident);
168}
169
170fn write_cxx_function_shim(out: &mut OutFile, efn: &ExternFn, types: &Types) {
171 let indirect_return = efn
172 .ret
173 .as_ref()
174 .map_or(false, |ret| types.needs_indirect_abi(ret));
175 write_extern_return_type(out, &efn.ret, types);
176 for name in out.namespace.clone() {
177 write!(out, "{}$", name);
178 }
David Tolnaye43b7372020-01-08 08:46:20 -0800179 write!(out, "cxxbridge01${}(", efn.ident);
David Tolnay7db73692019-10-20 14:51:12 -0400180 for (i, arg) in efn.args.iter().enumerate() {
181 if i > 0 {
182 write!(out, ", ");
183 }
184 write_extern_arg(out, arg, types);
185 }
186 if indirect_return {
187 if !efn.args.is_empty() {
188 write!(out, ", ");
189 }
190 write_return_type(out, &efn.ret);
191 write!(out, "*return$");
192 }
193 writeln!(out, ") noexcept {{");
194 write!(out, " ");
195 write_return_type(out, &efn.ret);
196 write!(out, "(*{}$)(", efn.ident);
197 for (i, arg) in efn.args.iter().enumerate() {
198 if i > 0 {
199 write!(out, ", ");
200 }
201 write_type(out, &arg.ty);
202 }
203 writeln!(out, ") = {};", efn.ident);
204 write!(out, " ");
205 if indirect_return {
206 write!(out, "new (return$) ");
207 write_type(out, efn.ret.as_ref().unwrap());
208 write!(out, "(");
209 } else if efn.ret.is_some() {
210 write!(out, "return ");
211 }
212 write!(out, "{}$(", efn.ident);
213 for (i, arg) in efn.args.iter().enumerate() {
214 if i > 0 {
215 write!(out, ", ");
216 }
217 if let Type::RustBox(_) = &arg.ty {
218 write_type(out, &arg.ty);
219 write!(out, "::from_raw({})", arg.ident);
220 } else if let Type::UniquePtr(_) = &arg.ty {
221 write_type(out, &arg.ty);
222 write!(out, "({})", arg.ident);
223 } else if types.needs_indirect_abi(&arg.ty) {
224 write!(out, "std::move(*{})", arg.ident);
225 } else {
226 write!(out, "{}", arg.ident);
227 }
228 }
229 write!(out, ")");
230 match &efn.ret {
231 Some(Type::RustBox(_)) => write!(out, ".into_raw()"),
232 Some(Type::UniquePtr(_)) => write!(out, ".release()"),
233 _ => {}
234 }
235 if indirect_return {
236 write!(out, ")");
237 }
238 writeln!(out, ";");
239 writeln!(out, "}}");
240}
241
242fn write_rust_function_decl(out: &mut OutFile, efn: &ExternFn, types: &Types) {
243 write_extern_return_type(out, &efn.ret, types);
244 for name in out.namespace.clone() {
245 write!(out, "{}$", name);
246 }
David Tolnaye43b7372020-01-08 08:46:20 -0800247 write!(out, "cxxbridge01${}(", efn.ident);
David Tolnay7db73692019-10-20 14:51:12 -0400248 for (i, arg) in efn.args.iter().enumerate() {
249 if i > 0 {
250 write!(out, ", ");
251 }
252 write_extern_arg(out, arg, types);
253 }
254 if efn
255 .ret
256 .as_ref()
257 .map_or(false, |ret| types.needs_indirect_abi(ret))
258 {
259 if !efn.args.is_empty() {
260 write!(out, ", ");
261 }
262 write_return_type(out, &efn.ret);
263 write!(out, "*return$");
264 }
265 writeln!(out, ") noexcept;");
266}
267
268fn write_rust_function_shim(out: &mut OutFile, efn: &ExternFn, types: &Types) {
269 let indirect_return = efn
270 .ret
271 .as_ref()
272 .map_or(false, |ret| types.needs_indirect_abi(ret));
273 for line in efn.doc.to_string().lines() {
274 writeln!(out, "//{}", line);
275 }
276 write_return_type(out, &efn.ret);
277 write!(out, "{}(", efn.ident);
278 for (i, arg) in efn.args.iter().enumerate() {
279 if i > 0 {
280 write!(out, ", ");
281 }
282 write_type_space(out, &arg.ty);
283 write!(out, "{}", arg.ident);
284 }
285 write!(out, ") noexcept");
286 if out.header {
287 writeln!(out, ";");
288 } else {
289 writeln!(out, " {{");
290 write!(out, " ");
291 if indirect_return {
292 write!(out, "char return$[sizeof(");
293 write_type(out, efn.ret.as_ref().unwrap());
294 writeln!(out, ")];");
295 write!(out, " ");
296 } else if efn.ret.is_some() {
297 write!(out, "return ");
298 }
299 for name in out.namespace.clone() {
300 write!(out, "{}$", name);
301 }
David Tolnaye43b7372020-01-08 08:46:20 -0800302 write!(out, "cxxbridge01${}(", efn.ident);
David Tolnay7db73692019-10-20 14:51:12 -0400303 for (i, arg) in efn.args.iter().enumerate() {
304 if i > 0 {
305 write!(out, ", ");
306 }
307 if types.needs_indirect_abi(&arg.ty) {
308 write!(out, "&");
309 }
310 write!(out, "{}", arg.ident);
David Tolnay17955e22020-01-20 17:58:24 -0800311 match arg.ty {
312 Type::RustBox(_) => write!(out, ".into_raw()"),
313 Type::UniquePtr(_) => write!(out, ".release()"),
314 _ => {}
315 }
David Tolnay7db73692019-10-20 14:51:12 -0400316 }
317 if indirect_return {
318 if !efn.args.is_empty() {
319 write!(out, ", ");
320 }
321 write!(out, "reinterpret_cast<");
322 write_return_type(out, &efn.ret);
323 write!(out, "*>(return$)");
324 }
325 writeln!(out, ");");
326 if indirect_return {
327 write!(out, " return ");
328 write_type(out, efn.ret.as_ref().unwrap());
329 write!(out, "(*reinterpret_cast<");
330 write_return_type(out, &efn.ret);
331 writeln!(out, "*>(return$));");
332 }
333 writeln!(out, "}}");
334 }
335}
336
337fn write_return_type(out: &mut OutFile, ty: &Option<Type>) {
338 match ty {
339 None => write!(out, "void "),
340 Some(ty) => write_type_space(out, ty),
341 }
342}
343
344fn write_extern_return_type(out: &mut OutFile, ty: &Option<Type>, types: &Types) {
345 match ty {
346 Some(Type::RustBox(ty)) | Some(Type::UniquePtr(ty)) => {
347 write_type_space(out, &ty.inner);
348 write!(out, "*");
349 }
350 Some(Type::Str(_)) => write!(out, "cxxbridge::RustStr::Repr "),
351 Some(ty) if types.needs_indirect_abi(ty) => write!(out, "void "),
352 _ => write_return_type(out, ty),
353 }
354}
355
356fn write_extern_arg(out: &mut OutFile, arg: &Var, types: &Types) {
357 match &arg.ty {
358 Type::RustBox(ty) | Type::UniquePtr(ty) => {
359 write_type_space(out, &ty.inner);
360 write!(out, "*");
361 }
362 Type::Str(_) => write!(out, "cxxbridge::RustStr::Repr "),
363 _ => write_type_space(out, &arg.ty),
364 }
365 if types.needs_indirect_abi(&arg.ty) {
366 write!(out, "*");
367 }
368 write!(out, "{}", arg.ident);
369}
370
371fn write_type(out: &mut OutFile, ty: &Type) {
372 match ty {
373 Type::Ident(ident) => match Atom::from(ident) {
374 Some(Bool) => write!(out, "bool"),
375 Some(U8) => write!(out, "uint8_t"),
376 Some(U16) => write!(out, "uint16_t"),
377 Some(U32) => write!(out, "uint32_t"),
378 Some(U64) => write!(out, "uint64_t"),
379 Some(Usize) => write!(out, "size_t"),
380 Some(I8) => write!(out, "int8_t"),
381 Some(I16) => write!(out, "int16_t"),
382 Some(I32) => write!(out, "int32_t"),
383 Some(I64) => write!(out, "int64_t"),
384 Some(Isize) => write!(out, "ssize_t"),
385 Some(CxxString) => write!(out, "std::string"),
386 Some(RustString) => write!(out, "cxxbridge::RustString"),
387 None => write!(out, "{}", ident),
388 },
389 Type::RustBox(ty) => {
390 write!(out, "cxxbridge::RustBox<");
391 write_type(out, &ty.inner);
392 write!(out, ">");
393 }
394 Type::UniquePtr(ptr) => {
395 write!(out, "std::unique_ptr<");
396 write_type(out, &ptr.inner);
397 write!(out, ">");
398 }
399 Type::Ref(r) => {
400 if r.mutability.is_none() {
401 write!(out, "const ");
402 }
403 write_type(out, &r.inner);
404 write!(out, " &");
405 }
406 Type::Str(_) => {
407 write!(out, "cxxbridge::RustStr");
408 }
409 }
410}
411
412fn write_type_space(out: &mut OutFile, ty: &Type) {
413 write_type(out, ty);
414 match ty {
415 Type::Ident(_) | Type::RustBox(_) | Type::UniquePtr(_) | Type::Str(_) => write!(out, " "),
416 Type::Ref(_) => {}
417 }
418}
419
420fn write_generic_instantiations(out: &mut OutFile, types: &Types) {
421 fn allow_unique_ptr(ident: &Ident) -> bool {
422 Atom::from(ident).is_none()
423 }
424
425 out.begin_block("extern \"C\"");
426 for ty in types {
427 if let Type::RustBox(ty) = ty {
428 if let Type::Ident(inner) = &ty.inner {
429 out.next_section();
430 write_rust_box_extern(out, inner);
431 }
432 } else if let Type::UniquePtr(ptr) = ty {
433 if let Type::Ident(inner) = &ptr.inner {
434 if allow_unique_ptr(inner) {
435 out.next_section();
436 write_unique_ptr(out, inner);
437 }
438 }
439 }
440 }
441 out.end_block();
442
David Tolnaye43b7372020-01-08 08:46:20 -0800443 out.begin_block("namespace cxxbridge01");
David Tolnay7db73692019-10-20 14:51:12 -0400444 for ty in types {
445 if let Type::RustBox(ty) = ty {
446 if let Type::Ident(inner) = &ty.inner {
447 write_rust_box_impl(out, inner);
448 }
449 }
450 }
451 out.end_block();
452}
453
454fn write_rust_box_extern(out: &mut OutFile, ident: &Ident) {
455 let mut inner = String::new();
456 for name in &out.namespace {
457 inner += name;
458 inner += "::";
459 }
460 inner += &ident.to_string();
461 let instance = inner.replace("::", "$");
462
David Tolnaye43b7372020-01-08 08:46:20 -0800463 writeln!(out, "#ifndef CXXBRIDGE01_RUST_BOX_{}", instance);
464 writeln!(out, "#define CXXBRIDGE01_RUST_BOX_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400465 writeln!(
466 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800467 "void cxxbridge01$rust_box${}$uninit(cxxbridge::RustBox<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400468 instance, inner,
469 );
470 writeln!(
471 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800472 "void cxxbridge01$rust_box${}$set_raw(cxxbridge::RustBox<{}> *ptr, {} *raw) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400473 instance, inner, inner
474 );
475 writeln!(
476 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800477 "void cxxbridge01$rust_box${}$drop(cxxbridge::RustBox<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400478 instance, inner,
479 );
480 writeln!(
481 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800482 "const {} *cxxbridge01$rust_box${}$deref(const cxxbridge::RustBox<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400483 inner, instance, inner,
484 );
485 writeln!(
486 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800487 "{} *cxxbridge01$rust_box${}$deref_mut(cxxbridge::RustBox<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400488 inner, instance, inner,
489 );
David Tolnaye43b7372020-01-08 08:46:20 -0800490 writeln!(out, "#endif // CXXBRIDGE01_RUST_BOX_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400491}
492
493fn write_rust_box_impl(out: &mut OutFile, ident: &Ident) {
494 let mut inner = String::new();
495 for name in &out.namespace {
496 inner += name;
497 inner += "::";
498 }
499 inner += &ident.to_string();
500 let instance = inner.replace("::", "$");
501
502 writeln!(out, "template <>");
503 writeln!(out, "void RustBox<{}>::uninit() noexcept {{", inner);
504 writeln!(
505 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800506 " return cxxbridge01$rust_box${}$uninit(this);",
David Tolnay7db73692019-10-20 14:51:12 -0400507 instance
508 );
509 writeln!(out, "}}");
510
511 writeln!(out, "template <>");
512 writeln!(
513 out,
514 "void RustBox<{}>::set_raw({} *raw) noexcept {{",
515 inner, inner,
516 );
517 writeln!(
518 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800519 " return cxxbridge01$rust_box${}$set_raw(this, raw);",
David Tolnay7db73692019-10-20 14:51:12 -0400520 instance
521 );
522 writeln!(out, "}}");
523
524 writeln!(out, "template <>");
525 writeln!(out, "void RustBox<{}>::drop() noexcept {{", inner);
526 writeln!(
527 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800528 " return cxxbridge01$rust_box${}$drop(this);",
David Tolnay7db73692019-10-20 14:51:12 -0400529 instance
530 );
531 writeln!(out, "}}");
532
533 writeln!(out, "template <>");
534 writeln!(
535 out,
536 "const {} *RustBox<{}>::deref() const noexcept {{",
537 inner, inner,
538 );
539 writeln!(
540 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800541 " return cxxbridge01$rust_box${}$deref(this);",
David Tolnay7db73692019-10-20 14:51:12 -0400542 instance
543 );
544 writeln!(out, "}}");
545
546 writeln!(out, "template <>");
547 writeln!(
548 out,
549 "{} *RustBox<{}>::deref_mut() noexcept {{",
550 inner, inner,
551 );
552 writeln!(
553 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800554 " return cxxbridge01$rust_box${}$deref_mut(this);",
David Tolnay7db73692019-10-20 14:51:12 -0400555 instance
556 );
557 writeln!(out, "}}");
558}
559
560fn write_unique_ptr(out: &mut OutFile, ident: &Ident) {
561 let mut inner = String::new();
562 for name in &out.namespace {
563 inner += name;
564 inner += "::";
565 }
566 inner += &ident.to_string();
567 let instance = inner.replace("::", "$");
568
David Tolnaye43b7372020-01-08 08:46:20 -0800569 writeln!(out, "#ifndef CXXBRIDGE01_UNIQUE_PTR_{}", instance);
570 writeln!(out, "#define CXXBRIDGE01_UNIQUE_PTR_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400571 writeln!(
572 out,
573 "static_assert(sizeof(std::unique_ptr<{}>) == sizeof(void *), \"\");",
574 inner,
575 );
576 writeln!(
577 out,
578 "static_assert(alignof(std::unique_ptr<{}>) == alignof(void *), \"\");",
579 inner,
580 );
581 writeln!(
582 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800583 "void cxxbridge01$unique_ptr${}$null(std::unique_ptr<{}> *ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400584 instance, inner,
585 );
586 writeln!(out, " new (ptr) std::unique_ptr<{}>();", inner);
587 writeln!(out, "}}");
588 writeln!(
589 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800590 "void cxxbridge01$unique_ptr${}$new(std::unique_ptr<{}> *ptr, {} *value) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400591 instance, inner, inner,
592 );
593 writeln!(
594 out,
595 " new (ptr) std::unique_ptr<{}>(new {}(std::move(*value)));",
596 inner, inner,
597 );
598 writeln!(out, "}}");
599 writeln!(
600 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800601 "void cxxbridge01$unique_ptr${}$raw(std::unique_ptr<{}> *ptr, {} *raw) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400602 instance, inner, inner,
603 );
604 writeln!(out, " new (ptr) std::unique_ptr<{}>(raw);", inner);
605 writeln!(out, "}}");
606 writeln!(
607 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800608 "const {} *cxxbridge01$unique_ptr${}$get(const std::unique_ptr<{}>& ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400609 inner, instance, inner,
610 );
611 writeln!(out, " return ptr.get();");
612 writeln!(out, "}}");
613 writeln!(
614 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800615 "{} *cxxbridge01$unique_ptr${}$release(std::unique_ptr<{}>& ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400616 inner, instance, inner,
617 );
618 writeln!(out, " return ptr.release();");
619 writeln!(out, "}}");
620 writeln!(
621 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800622 "void cxxbridge01$unique_ptr${}$drop(std::unique_ptr<{}> *ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400623 instance, inner,
624 );
625 writeln!(out, " ptr->~unique_ptr();");
626 writeln!(out, "}}");
David Tolnaye43b7372020-01-08 08:46:20 -0800627 writeln!(out, "#endif // CXXBRIDGE01_UNIQUE_PTR_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400628}