nativeview_codegen/targets/c_cpp/
import_rn.rs1use crate::writer::CodeWriter;
5
6use crate::naming::{cpp_ident, escape_c_like_string, sanitize_single_line_comment, to_pascal_case};
7use crate::schema::export::{PropType, TurboModuleSpec};
8
9pub(crate) fn emit_turbomodule_cpp(spec: &TurboModuleSpec) -> String {
10 let pascal = to_pascal_case(&spec.module_name);
11 let mut out = CodeWriter::with_capacity(2048);
12
13 writeln!(out, "#pragma once");
14 writeln!(out);
15 writeln!(
16 out,
17 "// @generated by nativeview-codegen (`import_rn`) from React Native TurboModule `{}`.",
18 sanitize_single_line_comment(&spec.module_name)
19 );
20 writeln!(out);
21 writeln!(out, "#include <cstdint>");
22 writeln!(out, "#include <optional>");
23 writeln!(out, "#include <string>");
24 writeln!(out, "#include <string_view>");
25 writeln!(out, "#include <vector>");
26 writeln!(out);
27 writeln!(out, "namespace nv::generated {{");
28 writeln!(out);
29 writeln!(
30 out,
31 "inline constexpr std::string_view k{pascal}ModuleName = \"{}\";",
32 escape_c_like_string(&spec.module_name)
33 );
34 writeln!(out);
35 writeln!(out, "class {pascal}TurboModuleHost {{");
36 writeln!(out, " public:");
37 writeln!(out, " virtual ~{pascal}TurboModuleHost() = default;");
38 for method in &spec.methods {
39 let mname = cpp_ident(&method.name);
40 let ret = cpp_tm_type(&method.return_type);
41 let mut params = CodeWriter::new();
42 for (i, p) in method.params.iter().enumerate() {
43 if i > 0 {
44 params.push_str(", ");
45 }
46 let pty = cpp_tm_type(&p.param_type);
47 let pname = cpp_ident(&p.name);
48 if p.optional {
49 write!(params, "std::optional<{pty}> {pname}");
50 } else {
51 write!(params, "{pty} {pname}");
52 }
53 }
54 writeln!(out, " virtual {ret} {mname}({params}) = 0;");
55 }
56 writeln!(out, "}};");
57 writeln!(out);
58 writeln!(out, "}} // namespace nv::generated");
59 out.into_string()
60}
61
62fn cpp_tm_type(ty: &PropType) -> String {
63 match ty {
64 PropType::Void => "void".to_owned(),
65 PropType::Bool => "bool".to_owned(),
66 PropType::Int32 => "int32_t".to_owned(),
67 PropType::Float => "float".to_owned(),
68 PropType::Double => "double".to_owned(),
69 PropType::String | PropType::StringEnum { .. } | PropType::Mixed => {
70 "std::string".to_owned()
71 }
72 PropType::IntEnum { .. } => "int32_t".to_owned(),
73 PropType::Array { item } => format!("std::vector<{}>", cpp_tm_type(item)),
74 PropType::Promise { inner } => cpp_tm_type(inner),
75 _ => "std::string".to_owned(),
76 }
77}