blob: 81f26b818cfaef237782a67009f5614a8f4b3115 [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);
311 }
312 if indirect_return {
313 if !efn.args.is_empty() {
314 write!(out, ", ");
315 }
316 write!(out, "reinterpret_cast<");
317 write_return_type(out, &efn.ret);
318 write!(out, "*>(return$)");
319 }
320 writeln!(out, ");");
321 if indirect_return {
322 write!(out, " return ");
323 write_type(out, efn.ret.as_ref().unwrap());
324 write!(out, "(*reinterpret_cast<");
325 write_return_type(out, &efn.ret);
326 writeln!(out, "*>(return$));");
327 }
328 writeln!(out, "}}");
329 }
330}
331
332fn write_return_type(out: &mut OutFile, ty: &Option<Type>) {
333 match ty {
334 None => write!(out, "void "),
335 Some(ty) => write_type_space(out, ty),
336 }
337}
338
339fn write_extern_return_type(out: &mut OutFile, ty: &Option<Type>, types: &Types) {
340 match ty {
341 Some(Type::RustBox(ty)) | Some(Type::UniquePtr(ty)) => {
342 write_type_space(out, &ty.inner);
343 write!(out, "*");
344 }
345 Some(Type::Str(_)) => write!(out, "cxxbridge::RustStr::Repr "),
346 Some(ty) if types.needs_indirect_abi(ty) => write!(out, "void "),
347 _ => write_return_type(out, ty),
348 }
349}
350
351fn write_extern_arg(out: &mut OutFile, arg: &Var, types: &Types) {
352 match &arg.ty {
353 Type::RustBox(ty) | Type::UniquePtr(ty) => {
354 write_type_space(out, &ty.inner);
355 write!(out, "*");
356 }
357 Type::Str(_) => write!(out, "cxxbridge::RustStr::Repr "),
358 _ => write_type_space(out, &arg.ty),
359 }
360 if types.needs_indirect_abi(&arg.ty) {
361 write!(out, "*");
362 }
363 write!(out, "{}", arg.ident);
364}
365
366fn write_type(out: &mut OutFile, ty: &Type) {
367 match ty {
368 Type::Ident(ident) => match Atom::from(ident) {
369 Some(Bool) => write!(out, "bool"),
370 Some(U8) => write!(out, "uint8_t"),
371 Some(U16) => write!(out, "uint16_t"),
372 Some(U32) => write!(out, "uint32_t"),
373 Some(U64) => write!(out, "uint64_t"),
374 Some(Usize) => write!(out, "size_t"),
375 Some(I8) => write!(out, "int8_t"),
376 Some(I16) => write!(out, "int16_t"),
377 Some(I32) => write!(out, "int32_t"),
378 Some(I64) => write!(out, "int64_t"),
379 Some(Isize) => write!(out, "ssize_t"),
380 Some(CxxString) => write!(out, "std::string"),
381 Some(RustString) => write!(out, "cxxbridge::RustString"),
382 None => write!(out, "{}", ident),
383 },
384 Type::RustBox(ty) => {
385 write!(out, "cxxbridge::RustBox<");
386 write_type(out, &ty.inner);
387 write!(out, ">");
388 }
389 Type::UniquePtr(ptr) => {
390 write!(out, "std::unique_ptr<");
391 write_type(out, &ptr.inner);
392 write!(out, ">");
393 }
394 Type::Ref(r) => {
395 if r.mutability.is_none() {
396 write!(out, "const ");
397 }
398 write_type(out, &r.inner);
399 write!(out, " &");
400 }
401 Type::Str(_) => {
402 write!(out, "cxxbridge::RustStr");
403 }
404 }
405}
406
407fn write_type_space(out: &mut OutFile, ty: &Type) {
408 write_type(out, ty);
409 match ty {
410 Type::Ident(_) | Type::RustBox(_) | Type::UniquePtr(_) | Type::Str(_) => write!(out, " "),
411 Type::Ref(_) => {}
412 }
413}
414
415fn write_generic_instantiations(out: &mut OutFile, types: &Types) {
416 fn allow_unique_ptr(ident: &Ident) -> bool {
417 Atom::from(ident).is_none()
418 }
419
420 out.begin_block("extern \"C\"");
421 for ty in types {
422 if let Type::RustBox(ty) = ty {
423 if let Type::Ident(inner) = &ty.inner {
424 out.next_section();
425 write_rust_box_extern(out, inner);
426 }
427 } else if let Type::UniquePtr(ptr) = ty {
428 if let Type::Ident(inner) = &ptr.inner {
429 if allow_unique_ptr(inner) {
430 out.next_section();
431 write_unique_ptr(out, inner);
432 }
433 }
434 }
435 }
436 out.end_block();
437
David Tolnaye43b7372020-01-08 08:46:20 -0800438 out.begin_block("namespace cxxbridge01");
David Tolnay7db73692019-10-20 14:51:12 -0400439 for ty in types {
440 if let Type::RustBox(ty) = ty {
441 if let Type::Ident(inner) = &ty.inner {
442 write_rust_box_impl(out, inner);
443 }
444 }
445 }
446 out.end_block();
447}
448
449fn write_rust_box_extern(out: &mut OutFile, ident: &Ident) {
450 let mut inner = String::new();
451 for name in &out.namespace {
452 inner += name;
453 inner += "::";
454 }
455 inner += &ident.to_string();
456 let instance = inner.replace("::", "$");
457
David Tolnaye43b7372020-01-08 08:46:20 -0800458 writeln!(out, "#ifndef CXXBRIDGE01_RUST_BOX_{}", instance);
459 writeln!(out, "#define CXXBRIDGE01_RUST_BOX_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400460 writeln!(
461 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800462 "void cxxbridge01$rust_box${}$uninit(cxxbridge::RustBox<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400463 instance, inner,
464 );
465 writeln!(
466 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800467 "void cxxbridge01$rust_box${}$set_raw(cxxbridge::RustBox<{}> *ptr, {} *raw) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400468 instance, inner, inner
469 );
470 writeln!(
471 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800472 "void cxxbridge01$rust_box${}$drop(cxxbridge::RustBox<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400473 instance, inner,
474 );
475 writeln!(
476 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800477 "const {} *cxxbridge01$rust_box${}$deref(const cxxbridge::RustBox<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400478 inner, instance, inner,
479 );
480 writeln!(
481 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800482 "{} *cxxbridge01$rust_box${}$deref_mut(cxxbridge::RustBox<{}> *ptr) noexcept;",
David Tolnay7db73692019-10-20 14:51:12 -0400483 inner, instance, inner,
484 );
David Tolnaye43b7372020-01-08 08:46:20 -0800485 writeln!(out, "#endif // CXXBRIDGE01_RUST_BOX_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400486}
487
488fn write_rust_box_impl(out: &mut OutFile, ident: &Ident) {
489 let mut inner = String::new();
490 for name in &out.namespace {
491 inner += name;
492 inner += "::";
493 }
494 inner += &ident.to_string();
495 let instance = inner.replace("::", "$");
496
497 writeln!(out, "template <>");
498 writeln!(out, "void RustBox<{}>::uninit() noexcept {{", inner);
499 writeln!(
500 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800501 " return cxxbridge01$rust_box${}$uninit(this);",
David Tolnay7db73692019-10-20 14:51:12 -0400502 instance
503 );
504 writeln!(out, "}}");
505
506 writeln!(out, "template <>");
507 writeln!(
508 out,
509 "void RustBox<{}>::set_raw({} *raw) noexcept {{",
510 inner, inner,
511 );
512 writeln!(
513 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800514 " return cxxbridge01$rust_box${}$set_raw(this, raw);",
David Tolnay7db73692019-10-20 14:51:12 -0400515 instance
516 );
517 writeln!(out, "}}");
518
519 writeln!(out, "template <>");
520 writeln!(out, "void RustBox<{}>::drop() noexcept {{", inner);
521 writeln!(
522 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800523 " return cxxbridge01$rust_box${}$drop(this);",
David Tolnay7db73692019-10-20 14:51:12 -0400524 instance
525 );
526 writeln!(out, "}}");
527
528 writeln!(out, "template <>");
529 writeln!(
530 out,
531 "const {} *RustBox<{}>::deref() const noexcept {{",
532 inner, inner,
533 );
534 writeln!(
535 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800536 " return cxxbridge01$rust_box${}$deref(this);",
David Tolnay7db73692019-10-20 14:51:12 -0400537 instance
538 );
539 writeln!(out, "}}");
540
541 writeln!(out, "template <>");
542 writeln!(
543 out,
544 "{} *RustBox<{}>::deref_mut() noexcept {{",
545 inner, inner,
546 );
547 writeln!(
548 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800549 " return cxxbridge01$rust_box${}$deref_mut(this);",
David Tolnay7db73692019-10-20 14:51:12 -0400550 instance
551 );
552 writeln!(out, "}}");
553}
554
555fn write_unique_ptr(out: &mut OutFile, ident: &Ident) {
556 let mut inner = String::new();
557 for name in &out.namespace {
558 inner += name;
559 inner += "::";
560 }
561 inner += &ident.to_string();
562 let instance = inner.replace("::", "$");
563
David Tolnaye43b7372020-01-08 08:46:20 -0800564 writeln!(out, "#ifndef CXXBRIDGE01_UNIQUE_PTR_{}", instance);
565 writeln!(out, "#define CXXBRIDGE01_UNIQUE_PTR_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400566 writeln!(
567 out,
568 "static_assert(sizeof(std::unique_ptr<{}>) == sizeof(void *), \"\");",
569 inner,
570 );
571 writeln!(
572 out,
573 "static_assert(alignof(std::unique_ptr<{}>) == alignof(void *), \"\");",
574 inner,
575 );
576 writeln!(
577 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800578 "void cxxbridge01$unique_ptr${}$null(std::unique_ptr<{}> *ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400579 instance, inner,
580 );
581 writeln!(out, " new (ptr) std::unique_ptr<{}>();", inner);
582 writeln!(out, "}}");
583 writeln!(
584 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800585 "void cxxbridge01$unique_ptr${}$new(std::unique_ptr<{}> *ptr, {} *value) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400586 instance, inner, inner,
587 );
588 writeln!(
589 out,
590 " new (ptr) std::unique_ptr<{}>(new {}(std::move(*value)));",
591 inner, inner,
592 );
593 writeln!(out, "}}");
594 writeln!(
595 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800596 "void cxxbridge01$unique_ptr${}$raw(std::unique_ptr<{}> *ptr, {} *raw) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400597 instance, inner, inner,
598 );
599 writeln!(out, " new (ptr) std::unique_ptr<{}>(raw);", inner);
600 writeln!(out, "}}");
601 writeln!(
602 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800603 "const {} *cxxbridge01$unique_ptr${}$get(const std::unique_ptr<{}>& ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400604 inner, instance, inner,
605 );
606 writeln!(out, " return ptr.get();");
607 writeln!(out, "}}");
608 writeln!(
609 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800610 "{} *cxxbridge01$unique_ptr${}$release(std::unique_ptr<{}>& ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400611 inner, instance, inner,
612 );
613 writeln!(out, " return ptr.release();");
614 writeln!(out, "}}");
615 writeln!(
616 out,
David Tolnaye43b7372020-01-08 08:46:20 -0800617 "void cxxbridge01$unique_ptr${}$drop(std::unique_ptr<{}> *ptr) noexcept {{",
David Tolnay7db73692019-10-20 14:51:12 -0400618 instance, inner,
619 );
620 writeln!(out, " ptr->~unique_ptr();");
621 writeln!(out, "}}");
David Tolnaye43b7372020-01-08 08:46:20 -0800622 writeln!(out, "#endif // CXXBRIDGE01_UNIQUE_PTR_{}", instance);
David Tolnay7db73692019-10-20 14:51:12 -0400623}