diff --git a/.bazelrc b/.bazelrc index d3ab34b..0ff7adb 100644 --- a/.bazelrc +++ b/.bazelrc @@ -10,6 +10,11 @@ build:asan --linkopt=-fsanitize=address # phaser_python_test loads an instrumented extension into the uninstrumented # CPython interpreter. ASan aborts unless its runtime is the first library # loaded, which a dlopen of the extension is not. Tag that test no-asan. +# phaser_rust_test is linked by rustc with -nodefaultlibs, which does not pull +# in the ASan runtime. Its rust_test platform transition also ignores +# test_tag_filters, so the test is marked incompatible when --define=asan=1 +# (set here) rather than filtered by tag. The C API cc_test still runs. +build:asan --define=asan=1 test:asan --test_tag_filters=-no-asan # AddressSanitizer + libFuzzer for long receive-path fuzz runs. diff --git a/MODULE.bazel b/MODULE.bazel index 6f81be0..6a31a2b 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -44,3 +44,10 @@ single_version_override( module_name = "rules_android", version = "0.7.2", ) + +bazel_dep(name = "rules_rust", version = "0.74.0") + +rust = use_extension("@rules_rust//rust:extensions.bzl", "rust") +rust.toolchain(edition = "2021") +use_repo(rust, "rust_toolchains") +register_toolchains("@rust_toolchains//:all") diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index cea3940..97b91ce 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -23,6 +23,7 @@ "https://bcr.bazel.build/modules/apple_support/1.21.0/MODULE.bazel": "ac1824ed5edf17dee2fdd4927ada30c9f8c3b520be1b5fd02a5da15bc10bff3e", "https://bcr.bazel.build/modules/apple_support/1.21.1/MODULE.bazel": "5809fa3efab15d1f3c3c635af6974044bac8a4919c62238cce06acee8a8c11f1", "https://bcr.bazel.build/modules/apple_support/1.22.1/MODULE.bazel": "90bd1a660590f3ceffbdf524e37483094b29352d85317060b2327fff8f3f4458", + "https://bcr.bazel.build/modules/apple_support/1.24.1/MODULE.bazel": "f46e8ddad60aef170ee92b2f3d00ef66c147ceafea68b6877cb45bd91737f5f8", "https://bcr.bazel.build/modules/apple_support/1.24.2/MODULE.bazel": "0e62471818affb9f0b26f128831d5c40b074d32e6dda5a0d3852847215a41ca4", "https://bcr.bazel.build/modules/apple_support/1.24.2/source.json": "2c22c9827093250406c5568da6c54e6fdf0ef06238def3d99c71b12feb057a8d", "https://bcr.bazel.build/modules/aspect_bazel_lib/2.14.0/MODULE.bazel": "2b31ffcc9bdc8295b2167e07a757dbbc9ac8906e7028e5170a3708cecaac119f", @@ -50,7 +51,8 @@ "https://bcr.bazel.build/modules/bazel_features/1.4.1/MODULE.bazel": "e45b6bb2350aff3e442ae1111c555e27eac1d915e77775f6fdc4b351b758b5d7", "https://bcr.bazel.build/modules/bazel_features/1.42.1/MODULE.bazel": "275a59b5406ff18c01739860aa70ad7ccb3cfb474579411decca11c93b951080", "https://bcr.bazel.build/modules/bazel_features/1.43.0/MODULE.bazel": "defa2226f06ba20550d6548c3a2ea2a7929634437a52973869c20c225450eb91", - "https://bcr.bazel.build/modules/bazel_features/1.43.0/source.json": "1c4207dc858d6de0eecef30026793616bbf420c74aac27b6bad212534a730437", + "https://bcr.bazel.build/modules/bazel_features/1.50.0/MODULE.bazel": "2083ef9c7a469f520890483ccf8e0189d6e71e2117e7752e15e6554433d5ae3e", + "https://bcr.bazel.build/modules/bazel_features/1.50.0/source.json": "e0ee3debde2789ff56e4452e612d126925ba9ab64d4bde79c67f099d2902df9b", "https://bcr.bazel.build/modules/bazel_features/1.9.0/MODULE.bazel": "885151d58d90d8d9c811eb75e3288c11f850e1d6b481a8c9f766adee4712358b", "https://bcr.bazel.build/modules/bazel_features/1.9.1/MODULE.bazel": "8f679097876a9b609ad1f60249c49d68bfab783dd9be012faf9d82547b14815a", "https://bcr.bazel.build/modules/bazel_lib/3.0.0/MODULE.bazel": "22b70b80ac89ad3f3772526cd9feee2fa412c2b01933fea7ed13238a448d370d", @@ -168,6 +170,7 @@ "https://bcr.bazel.build/modules/rules_cc/0.2.16/MODULE.bazel": "9242fa89f950c6ef7702801ab53922e99c69b02310c39fb6e62b2bd30df2a1d4", "https://bcr.bazel.build/modules/rules_cc/0.2.17/MODULE.bazel": "1849602c86cb60da8613d2de887f9566a6d354a6df6d7009f9d04a14402f9a84", "https://bcr.bazel.build/modules/rules_cc/0.2.17/source.json": "3832f45d145354049137c0090df04629d9c2b5493dc5c2bf46f1834040133a07", + "https://bcr.bazel.build/modules/rules_cc/0.2.4/MODULE.bazel": "1ff1223dfd24f3ecf8f028446d4a27608aa43c3f41e346d22838a4223980b8cc", "https://bcr.bazel.build/modules/rules_cc/0.2.8/MODULE.bazel": "f1df20f0bf22c28192a794f29b501ee2018fa37a3862a1a2132ae2940a23a642", "https://bcr.bazel.build/modules/rules_foreign_cc/0.9.0/MODULE.bazel": "c9e8c682bf75b0e7c704166d79b599f93b72cfca5ad7477df596947891feeef6", "https://bcr.bazel.build/modules/rules_fuzzing/0.5.2/MODULE.bazel": "40c97d1144356f52905566c55811f13b299453a14ac7769dfba2ac38192337a8", @@ -242,6 +245,8 @@ "https://bcr.bazel.build/modules/rules_python/1.9.0/source.json": "3921ea0b65298d51aead5b9e4a82203d7be9b5918619b58b53f1c259f4e63169", "https://bcr.bazel.build/modules/rules_robolectric/4.14.1.2/MODULE.bazel": "d44fec647d0aeb67b9f3b980cf68ba634976f3ae7ccd6c07d790b59b87a4f251", "https://bcr.bazel.build/modules/rules_robolectric/4.14.1.2/source.json": "37c10335f2361c337c5c1f34ed36d2da70534c23088062b33a8bdaab68aa9dea", + "https://bcr.bazel.build/modules/rules_rust/0.74.0/MODULE.bazel": "6e6fa04d7c8202f9cd63205ec9f96da39382a4ac971ee1d7a900fe8e1f68be17", + "https://bcr.bazel.build/modules/rules_rust/0.74.0/source.json": "04eac31b4536eb23dd8e8e8ca7e079d3c1c4ac99934d38aa54bbae36917c7507", "https://bcr.bazel.build/modules/rules_shell/0.2.0/MODULE.bazel": "fda8a652ab3c7d8fee214de05e7a9916d8b28082234e8d2c0094505c5268ed3c", "https://bcr.bazel.build/modules/rules_shell/0.3.0/MODULE.bazel": "de4402cd12f4cc8fda2354fce179fdb068c0b9ca1ec2d2b17b3e21b24c1a937b", "https://bcr.bazel.build/modules/rules_shell/0.4.1/MODULE.bazel": "00e501db01bbf4e3e1dd1595959092c2fadf2087b2852d3f553b5370f5633592", diff --git a/README.md b/README.md index 0ef2c46..877428a 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,9 @@ wire-format, instead of in a tree of heap-allocated objects. Once a message is b it can be written to disk, placed in shared memory, or sent over an IPC system **without a serialization step** — the bytes in the buffer *are* the message. -Choose a familiar protobuf-style C++ API or a ROS-style public-field API. Both -frontends use the same native payload and expose the same protobuf and ROS wire -conversion backends. +Choose a protobuf-style C++ API, a ROS-style public-field API, or a C API. +Python and Rust clients use the protobuf-style accessors. All of them share +the same native payload and the same protobuf and ROS wire conversion backends. > 📖 For the full reference, see the **[Phaser User Guide](phaser/docs/phaser_user_guide.md)**. @@ -48,7 +48,7 @@ costs nothing until you actually touch a field. interoperate via per-message field metadata. - **Protobuf wire-format transcoding** is available when you *do* need it (e.g. storing in systems like BigQuery that expect protobuf bytes). -- **Two C++ frontends** — protobuf-style accessors or ROS-style public field proxies. +- **Three frontends** — protobuf-style C++ accessors, ROS-style public field proxies, or a C API. Python wraps the protobuf accessors. Rust wraps the C API. - **Direct wire-to-wire conversion** between protobuf and ROS1 without constructing an intermediate user-facing message. - **Allocation-free receive paths** when native payloads and wire conversions use @@ -57,7 +57,7 @@ costs nothing until you actually touch a field. ## Features 1. proto3 (primary) and proto2 IDL support -2. Protobuf and ROS-style generated C++ frontends +2. Protobuf, ROS, and C frontends, plus Python and Rust clients 3. Native Phaser, protobuf, and ROS1 wire input/output 4. Direct protobuf-to-ROS and ROS-to-protobuf backend conversion 5. Fixed, caller-owned, and dynamically growing buffers @@ -127,7 +127,7 @@ proto_library( phaser_library( name = "foo_phaser", add_namespace = "phaser", # optional: avoids clashing with protobuf classes - frontend = "protobuf", # default; use "ros" for public field proxies + frontend = "protobuf", # default; "ros" or "c" select the other frontends enable_active_message = False, # optionally add an active_message deps = [":foo_proto"], ) @@ -141,8 +141,7 @@ any protobuf header: #include "foo/bar/Foo.phaser.h" ``` -Phaser can generate either the default protobuf-style accessors or a ROS-style -struct interface: +The C++ library can use protobuf-style accessors or a ROS-style struct: ```python phaser_library( @@ -153,7 +152,42 @@ phaser_library( ) ``` -The frontend changes only the C++ access syntax: +### Python, C, and Rust + +`python = True` builds a pybind11 module named `_py` over the protobuf accessors. `frontend = "c"` emits `Foo.phaser.c.h`. `rust = True` builds a crate named `_rs` and selects the C frontend when `frontend` is omitted. The ROS frontend is C++ only. Field mapping, ownership, and examples are in the user guide's [Python, C, and Rust](phaser/docs/phaser_user_guide.md#python-c-and-rust) section. + +```python +phaser_library( + name = "foo_py", + python = True, + deps = [":foo_proto"], +) + +phaser_library( + name = "foo_c", + rust = True, # C API, plus a Rust crate foo_c_rs + deps = [":foo_proto"], +) +``` + +```c +phaser_foo_bar_Foo* msg = phaser_foo_bar_Foo_new(8192); +phaser_foo_bar_Foo_set_name(msg, (const uint8_t*)"sensor", 6); +PhaserBytes name = phaser_foo_bar_Foo_name(msg); +phaser_free(name.data); /* PhaserBytes.data */ +phaser_foo_bar_Foo_free(msg); /* free nested handles first */ +``` + +```rust +let mut msg = foo_c::Foo::new(8192); +msg.set_name("sensor"); +{ + let mut child = msg.mutable_child(); + child.set_label("cam"); +} +``` + +The frontend changes source-level access, not the payload layout: ```c++ // frontend = "protobuf" @@ -538,8 +572,8 @@ accessor, so that presence accessor is named `_phaser_has_()` instead. | Path | Description | | --- | --- | -| `phaser/compiler/` | The `protoc` plugin that generates C++ code (`gen`, `enum_gen`, `message_gen`, `main`). | -| `phaser/runtime/` | The runtime library: `Message`, fields, vectors, unions, wire-format, the Phaser Bank, and `PayloadBuffer` glue. | +| `phaser/compiler/` | The `protoc` plugin (`gen`, `enum_gen`, `message_gen`, and the C frontend emitter). | +| `phaser/runtime/` | The runtime library: `Message`, fields, vectors, unions, wire-format, the Phaser Bank, the C API, and `PayloadBuffer` glue. | | `phaser/phaser_library.bzl` | The `phaser_library` Bazel rule and supporting aspect. | | `phaser/testdata/` | Example `.proto` files used by the tests. | | `phaser/docs/` | Reference documentation (the user guide). | @@ -548,6 +582,7 @@ accessor, so that presence accessor is named `_phaser_has_()` instead. The complete reference — message layout, buffer internals, the allocator, reflection, the Phaser Bank, Arrow conversion, and more — is in the **[Phaser User Guide](phaser/docs/phaser_user_guide.md)**. +Python, C, and Rust are in [Python, C, and Rust](phaser/docs/phaser_user_guide.md#python-c-and-rust). Arrow usage is in the guide's [Arrow](phaser/docs/phaser_user_guide.md#arrow) section. Protobuf and ROS conversion through the bank is in [Protobuf and ROS conversion](phaser/docs/phaser_user_guide.md#protobuf-and-ros-conversion). diff --git a/phaser/compiler/BUILD.bazel b/phaser/compiler/BUILD.bazel index a659191..8231595 100644 --- a/phaser/compiler/BUILD.bazel +++ b/phaser/compiler/BUILD.bazel @@ -10,6 +10,7 @@ cc_library( "gen.cc", "message_gen.cc", "message_gen_arrow.cc", + "message_gen_c.cc", "message_gen_python.cc", ], copts = PHASER_PROTOC_COPTS, diff --git a/phaser/compiler/gen.cc b/phaser/compiler/gen.cc index 7b89c52..c02d397 100644 --- a/phaser/compiler/gen.cc +++ b/phaser/compiler/gen.cc @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -122,6 +123,20 @@ static void WriteToZeroCopyStream( } } +static bool WriteOutput( + google::protobuf::compiler::GeneratorContext* generator_context, + const std::filesystem::path& path, const std::string& contents, + std::string* error) { + std::unique_ptr output( + generator_context->Open(path.string())); + if (output == nullptr) { + *error = absl::StrFormat("Failed to open %s for writing", path.string()); + return false; + } + WriteToZeroCopyStream(contents, output.get()); + return true; +} + static std::string GeneratedFilename(const std::filesystem::path& package_name, const std::filesystem::path& target_name, std::string filename) { @@ -182,19 +197,28 @@ bool CodeGenerator::Generate( } else if (option.first == "ros_metadata") { generate_ros_metadata_ = option.second.empty() || option.second == "true" || option.second == "1"; + } else if (option.first == "rust") { + generate_rust_ = option.second.empty() || option.second == "true" || + option.second == "1"; } else if (option.first == "frontend") { if (option.second == "protobuf" || option.second.empty()) { frontend_style_ = FrontendStyle::kProtobuf; } else if (option.second == "ros") { frontend_style_ = FrontendStyle::kRos; + } else if (option.second == "c") { + frontend_style_ = FrontendStyle::kC; } else { *error = absl::StrFormat( - "Unknown frontend value: %s (expected protobuf or ros)", + "Unknown frontend value: %s (expected protobuf, ros, or c)", option.second); return false; } } } + if (generate_rust_ && frontend_style_ != FrontendStyle::kC) { + *error = "rust=true requires frontend=c"; + return false; + } const FrontendStyle effective_frontend = EffectiveFrontendStyle(file, frontend_style_); @@ -229,10 +253,28 @@ bool CodeGenerator::Generate( header_output.get()); WriteToZeroCopyStream("// No Phaser definitions in this schema.\n", source_output.get()); - // descriptor.proto and options.proto are not declared as Python outputs. + // descriptor.proto and options.proto are not declared as language outputs. // Every other schema, including ones with no messages, is. - if (file->name() != std::string("google/protobuf/descriptor.proto") && - file->name() != std::string("phaser/options.proto")) { + const bool skip_language_bindings = + file->name() == std::string("google/protobuf/descriptor.proto") || + file->name() == std::string("phaser/options.proto"); + if (!skip_language_bindings && frontend_style_ == FrontendStyle::kC) { + std::filesystem::path c_header(filename); + c_header.replace_extension(".phaser.c.h"); + if (!WriteOutput(generator_context, c_header, + "// No Phaser C API in this schema.\n", error)) { + return false; + } + } + if (!skip_language_bindings && generate_rust_) { + std::filesystem::path rust_path(filename); + rust_path.replace_extension(".rs"); + if (!WriteOutput(generator_context, rust_path, + "// No Phaser Rust API in this schema.\n", error)) { + return false; + } + } + if (!skip_language_bindings) { std::filesystem::path pyp(filename); pyp.replace_extension(".pybind.cc"); auto python_output = @@ -296,6 +338,26 @@ bool CodeGenerator::Generate( std::stringstream source_stream; gen.GenerateSources(source_stream); + if (effective_frontend == FrontendStyle::kC) { + std::stringstream c_header; + std::stringstream rust_stream; + gen.GenerateBindings(c_header, source_stream, + generate_rust_ ? &rust_stream : nullptr); + std::filesystem::path c_path(filename); + c_path.replace_extension(".phaser.c.h"); + if (!WriteOutput(generator_context, c_path, c_header.str(), error)) { + return false; + } + if (generate_rust_) { + std::filesystem::path rust_path(filename); + rust_path.replace_extension(".rs"); + if (!WriteOutput(generator_context, rust_path, rust_stream.str(), + error)) { + return false; + } + } + } + // Write to the streams that protobuf wants std::filesystem::path pyp(filename); pyp.replace_extension(".pybind.cc"); diff --git a/phaser/compiler/gen.h b/phaser/compiler/gen.h index fb9eea3..6e383ae 100644 --- a/phaser/compiler/gen.h +++ b/phaser/compiler/gen.h @@ -40,9 +40,14 @@ class CodeGenerator : public google::protobuf::compiler::CodeGenerator { // phaser_library(enable_active_message = True)). mutable bool generate_active_message_ = false; mutable bool generate_ros_metadata_ = false; + mutable bool generate_rust_ = false; mutable FrontendStyle frontend_style_ = FrontendStyle::kProtobuf; }; +std::string GeneratedIncludeFilename(const std::filesystem::path& package_name, + const std::filesystem::path& target_name, + const std::string& filename); + class Generator { public: Generator(const google::protobuf::FileDescriptor* file, const std::string& ns, @@ -55,6 +60,8 @@ class Generator { void GenerateSources(std::ostream& os); void GeneratePython(std::ostream& os); void GenerateProtobufDescriptorRegistrations(std::ostream& os); + void GenerateBindings(std::ostream& c_header, std::ostream& c_source, + std::ostream* rust); std::string CppNamespace() const; private: @@ -76,9 +83,6 @@ class Generator { // `proto_filename` is the canonical proto path, such as // `phaser/testdata/TestMessage.proto`. The Bazel rule derives the same symbol // from that path. -std::string GeneratedIncludeFilename( - const std::filesystem::path& package_name, - const std::filesystem::path& target_name, const std::string& filename); std::string PythonRegisterSymbol(const std::string& proto_filename); void WriteEmptyPythonRegistration(std::ostream& os, const std::string& symbol); diff --git a/phaser/compiler/message_gen.h b/phaser/compiler/message_gen.h index 07cd30e..be8f323 100644 --- a/phaser/compiler/message_gen.h +++ b/phaser/compiler/message_gen.h @@ -19,7 +19,7 @@ namespace phaser { -enum class FrontendStyle { kProtobuf, kRos }; +enum class FrontendStyle { kProtobuf, kRos, kC }; struct FieldInfo { // Constructor. @@ -86,6 +86,12 @@ class MessageGenerator { absl::Status GenerateHeader(std::ostream& os); void GenerateSource(std::ostream& os); + // C frontend declarations and definitions. `rust` receives the safe Rust + // wrapper when non-null. `declared_types` records opaque struct names + // already emitted into the C header. + void GenerateBindings(std::ostream& decl, std::ostream& def, + std::ostream* rust, + std::vector* declared_types); // Python bindings are emitted in three passes so a method can return a type // declared later in the file: enums, then class objects, then methods. void GeneratePythonEnums(std::ostream& os); @@ -313,6 +319,16 @@ class MessageGenerator { bool IsRosFrontend() const { return frontend_style_ == FrontendStyle::kRos; } + bool IsCFrontend() const { return frontend_style_ == FrontendStyle::kC; } + void EmitCField(const google::protobuf::FieldDescriptor* field, + std::ostream& decl, std::ostream& def, + std::ostream* rust_extern, std::ostream* rust_body, + std::vector* declared_types, + const std::string& self_prefix, const std::string& self_cxx, + const std::string& self_raw); + std::string CppMessageType(const google::protobuf::Descriptor* desc) const; + std::string CppEnumType(const google::protobuf::EnumDescriptor* desc) const; + std::string RustMessageType(const google::protobuf::Descriptor* desc) const; const google::protobuf::Descriptor* message_; std::vector> nested_message_gens_; diff --git a/phaser/compiler/message_gen_c.cc b/phaser/compiler/message_gen_c.cc new file mode 100644 index 0000000..191125d --- /dev/null +++ b/phaser/compiler/message_gen_c.cc @@ -0,0 +1,738 @@ +// Copyright 2024-2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "phaser/compiler/gen.h" + +#include +#include +#include +#include + +#include "absl/strings/str_replace.h" + +namespace phaser { +namespace { + +bool IsRustKeyword(std::string_view name) { + static constexpr std::string_view kWords[] = { + "Self", "abstract", "as", "async", "await", "become", + "box", "break", "const", "continue", "crate", "do", + "dyn", "else", "enum", "extern", "false", "final", + "fn", "for", "if", "impl", "in", "let", + "loop", "macro", "match", "mod", "move", "mut", + "override","priv", "pub", "ref", "return", "self", + "static", "struct", "super", "trait", "true", "try", + "type", "typeof", "union", "unsafe", "unsized", "use", + "virtual", "where", "while", "yield", + }; + for (std::string_view word : kWords) { + if (name == word) { + return true; + } + } + return false; +} + +std::string RustIdent(std::string name) { + while (IsRustKeyword(name)) { + name.push_back('_'); + } + return name; +} + +std::string SanitizeIdent(std::string name) { + for (char& c : name) { + const unsigned char uc = static_cast(c); + const bool ok = (uc >= '0' && uc <= '9') || (uc >= 'A' && uc <= 'Z') || + (uc >= 'a' && uc <= 'z') || c == '_'; + if (!ok) { + c = '_'; + } + } + if (name.empty() || (name[0] >= '0' && name[0] <= '9')) { + name.insert(name.begin(), '_'); + } + return name; +} + +std::string FlatMessageName(const google::protobuf::Descriptor* desc) { + if (desc->containing_type() == nullptr) { + return std::string(desc->name()); + } + return std::string(desc->containing_type()->name()) + "_" + + std::string(desc->name()); +} + +std::string FlatEnumName(const google::protobuf::EnumDescriptor* desc) { + if (desc->containing_type() == nullptr) { + return std::string(desc->name()); + } + return std::string(desc->containing_type()->name()) + "_" + + std::string(desc->name()); +} + +std::string CPrefixFrom(const std::string& package, const std::string& flat) { + if (package.empty()) { + return "phaser_" + SanitizeIdent(flat); + } + return "phaser_" + SanitizeIdent(package) + "_" + SanitizeIdent(flat); +} + +std::string CMessagePrefix(const google::protobuf::Descriptor* desc) { + return CPrefixFrom(std::string(desc->file()->package()), FlatMessageName(desc)); +} + +std::string CEnumPrefix(const google::protobuf::EnumDescriptor* desc) { + return CPrefixFrom(std::string(desc->file()->package()), FlatEnumName(desc)); +} + +void EnsureType(std::ostream& decl, std::vector* declared, + const std::string& prefix) { + if (prefix == "phaser_AnyMessage") { + return; + } + for (const std::string& name : *declared) { + if (name == prefix) { + return; + } + } + declared->push_back(prefix); + decl << "typedef struct " << prefix << " " << prefix << ";\n"; +} + +void EmitEnum(const google::protobuf::EnumDescriptor* desc, std::ostream& decl, + std::ostream* rust) { + const std::string prefix = CEnumPrefix(desc); + decl << "typedef int32_t " << prefix << ";\n"; + decl << "enum {\n"; + for (int i = 0; i < desc->value_count(); ++i) { + const google::protobuf::EnumValueDescriptor* value = desc->value(i); + decl << " " << prefix << "_" << value->name() << " = " << value->number() + << ",\n"; + } + decl << "};\n"; + if (rust == nullptr) { + return; + } + const std::string rust_name = RustIdent(FlatEnumName(desc)); + *rust << "#[derive(Clone, Copy, PartialEq, Eq, Debug)]\npub struct " << rust_name + << "(pub i32);\nimpl " << rust_name << " {\n"; + for (int i = 0; i < desc->value_count(); ++i) { + const google::protobuf::EnumValueDescriptor* value = desc->value(i); + *rust << " pub const " << RustIdent(std::string(value->name())) + << ": Self = Self(" << value->number() << ");\n"; + } + *rust << "}\n\n"; +} + +std::string Guard(const std::string& cpp, bool is_const, + const std::string& fallback) { + std::string out = " using Msg = " + cpp + ";\n "; + out += is_const ? "const auto* h = ::phaser::capi::AsHandle(msg);\n" + : "auto* h = ::phaser::capi::AsHandle(msg);\n"; + out += " if (h == nullptr || h->get() == nullptr) {\n " + fallback + + "\n }\n"; + return out; +} + +void Bind(std::ostream& decl, std::ostream& def, std::ostream* rust_extern, + std::ostream* rust_body, const std::string& c_signature, + const std::string& c_body, const std::string& rust_signature, + const std::string& rust_method) { + decl << c_signature << ";\n"; + def << c_signature << " {\n" << c_body << "}\n"; + if (rust_extern == nullptr) { + return; + } + *rust_extern << " fn " << rust_signature << ";\n"; + *rust_body << rust_method; +} + +std::string Qualified(const std::string& package, const std::string& added, + const std::string& flat) { + std::string scope = "::"; + if (!package.empty()) { + scope += absl::StrReplaceAll(package, {{".", "::"}}); + } + if (!added.empty()) { + if (scope.size() > 2) { + scope += "::"; + } + scope += added; + } + if (scope == "::") { + return "::" + flat; + } + return scope + "::" + flat; +} + +} // namespace + +std::string MessageGenerator::CppMessageType( + const google::protobuf::Descriptor* desc) const { + if (desc->full_name() == "google.protobuf.Any") { + return "::phaser::AnyMessage"; + } + return Qualified(std::string(desc->file()->package()), added_namespace_, + FlatMessageName(desc)); +} + +std::string MessageGenerator::CppEnumType( + const google::protobuf::EnumDescriptor* desc) const { + return Qualified(std::string(desc->file()->package()), added_namespace_, + FlatEnumName(desc)); +} + +std::string MessageGenerator::RustMessageType( + const google::protobuf::Descriptor* desc) const { + if (desc->full_name() == "google.protobuf.Any") { + return "AnyMessage"; + } + return RustIdent(FlatMessageName(desc)); +} + +void MessageGenerator::EmitCField( + const google::protobuf::FieldDescriptor* field, std::ostream& decl, + std::ostream& def, std::ostream* rust_extern, std::ostream* rust_body, + std::vector* declared_types, const std::string& self_prefix, + const std::string& self_cxx, const std::string& self_raw) { + if (field->type() == google::protobuf::FieldDescriptor::TYPE_GROUP) { + return; + } + const std::string proto_name(field->name()); + const std::string cxx_get = FieldAccessorName(proto_name); + const std::string rust_get = RustIdent(cxx_get); + const bool repeated = field->is_repeated(); + const std::string const_self = "const " + self_prefix + "* msg"; + const std::string mut_self = self_prefix + "* msg"; + const std::string raw_const = "*const " + self_raw; + const std::string raw_mut = "*mut " + self_raw; + + auto c_name = [&](const std::string& method) { + return self_prefix + "_" + method; + }; + + if (field->type() == google::protobuf::FieldDescriptor::TYPE_MESSAGE) { + const bool any = IsAny(field); + const std::string child_cpp = CppMessageType(field->message_type()); + const std::string child_prefix = + any ? "phaser_AnyMessage" : CMessagePrefix(field->message_type()); + const std::string child_rust = RustMessageType(field->message_type()); + const std::string child_raw = + any ? "RawAnyMessage" : "Raw" + child_rust; + if (!any) { + EnsureType(decl, declared_types, child_prefix); + } + const std::string mutable_cxx = "mutable_" + proto_name; + const std::string add_cxx = "add_" + proto_name; + const std::string clear_cxx = "clear_" + proto_name; + const std::string size_cxx = proto_name + "_size"; + const std::string has_cxx = PresenceAccessorName(proto_name); + + auto box_view = [&](const std::string& expr) { + return " return ::phaser::capi::BoxView< " + child_cpp + ", " + + child_prefix + ">(" + expr + ");\n"; + }; + auto box_value = [&](const std::string& expr) { + return " return ::phaser::capi::BoxValue< " + child_cpp + ", " + + child_prefix + ">(" + expr + ");\n"; + }; + auto rust_child = [&](const std::string& call) { + if (any) { + return std::string(" AnyMessage::from_raw(unsafe { ") + call + + " })\n"; + } + return " " + child_rust + + " {\n ptr: rust_ptr(unsafe { " + call + + " }),\n _parent: PhantomData,\n }\n"; + }; + + if (repeated) { + Bind(decl, def, rust_extern, rust_body, + child_prefix + "* " + c_name(cxx_get) + "(" + const_self + + ", size_t index)", + Guard(self_cxx, true, "return nullptr;") + + box_value("h->get()->" + cxx_get + "(index)"), + c_name(cxx_get) + "(msg: " + raw_const + ", index: usize) -> *mut " + + child_raw, + " pub fn " + rust_get + + "<'b>(&'b self, index: usize) -> " + child_rust + "<'b> {\n" + + rust_child(c_name(cxx_get) + "(self.ptr, index)") + " }\n"); + Bind(decl, def, rust_extern, rust_body, + child_prefix + "* " + c_name(mutable_cxx) + "(" + mut_self + + ", size_t index)", + Guard(self_cxx, false, "return nullptr;") + + box_value("h->get()->" + mutable_cxx + "(index)"), + c_name(mutable_cxx) + "(msg: " + raw_mut + + ", index: usize) -> *mut " + child_raw, + " pub fn " + RustIdent(mutable_cxx) + + "<'b>(&'b mut self, index: usize) -> " + child_rust + + "<'b> {\n" + + rust_child(c_name(mutable_cxx) + "(self.ptr, index)") + + " }\n"); + Bind(decl, def, rust_extern, rust_body, + child_prefix + "* " + c_name(add_cxx) + "(" + mut_self + ")", + Guard(self_cxx, false, "return nullptr;") + + box_value("h->get()->" + add_cxx + "()"), + c_name(add_cxx) + "(msg: " + raw_mut + ") -> *mut " + child_raw, + " pub fn " + RustIdent(add_cxx) + "<'b>(&'b mut self) -> " + + child_rust + "<'b> {\n" + + rust_child(c_name(add_cxx) + "(self.ptr)") + " }\n"); + } else { + Bind(decl, def, rust_extern, rust_body, + child_prefix + "* " + c_name(cxx_get) + "(" + const_self + ")", + Guard(self_cxx, true, "return nullptr;") + + " const auto& ref = h->get()->" + cxx_get + + "();\n return ::phaser::capi::BoxView< " + child_cpp + ", " + + child_prefix + ">(const_cast< " + child_cpp + "*>(&ref));\n", + c_name(cxx_get) + "(msg: " + raw_const + ") -> *mut " + child_raw, + " pub fn " + rust_get + "<'b>(&'b self) -> " + child_rust + + "<'b> {\n" + rust_child(c_name(cxx_get) + "(self.ptr)") + + " }\n"); + Bind(decl, def, rust_extern, rust_body, + child_prefix + "* " + c_name(mutable_cxx) + "(" + mut_self + ")", + Guard(self_cxx, false, "return nullptr;") + + box_view("h->get()->" + mutable_cxx + "()"), + c_name(mutable_cxx) + "(msg: " + raw_mut + ") -> *mut " + child_raw, + " pub fn " + RustIdent(mutable_cxx) + "<'b>(&'b mut self) -> " + + child_rust + "<'b> {\n" + + rust_child(c_name(mutable_cxx) + "(self.ptr)") + " }\n"); + Bind(decl, def, rust_extern, rust_body, + "uint8_t " + c_name(has_cxx) + "(" + const_self + ")", + Guard(self_cxx, true, "return 0;") + + " return h->get()->" + has_cxx + + "() ? static_cast(1) : static_cast(0);\n", + c_name(has_cxx) + "(msg: " + raw_const + ") -> u8", + " pub fn " + RustIdent(has_cxx) + "(&self) -> bool {\n flag(unsafe { " + + c_name(has_cxx) + "(self.ptr) })\n }\n"); + } + Bind(decl, def, rust_extern, rust_body, + "void " + c_name(clear_cxx) + "(" + mut_self + ")", + Guard(self_cxx, false, "return;") + " h->get()->" + clear_cxx + + "();\n", + c_name(clear_cxx) + "(msg: " + raw_mut + ")", + " pub fn " + RustIdent(clear_cxx) + + "(&mut self) {\n unsafe { " + c_name(clear_cxx) + + "(self.ptr) }\n }\n"); + if (repeated) { + Bind(decl, def, rust_extern, rust_body, + "size_t " + c_name(size_cxx) + "(" + const_self + ")", + Guard(self_cxx, true, "return 0;") + " return h->get()->" + + size_cxx + "();\n", + c_name(size_cxx) + "(msg: " + raw_const + ") -> usize", + " pub fn " + RustIdent(size_cxx) + + "(&self) -> usize {\n unsafe { " + c_name(size_cxx) + + "(self.ptr) }\n }\n"); + Bind(decl, def, rust_extern, rust_body, + "void " + c_name("reserve_" + proto_name) + "(" + mut_self + + ", size_t count)", + Guard(self_cxx, false, "return;") + " h->get()->reserve_" + + proto_name + "(count);\n", + c_name("reserve_" + proto_name) + "(msg: " + raw_mut + + ", count: usize)", + " pub fn " + RustIdent("reserve_" + proto_name) + + "(&mut self, count: usize) {\n unsafe { " + + c_name("reserve_" + proto_name) + "(self.ptr, count) }\n }\n"); + Bind(decl, def, rust_extern, rust_body, + "void " + c_name("resize_" + proto_name) + "(" + mut_self + + ", size_t count)", + Guard(self_cxx, false, "return;") + " h->get()->resize_" + + proto_name + "(count);\n", + c_name("resize_" + proto_name) + "(msg: " + raw_mut + + ", count: usize)", + " pub fn " + RustIdent("resize_" + proto_name) + + "(&mut self, count: usize) {\n unsafe { " + + c_name("resize_" + proto_name) + "(self.ptr, count) }\n }\n"); + } + return; + } + + std::string c_type = "int32_t"; + std::string rust_type = "i32"; + std::string c_zero = "0"; + enum class Kind { kNumber, kBool, kString, kBytes, kEnum }; + Kind kind = Kind::kNumber; + std::string enum_cpp; + std::string enum_rust; + switch (field->type()) { + case google::protobuf::FieldDescriptor::TYPE_INT32: + case google::protobuf::FieldDescriptor::TYPE_SINT32: + case google::protobuf::FieldDescriptor::TYPE_SFIXED32: + break; + case google::protobuf::FieldDescriptor::TYPE_INT64: + case google::protobuf::FieldDescriptor::TYPE_SINT64: + case google::protobuf::FieldDescriptor::TYPE_SFIXED64: + c_type = "int64_t"; + rust_type = "i64"; + break; + case google::protobuf::FieldDescriptor::TYPE_UINT32: + case google::protobuf::FieldDescriptor::TYPE_FIXED32: + c_type = "uint32_t"; + rust_type = "u32"; + break; + case google::protobuf::FieldDescriptor::TYPE_UINT64: + case google::protobuf::FieldDescriptor::TYPE_FIXED64: + c_type = "uint64_t"; + rust_type = "u64"; + break; + case google::protobuf::FieldDescriptor::TYPE_FLOAT: + c_type = "float"; + rust_type = "f32"; + break; + case google::protobuf::FieldDescriptor::TYPE_DOUBLE: + c_type = "double"; + rust_type = "f64"; + break; + case google::protobuf::FieldDescriptor::TYPE_BOOL: + kind = Kind::kBool; + c_type = "uint8_t"; + rust_type = "bool"; + break; + case google::protobuf::FieldDescriptor::TYPE_STRING: + kind = Kind::kString; + c_type = "PhaserBytes"; + rust_type = "String"; + c_zero = "PhaserBytes{nullptr, size_t{0}}"; + break; + case google::protobuf::FieldDescriptor::TYPE_BYTES: + kind = Kind::kBytes; + c_type = "PhaserBytes"; + rust_type = "Vec"; + c_zero = "PhaserBytes{nullptr, size_t{0}}"; + break; + case google::protobuf::FieldDescriptor::TYPE_ENUM: + kind = Kind::kEnum; + c_type = "int32_t"; + enum_cpp = CppEnumType(field->enum_type()); + enum_rust = RustIdent(FlatEnumName(field->enum_type())); + rust_type = enum_rust; + break; + default: + return; + } + + const std::string set_cxx = "set_" + proto_name; + const std::string clear_cxx = "clear_" + proto_name; + const std::string has_cxx = PresenceAccessorName(proto_name); + const std::string add_cxx = "add_" + proto_name; + const std::string size_cxx = proto_name + "_size"; + + auto value_expr = [&](const std::string& expr) { + if (kind == Kind::kBool) { + return expr + " ? static_cast(1) : static_cast(0)"; + } + if (kind == Kind::kString || kind == Kind::kBytes) { + return "::phaser::capi::Copy(" + expr + ")"; + } + if (kind == Kind::kEnum) { + return "static_cast(" + expr + ")"; + } + return expr; + }; + auto store_expr = [&](const std::string& value) { + if (kind == Kind::kBool) { + return value + " != 0"; + } + if (kind == Kind::kString || kind == Kind::kBytes) { + return "::phaser::capi::Bytes(" + value + ")"; + } + if (kind == Kind::kEnum) { + return "static_cast< " + enum_cpp + ">(" + value + ")"; + } + return value; + }; + + const std::string get_params = + repeated ? const_self + ", size_t index" : const_self; + const std::string get_call = + repeated ? cxx_get + "(index)" : cxx_get + "()"; + const std::string rust_get_params = + repeated ? "msg: " + raw_const + ", index: usize" + : "msg: " + raw_const; + const std::string rust_get_args = repeated ? "self.ptr, index" : "self.ptr"; + std::string rust_ret = rust_type; + if (kind == Kind::kBool) { + rust_ret = "u8"; + } else if (kind == Kind::kString || kind == Kind::kBytes) { + rust_ret = "PhaserBytes"; + } else if (kind == Kind::kEnum) { + rust_ret = "i32"; + } + const std::string call = + "unsafe { " + c_name(cxx_get) + "(" + rust_get_args + ") }"; + std::string expr = call; + if (kind == Kind::kBool) { + expr = "flag(" + call + ")"; + } else if (kind == Kind::kString) { + expr = "copy_string(" + call + ")"; + } else if (kind == Kind::kBytes) { + expr = "copy_bytes(" + call + ")"; + } else if (kind == Kind::kEnum) { + expr = enum_rust + "(" + call + ")"; + } + const std::string rust_get_body = " " + expr + "\n"; + const std::string rust_get_sig = + repeated ? " pub fn " + rust_get + "(&self, index: usize) -> " + + rust_type + " {\n" + rust_get_body + " }\n" + : " pub fn " + rust_get + "(&self) -> " + rust_type + + " {\n" + rust_get_body + " }\n"; + Bind(decl, def, rust_extern, rust_body, + c_type + " " + c_name(cxx_get) + "(" + get_params + ")", + Guard(self_cxx, true, "return " + c_zero + ";") + " return " + + value_expr("h->get()->" + get_call) + ";\n", + c_name(cxx_get) + "(" + rust_get_params + ") -> " + rust_ret, + rust_get_sig); + + std::string set_rust_value = rust_type; + std::string rust_set_arg = "value"; + std::string c_set_type = c_type + " value"; + if (kind == Kind::kBool) { + c_set_type = "uint8_t value"; + set_rust_value = "bool"; + rust_set_arg = "u8::from(value)"; + } else if (kind == Kind::kString) { + c_set_type = "const uint8_t* data, size_t len"; + set_rust_value = "&str"; + rust_set_arg = "phaser_bytes_ptr(value.as_bytes()), value.len()"; + } else if (kind == Kind::kBytes) { + c_set_type = "const uint8_t* data, size_t len"; + set_rust_value = "&[u8]"; + rust_set_arg = "phaser_bytes_ptr(value), value.len()"; + } else if (kind == Kind::kEnum) { + c_set_type = "int32_t value"; + set_rust_value = enum_rust; + rust_set_arg = "value.0"; + } + const std::string stored = + (kind == Kind::kString || kind == Kind::kBytes) ? store_expr("data, len") + : store_expr("value"); + if (repeated) { + Bind(decl, def, rust_extern, rust_body, + "void " + c_name(set_cxx) + "(" + mut_self + ", size_t index, " + + c_set_type + ")", + Guard(self_cxx, false, "return;") + " h->get()->" + set_cxx + + "(index, " + stored + ");\n", + c_name(set_cxx) + "(msg: " + raw_mut + ", index: usize, " + + (kind == Kind::kString || kind == Kind::kBytes + ? "data: *const u8, len: usize" + : std::string("value: ") + rust_ret) + + ")", + " pub fn " + RustIdent(set_cxx) + + "(&mut self, index: usize, value: " + set_rust_value + + ") {\n unsafe { " + c_name(set_cxx) + + "(self.ptr, index, " + rust_set_arg + ") }\n }\n"); + Bind(decl, def, rust_extern, rust_body, + "void " + c_name(add_cxx) + "(" + mut_self + ", " + c_set_type + ")", + Guard(self_cxx, false, "return;") + " h->get()->" + add_cxx + "(" + + stored + ");\n", + c_name(add_cxx) + "(msg: " + raw_mut + ", " + + (kind == Kind::kString || kind == Kind::kBytes + ? "data: *const u8, len: usize" + : std::string("value: ") + rust_ret) + + ")", + " pub fn " + RustIdent(add_cxx) + "(&mut self, value: " + + set_rust_value + ") {\n unsafe { " + c_name(add_cxx) + + "(self.ptr, " + rust_set_arg + ") }\n }\n"); + Bind(decl, def, rust_extern, rust_body, + "size_t " + c_name(size_cxx) + "(" + const_self + ")", + Guard(self_cxx, true, "return 0;") + " return h->get()->" + size_cxx + + "();\n", + c_name(size_cxx) + "(msg: " + raw_const + ") -> usize", + " pub fn " + RustIdent(size_cxx) + + "(&self) -> usize {\n unsafe { " + c_name(size_cxx) + + "(self.ptr) }\n }\n"); + Bind(decl, def, rust_extern, rust_body, + "void " + c_name("reserve_" + proto_name) + "(" + mut_self + + ", size_t count)", + Guard(self_cxx, false, "return;") + " h->get()->reserve_" + + proto_name + "(count);\n", + c_name("reserve_" + proto_name) + "(msg: " + raw_mut + + ", count: usize)", + " pub fn " + RustIdent("reserve_" + proto_name) + + "(&mut self, count: usize) {\n unsafe { " + + c_name("reserve_" + proto_name) + "(self.ptr, count) }\n }\n"); + Bind(decl, def, rust_extern, rust_body, + "void " + c_name("resize_" + proto_name) + "(" + mut_self + + ", size_t count)", + Guard(self_cxx, false, "return;") + " h->get()->resize_" + proto_name + + "(count);\n", + c_name("resize_" + proto_name) + "(msg: " + raw_mut + ", count: usize)", + " pub fn " + RustIdent("resize_" + proto_name) + + "(&mut self, count: usize) {\n unsafe { " + + c_name("resize_" + proto_name) + "(self.ptr, count) }\n }\n"); + } else { + Bind(decl, def, rust_extern, rust_body, + "void " + c_name(set_cxx) + "(" + mut_self + ", " + c_set_type + ")", + Guard(self_cxx, false, "return;") + " h->get()->" + set_cxx + "(" + + stored + ");\n", + c_name(set_cxx) + "(msg: " + raw_mut + ", " + + (kind == Kind::kString || kind == Kind::kBytes + ? "data: *const u8, len: usize" + : std::string("value: ") + rust_ret) + + ")", + " pub fn " + RustIdent(set_cxx) + "(&mut self, value: " + + set_rust_value + ") {\n unsafe { " + c_name(set_cxx) + + "(self.ptr, " + rust_set_arg + ") }\n }\n"); + Bind(decl, def, rust_extern, rust_body, + "uint8_t " + c_name(has_cxx) + "(" + const_self + ")", + Guard(self_cxx, true, "return 0;") + " return h->get()->" + has_cxx + + "() ? static_cast(1) : static_cast(0);\n", + c_name(has_cxx) + "(msg: " + raw_const + ") -> u8", + " pub fn " + RustIdent(has_cxx) + + "(&self) -> bool {\n flag(unsafe { " + c_name(has_cxx) + + "(self.ptr) })\n }\n"); + } + Bind(decl, def, rust_extern, rust_body, + "void " + c_name(clear_cxx) + "(" + mut_self + ")", + Guard(self_cxx, false, "return;") + " h->get()->" + clear_cxx + "();\n", + c_name(clear_cxx) + "(msg: " + raw_mut + ")", + " pub fn " + RustIdent(clear_cxx) + + "(&mut self) {\n unsafe { " + c_name(clear_cxx) + + "(self.ptr) }\n }\n"); +} + +void MessageGenerator::GenerateBindings( + std::ostream& decl, std::ostream& def, std::ostream* rust, + std::vector* declared_types) { + if (!IsCFrontend()) { + return; + } + for (const auto& nested : nested_message_gens_) { + nested->GenerateBindings(decl, def, rust, declared_types); + } + const std::string prefix = CMessagePrefix(message_); + // Field types named Any are the runtime AnyMessage. This message's own + // class is the generated type, including when the proto is google.protobuf.Any. + const std::string cpp = + Qualified(std::string(message_->file()->package()), added_namespace_, + FlatMessageName(message_)); + const std::string rust_name = RustIdent(FlatMessageName(message_)); + const std::string raw = "Raw" + rust_name; + EnsureType(decl, declared_types, prefix); + for (int i = 0; i < message_->enum_type_count(); ++i) { + EmitEnum(message_->enum_type(i), decl, rust); + } + + std::stringstream rust_extern; + std::stringstream rust_body; + std::ostream* rust_extern_out = rust == nullptr ? nullptr : &rust_extern; + std::ostream* rust_body_out = rust == nullptr ? nullptr : &rust_body; + const std::string const_self = "const " + prefix + "* msg"; + const std::string mut_self = prefix + "* msg"; + + Bind(decl, def, rust_extern_out, rust_body_out, + prefix + "* " + prefix + "_new(size_t initial_size)", + " using Msg = " + cpp + + ";\n return ::phaser::capi::BoxNew(initial_size);\n", + prefix + "_new(initial_size: usize) -> *mut " + raw, + " pub fn new(initial_size: usize) -> " + rust_name + + "<'static> {\n " + rust_name + + " {\n ptr: rust_ptr(unsafe { " + prefix + + "_new(initial_size) }),\n _parent: PhantomData,\n" + " }\n }\n"); + Bind(decl, def, rust_extern_out, rust_body_out, + "void " + prefix + "_free(" + mut_self + ")", + " using Msg = " + cpp + ";\n ::phaser::capi::FreeHandle(msg);\n", + prefix + "_free(msg: *mut " + raw + ")", ""); + Bind(decl, def, rust_extern_out, rust_body_out, + "void " + prefix + "_clear(" + mut_self + ")", + Guard(cpp, false, "return;") + " h->get()->Clear();\n", + prefix + "_clear(msg: *mut " + raw + ")", + " pub fn clear(&mut self) {\n unsafe { " + prefix + + "_clear(self.ptr) }\n }\n"); + Bind(decl, def, rust_extern_out, rust_body_out, + "PhaserBytes " + prefix + "_debug_string(" + const_self + ")", + Guard(cpp, true, "return PhaserBytes{nullptr, size_t{0}};") + + " return ::phaser::capi::Copy(h->get()->DebugString());\n", + prefix + "_debug_string(msg: *const " + raw + ") -> PhaserBytes", + " pub fn debug_string(&self) -> String {\n copy_string(unsafe { " + + prefix + "_debug_string(self.ptr) })\n }\n"); + Bind(decl, def, rust_extern_out, rust_body_out, + "size_t " + prefix + "_byte_size_long(" + const_self + ")", + Guard(cpp, true, "return 0;") + " return h->get()->ByteSizeLong();\n", + prefix + "_byte_size_long(msg: *const " + raw + ") -> usize", + " pub fn byte_size_long(&self) -> usize {\n unsafe { " + + prefix + "_byte_size_long(self.ptr) }\n }\n"); + Bind(decl, def, rust_extern_out, rust_body_out, + "PhaserBytes " + prefix + "_serialize_as_string(" + const_self + ")", + Guard(cpp, true, "return PhaserBytes{nullptr, size_t{0}};") + + " return ::phaser::capi::Copy(h->get()->SerializeAsString());\n", + prefix + "_serialize_as_string(msg: *const " + raw + ") -> PhaserBytes", + " pub fn serialize_as_string(&self) -> Vec {\n copy_bytes(unsafe { " + + prefix + "_serialize_as_string(self.ptr) })\n }\n"); + Bind(decl, def, rust_extern_out, rust_body_out, + "uint8_t " + prefix + "_parse_from_string(" + mut_self + + ", const uint8_t* data, size_t len)", + Guard(cpp, false, "return 0;") + + " std::string bytes;\n if (data != nullptr && len != 0) {\n" + " bytes.assign(reinterpret_cast(data), len);\n }\n" + " return h->get()->ParseFromString(bytes) ? static_cast(1)" + " : static_cast(0);\n", + prefix + "_parse_from_string(msg: *mut " + raw + + ", data: *const u8, len: usize) -> u8", + " pub fn parse_from_string(&mut self, bytes: &[u8]) -> bool {\n" + " flag(unsafe { " + + prefix + + "_parse_from_string(self.ptr, phaser_bytes_ptr(bytes), bytes.len()) })\n" + " }\n"); + + for (const auto& field : fields_) { + EmitCField(field->field, decl, def, rust_extern_out, rust_body_out, + declared_types, prefix, cpp, raw); + } + for (const auto& [oneof, info] : unions_) { + const std::string case_cxx = std::string(oneof->name()) + "_case"; + Bind(decl, def, rust_extern_out, rust_body_out, + "int32_t " + prefix + "_" + case_cxx + "(" + const_self + ")", + Guard(cpp, true, "return 0;") + + " return static_cast(h->get()->" + case_cxx + "());\n", + prefix + "_" + case_cxx + "(msg: *const " + raw + ") -> i32", + " pub fn " + RustIdent(case_cxx) + + "(&self) -> i32 {\n unsafe { " + prefix + "_" + case_cxx + + "(self.ptr) }\n }\n"); + for (const auto& member : info->members) { + EmitCField(member->field, decl, def, rust_extern_out, rust_body_out, + declared_types, prefix, cpp, raw); + } + } + + if (rust == nullptr) { + return; + } + *rust << "#[repr(C)]\nstruct " << raw << " {\n _private: [u8; 0],\n}\n\n"; + *rust << "extern \"C\" {\n" << rust_extern.str() << "}\n\n"; + *rust << "pub struct " << rust_name << "<'a> {\n ptr: *mut " << raw + << ",\n _parent: PhantomData<&'a ()>,\n}\n\n"; + *rust << "impl<'a> Drop for " << rust_name << "<'a> {\n"; + *rust << " fn drop(&mut self) {\n if !self.ptr.is_null() {\n"; + *rust << " unsafe { " << prefix << "_free(self.ptr) }\n"; + *rust << " self.ptr = std::ptr::null_mut();\n }\n }\n}\n\n"; + *rust << "impl<'a> " << rust_name << "<'a> {\n" << rust_body.str() << "}\n\n"; +} + +void Generator::GenerateBindings(std::ostream& c_header, std::ostream& c_source, + std::ostream* rust) { + if (frontend_style_ != FrontendStyle::kC) { + return; + } + c_header << "#pragma once\n#include \"phaser/runtime/phaser_c.h\"\n\n"; + c_header << "#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n"; + std::filesystem::path include_path(GeneratedIncludeFilename( + package_name_, target_name_, std::string(file_->name()))); + include_path.replace_extension(".phaser.c.h"); + c_source << "\n#include \"phaser/runtime/phaser_c_handle.h\"\n#include \"" + << include_path.string() << "\"\nextern \"C\" {\n"; + for (int i = 0; i < file_->enum_type_count(); ++i) { + EmitEnum(file_->enum_type(i), c_header, rust); + } + std::vector declared; + for (auto& message : message_gens_) { + message->GenerateBindings(c_header, c_source, rust, &declared); + } + c_header << "\n#ifdef __cplusplus\n}\n#endif\n"; + c_source << "} // extern \"C\"\n"; +} + +} // namespace phaser diff --git a/phaser/docs/phaser_user_guide.md b/phaser/docs/phaser_user_guide.md index 6bb8b8b..0bb2c26 100644 --- a/phaser/docs/phaser_user_guide.md +++ b/phaser/docs/phaser_user_guide.md @@ -19,7 +19,7 @@ protobuf without constructing an intermediate user-facing message. Other features include: 1. Target IDL is proto3, but proto2 is also supported -2. Protobuf-style and ROS-style generated C++ frontends +2. Protobuf, ROS, and C frontends, plus Python and Rust clients 3. Native Phaser, protobuf, and ROS1 wire input/output 4. Direct protobuf-to-ROS and ROS-to-protobuf conversion 5. Fixed, caller-owned, and dynamically growing buffers @@ -32,8 +32,9 @@ Other features include: ## How Phaser works Phaser works as a plugin for the Protocol Buffers compiler (protoc). This means that protoc -does the parsing of the `.proto` files and hands off to Phaser to generate code. Only -C++ output is supported. +does the parsing of the `.proto` files and hands off to Phaser to generate code. +The C++ classes are the implementation. Python, C, and Rust are generated views +of the protobuf-style accessors. The ROS public-field frontend stays C++ only. The default generated frontend looks like the regular C++ protobuf backend, with a few enhancements and minor incompatibilities. The optional ROS frontend @@ -140,7 +141,7 @@ proto_library( phaser_library( name = "foo_phaser", add_namespace = "phaser", - frontend = "protobuf", # Default; use "ros" for public field proxies. + frontend = "protobuf", # Default. "ros" and "c" select the other frontends. enable_active_message = False, deps = [":foo_proto"], ) @@ -225,13 +226,20 @@ The actual command used by Bazel to build the Phaser files is: I haven't done this with `cmake` or any other build system but I guess it will be reasonably easy. -## Protobuf and ROS frontends -`phaser_library` supports two generated C++ interfaces over the same Phaser +## Protobuf, ROS, and C frontends +`phaser_library` supports three generated interfaces over the same Phaser payload layout: - `frontend = "protobuf"` (the default) generates protobuf-style getters and setters. - `frontend = "ros"` generates a struct with public field proxies. +- `frontend = "c"` generates a C API of opaque handles. `rust = True` builds a + Rust crate on that API and selects this frontend when `frontend` is omitted. +- `python = True` builds a pybind11 module over the protobuf frontend. + +Python, C, and Rust are described in [Python, C, and Rust](#python-c-and-rust). +The ROS frontend has no Python, C, or Rust API. `rust = True` cannot be +combined with an explicit protobuf or ROS frontend. ```python phaser_library( @@ -249,7 +257,9 @@ phaser_library( ) ``` -When invoking the plugin directly, pass `frontend=ros` in `--phaser_out`. +When invoking the plugin directly, pass `frontend=ros` or `frontend=c` in +`--phaser_out`. `rust=true` is accepted only with `frontend=c`. +`phaser_library` fills that in when `rust = True` and `frontend` is omitted. Unknown frontend values are rejected. The frontend controls source-level syntax, not wire compatibility: @@ -285,6 +295,185 @@ Both frontends also generate the complete protobuf and ROS1 serialization and wire-to-wire conversion APIs. You do not need the ROS frontend to produce or consume ROS1 wire bytes. +## Python, C, and Rust +Python, C, and Rust expose the protobuf getter and setter API. They do not +expose the ROS public-field frontend, and they do not change the native +payload. A library that wants more than one of these clients declares a +separate `phaser_library` for each. + +The mapping follows the generated C++ accessors: + +- Singular scalars, strings, bytes, and enums: `name()`, `set_name()`, + `has_name()`, and `clear_name()`. A field named `has_` next to + `` uses `_phaser_has_` for presence, same as C++. +- Repeated fields: `name(index)`, `set_name(index, value)`, `add_name(value)`, + `name_size()`, `clear_name()`, `reserve_name()`, and `resize_name()`. +- Singular messages: `name()` and `mutable_name()`. Repeated messages return + the element from `name(index)`, `mutable_name(index)`, and `add_name()`. +- Oneofs: `name_case()` is the selected field number, or `0` when unset. + Setting one arm clears the other. +- Maps are repeated entry messages. A `map values` field is + `add_values()`, then `set_key()` and `set_value()` on the entry. +- `google.protobuf.Any` fields are the shared `AnyMessage` type, with + `type_url` and `value`. That is the runtime any, not a separate generated + class you construct yourself. +- Strings are text. Bytes keep interior zero bytes. +- `ByteSizeLong` (`byte_size_long` in C and Rust) is the native buffer + capacity, not the protobuf wire size. Do not compare it across messages as + if it were a serialized length. + +### Python +`python = True` builds a pybind11 module named `_py` over the protobuf +frontend. The default frontend is already protobuf, so this is enough: + +```python +phaser_library( + name = "foo_phaser", + python = True, + deps = [":foo_proto"], +) +``` + +A `py_binary` or `py_test` that depends on `:foo_phaser_py` imports that +module. Classes use the generated C++ names (`Foo`, and `Foo_ValuesEntry` for +a nested map entry). Enums are pybind11 enums. The constructor takes +`initial_size` and defaults to 8192. + +```python +import foo_phaser_py as phaser + +msg = phaser.Foo() +msg.set_count(3) +msg.set_name("sensor") +assert msg.has_count() +msg.add_samples(1.5) + +child = msg.mutable_child() +child.set_label("cam") +assert msg.child().label() == "cam" + +msg.set_kind(phaser.Kind.CAMERA) +blob = msg.SerializeAsString() # bytes +copy = phaser.Foo(1024) +assert copy.ParseFromString(blob) +print(copy.DebugString()) +copy.Clear() +``` + +String fields are `str`. Bytes fields and serialized buffers are `bytes`. +Nested message objects keep the parent alive. `AnyMessage` has `type_url()`, +`set_type_url()`, `value()`, and `set_value()`; `value` is `bytes`. Enum +aliases that share a number register only the first declared name. +`python = True` with `frontend = "ros"` fails. + +### C +`frontend = "c"` emits `Foo.phaser.c.h` next to the C++ header. Include the C +header. The C++ classes are still in the library; the C functions are the +supported surface. + +```python +phaser_library( + name = "foo_c", + frontend = "c", + deps = [":foo_proto"], +) +``` + +Symbols are `phaser___`. Dots in the package become +underscores. An empty package omits that piece. The added C++ namespace from +`add_namespace` is not part of the C name. For package `foo.bar`, `Foo` is +`phaser_foo_bar_Foo`. Enum constants are `phaser_foo_bar_Kind_CAMERA`. Nested +types use one level of containing name, matching the C++ class: +`phaser_foo_bar_Foo_ValuesEntry`. + +```c +#include "foo/bar/Foo.phaser.c.h" + +phaser_foo_bar_Foo* msg = phaser_foo_bar_Foo_new(8192); +phaser_foo_bar_Foo_set_count(msg, 3); +phaser_foo_bar_Foo_set_name(msg, (const uint8_t*)"sensor", 6); + +PhaserBytes name = phaser_foo_bar_Foo_name(msg); +/* name.data has name.size bytes; free it with phaser_free. */ +phaser_free(name.data); + +phaser_foo_bar_Child* child = phaser_foo_bar_Foo_mutable_child(msg); +phaser_foo_bar_Child_set_label(child, (const uint8_t*)"cam", 3); +phaser_foo_bar_Child_free(child); + +phaser_foo_bar_Foo_free(msg); +``` + +Each returned pointer owns a small heap handle. `_free` deletes that handle. +Freeing a handle from a field accessor does not free the parent. Free those +handles before the pointer from `_new`. `PhaserBytes` owns its `data`; free it +with `phaser_free`. A null `data` pointer is empty. Bool crosses the ABI as +`uint8_t`. Strings and bytes are a pointer plus a length, so interior zeros +survive. Enum arguments and results are `int32_t`. + +`phaser_AnyMessage` is declared in `phaser/runtime/phaser_c.h`. Any fields +return that type. It has no `_new`; take it from `mutable_any` or `any`, then +`phaser_AnyMessage_free` the handle. The generated `google.protobuf.Any` +message, if your library includes that proto, is a separate C type named like +any other message. + +### Rust +`rust = True` builds a crate named `_rs` whose crate name is the target +name with non-alphanumeric characters replaced by `_`. When `frontend` is +omitted, this selects the C frontend: + +```python +load("@rules_rust//rust:defs.bzl", "rust_binary") + +phaser_library( + name = "foo_phaser", + rust = True, + deps = [":foo_proto"], +) + +rust_binary( + name = "demo", + srcs = ["demo.rs"], + edition = "2021", + deps = [":foo_phaser_rs"], +) +``` + +```rust +use foo_phaser::{Foo, Kind}; + +let mut msg = Foo::new(8192); +msg.set_count(3); +msg.set_name("sensor"); +assert!(msg.has_count()); +msg.add_samples(1.5); + +{ + let mut child = msg.mutable_child(); + child.set_label("cam"); +} +assert_eq!(msg.child().label(), "cam"); + +msg.set_kind(Kind::CAMERA); +let blob = msg.serialize_as_string(); +let mut copy = Foo::new(1024); +assert!(copy.parse_from_string(&blob)); +assert!(copy.debug_string().contains("cam")); +copy.clear(); +``` + +`new` returns a `'static` message. Accessors that return a message tie that +handle's lifetime to the borrow of the parent, and `Drop` frees the handle. +End the child borrow before using the parent again. Strings are `String` on +the way out and `&str` on the way in. Bytes are `Vec` and `&[u8]`. Enums +are `struct Kind(pub i32)` with associated constants, so aliases and unknown +values both work. Rust keywords in method names get a trailing `_`. +`AnyMessage` is in the same crate: `set_type_url`, `type_url`, `set_value`, +and `value`. + +Phaser's module registers `rules_rust` for this crate. A downstream Bazel +module that depends on Phaser picks that up through the module graph. + Set `enable_active_message = True` on `phaser_library`, or pass `active_message=true` to the plugin, to add a public `active_message` member to every generated message. This is application-side transient state; it is not diff --git a/phaser/phaser_library.bzl b/phaser/phaser_library.bzl index 5367891..5943770 100644 --- a/phaser/phaser_library.bzl +++ b/phaser/phaser_library.bzl @@ -6,6 +6,7 @@ load("@bazel_skylib//lib:paths.bzl", "paths") load("@com_google_protobuf//bazel/common:proto_info.bzl", "ProtoInfo") load("@pybind11_bazel//:build_defs.bzl", "pybind_extension") load("@rules_cc//cc:defs.bzl", "cc_library") +load("@rules_rust//rust:defs.bzl", "rust_library") MessageInfo = provider(fields = [ "direct_sources", @@ -15,6 +16,8 @@ MessageInfo = provider(fields = [ "python_registers", ]) +PhaserGenInfo = provider(fields = ["rust_files"]) + def _python_register_symbol(base): stem = base[:-len(".proto")] if base.endswith(".proto") else base chars = [] @@ -62,7 +65,8 @@ def _phaser_action( target_name, frontend, enable_active_message, - ros_metadata): + ros_metadata, + rust): # The protobuf compiler allow plugins to get arguments specified in the --plugin_out # argument. The args are passed as a comma separated list of key=value pairs followed # by a colon and the output directory. @@ -76,6 +80,8 @@ def _phaser_action( options.append("active_message=true") if ros_metadata: options.append("ros_metadata=true") + if rust: + options.append("rust=true") options_and_out_dir = "--phaser_out={}:{}".format(",".join(options), out_dir) inputs = depset(direct = direct_sources, transitive = transitive_sources) @@ -225,14 +231,18 @@ phaser_aspect = aspect( # The deps for the rule are proto_libraries that contain the protobuf files. def _phaser_impl(ctx): frontend = ctx.attr.frontend - if frontend not in ("protobuf", "ros"): - fail("phaser_library frontend must be 'protobuf' or 'ros', got: {}".format(frontend)) + if frontend not in ("protobuf", "ros", "c"): + fail("phaser_library frontend must be 'protobuf', 'ros', or 'c', got: {}".format(frontend)) + if ctx.attr.rust and frontend != "c": + fail("phaser_library rust=True requires frontend = \"c\"") outputs = [] direct_sources = [] transitive_sources = [] cpp_outputs = [] + rust_files = [] + seen_extra = {} python_registers = [] seen_registers = {} package_name = ctx.attr.package_name @@ -267,6 +277,35 @@ def _phaser_impl(ctx): ctx.actions.symlink(output = symlink, target_file = out_file) dep_outs.append(symlink) cpp_outputs.append(out_file) + if out.endswith(".phaser.h"): + stem = out[:-len(".phaser.h")] + if frontend == "c": + c_rel = stem + ".phaser.c.h" + if c_rel not in seen_extra: + seen_extra[c_rel] = True + c_file = ctx.actions.declare_file(ctx.attr.target_name + "/" + c_rel) + dep_outs.append(c_file) + cpp_outputs.append(c_file) + if ( + ctx.attr.direct_header_symlinks and + out in dep[MessageInfo].symlink_headers + ): + package_prefix = ctx.label.package + "/" + symlink_name = c_rel + if not ctx.label.package or symlink_name.startswith(package_prefix): + if package_prefix: + symlink_name = symlink_name[len(package_prefix):] + symlink = ctx.actions.declare_file(symlink_name) + ctx.actions.symlink(output = symlink, target_file = c_file) + dep_outs.append(symlink) + if ctx.attr.rust: + rs_rel = stem + ".rs" + if rs_rel not in seen_extra: + seen_extra[rs_rel] = True + rs_file = ctx.actions.declare_file(ctx.attr.target_name + "/" + rs_rel) + dep_outs.append(rs_file) + cpp_outputs.append(rs_file) + rust_files.append(rs_file) direct_sources += dep[MessageInfo].direct_sources transitive_sources.append(dep[MessageInfo].transitive_sources) @@ -288,6 +327,7 @@ def _phaser_impl(ctx): frontend, ctx.attr.enable_active_message, ctx.attr.ros_metadata, + ctx.attr.rust, ) if ctx.attr.python: @@ -301,7 +341,10 @@ def _phaser_impl(ctx): ) outputs.append(umbrella) - return [DefaultInfo(files = depset(outputs))] + return [ + DefaultInfo(files = depset(outputs)), + PhaserGenInfo(rust_files = rust_files), + ] _phaser_gen = rule( attrs = { @@ -325,11 +368,50 @@ _phaser_gen = rule( "frontend": attr.string(default = "protobuf"), "enable_active_message": attr.bool(default = False), "ros_metadata": attr.bool(default = False), + "rust": attr.bool(default = False), "python": attr.bool(default = False), }, implementation = _phaser_impl, ) +def _phaser_rust_crate_impl(ctx): + out = ctx.actions.declare_file(ctx.label.name + ".rs") + parts = [ctx.file.support] + ctx.attr.generated[PhaserGenInfo].rust_files + quoted = [] + for part in parts: + quoted.append("\"%s\"" % part.path) + ctx.actions.run_shell( + inputs = parts, + outputs = [out], + command = "cat %s > \"%s\"" % (" ".join(quoted), out.path), + mnemonic = "PhaserRustCrate", + progress_message = "Assembling Rust crate %s" % ctx.label, + ) + return [DefaultInfo(files = depset([out]))] + +_phaser_rust_crate = rule( + attrs = { + "generated": attr.label(mandatory = True, providers = [PhaserGenInfo]), + "support": attr.label( + default = Label("//phaser/runtime:rust_support.rs"), + allow_single_file = True, + ), + }, + implementation = _phaser_rust_crate_impl, +) + +def _rust_crate_name(name): + ident = "" + for i in range(len(name)): + c = name[i] + if c.isalnum() or c == "_": + ident += c + else: + ident += "_" + if not ident or ident[0].isdigit(): + ident = "_" + ident + return ident + def _split_files_impl(ctx): files = [] for file in ctx.files.deps: @@ -359,11 +441,12 @@ def phaser_library( runtime = "@phaser//phaser/runtime:phaser_runtime", add_namespace = "", enable_active_message = False, - frontend = "protobuf", + frontend = None, cc_deps = [], copts = [], direct_header_symlinks = True, ros_metadata = False, + rust = False, python = False): """ Generate a cc_libary for protobuf files specified in deps. @@ -378,20 +461,27 @@ def phaser_library( `phaser::ActiveMessage active_message` field, which holds a `std::any` (also enableable via the `active_message=true` plugin command-line option). - frontend: generated C++ API style, either "protobuf" (default) or "ros". + frontend: generated API style: "protobuf", "ros", or "c". + Omitted means "c" when rust is True, and "protobuf" otherwise. cc_deps: additional C++ dependencies required by generated headers, such as ROS1 message/runtime libraries for intrinsic ROS fields. copts: additional C++ compiler options for generated sources. direct_header_symlinks: create short direct-source header aliases. Disable this when generating multiple frontends from one proto target. ros_metadata: generate ROS datatype, definition, and MD5 functions. + rust: build a Rust crate named "_rs" over the C API. Selects + frontend "c" when frontend is omitted. python: also build a pybind11 module named `_py`. Messages are exposed with the protobuf getter and setter API (`x`, `set_x`, `has_x`, `clear_x`, and the repeated `add_`/`size` methods). The ROS frontend is not supported. """ - if frontend not in ("protobuf", "ros"): - fail("phaser_library frontend must be 'protobuf' or 'ros', got: {}".format(frontend)) + if frontend == None: + frontend = "c" if rust else "protobuf" + if frontend not in ("protobuf", "ros", "c"): + fail("phaser_library frontend must be 'protobuf', 'ros', or 'c', got: {}".format(frontend)) + if rust and frontend != "c": + fail("phaser_library rust=True requires frontend = \"c\"") if python and frontend != "protobuf": fail("phaser_library python bindings require frontend=protobuf") @@ -415,6 +505,7 @@ def phaser_library( enable_active_message = enable_active_message, frontend = frontend, ros_metadata = ros_metadata, + rust = rust, python = python, ) @@ -443,6 +534,8 @@ def phaser_library( # Generated sources register embedded FileDescriptorProtos with this # library. The descriptor is then available without linking the .pb.cc. libdeps.append(Label("//phaser/runtime:phaser_bank_protobuf")) + if frontend == "c": + libdeps.append(Label("//phaser/runtime:phaser_c")) libdeps = libdeps + cc_deps # PhaserBank entries are registered by static initializers in the generated @@ -457,6 +550,20 @@ def phaser_library( deps = libdeps, ) + if rust: + crate = name + "_rust_crate" + _phaser_rust_crate( + name = crate, + generated = phaser, + ) + rust_library( + name = name + "_rs", + srcs = [":" + crate], + crate_name = _rust_crate_name(name), + edition = "2021", + deps = [":" + name], + ) + if python: py_name = _sanitize_identifier(name + "_py") py_srcs = name + "_py_srcs" diff --git a/phaser/runtime/BUILD.bazel b/phaser/runtime/BUILD.bazel index 60798c1..cae5060 100644 --- a/phaser/runtime/BUILD.bazel +++ b/phaser/runtime/BUILD.bazel @@ -157,6 +157,20 @@ cc_test( ], ) +cc_library( + name = "phaser_c", + srcs = ["phaser_c.cc"], + hdrs = [ + "phaser_c.h", + "phaser_c_handle.h", + ], + alwayslink = True, + copts = PHASER_COPTS, + deps = [":phaser_runtime"], +) + +exports_files(["rust_support.rs"]) + cc_test( name = "arrow_test", srcs = ["arrow_test.cc"], diff --git a/phaser/runtime/phaser_c.cc b/phaser/runtime/phaser_c.cc new file mode 100644 index 0000000..6ce0280 --- /dev/null +++ b/phaser/runtime/phaser_c.cc @@ -0,0 +1,149 @@ +// Copyright 2024-2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "phaser/runtime/phaser_c_handle.h" + +#include +#include +#include + +namespace { + +::phaser::AnyMessage* MutableAny(phaser_AnyMessage* msg) { + auto* handle = ::phaser::capi::AsHandle<::phaser::AnyMessage>(msg); + if (handle == nullptr) { + return nullptr; + } + return handle->get(); +} + +const ::phaser::AnyMessage* ConstAny(const phaser_AnyMessage* msg) { + auto* handle = ::phaser::capi::AsHandle<::phaser::AnyMessage>(msg); + if (handle == nullptr) { + return nullptr; + } + return handle->get(); +} + +uint8_t Flag(bool value) { + return value ? static_cast(1) : static_cast(0); +} + +} // namespace + +namespace phaser::capi { + +PhaserBytes Copy(std::string_view bytes) { + PhaserBytes out{nullptr, size_t{0}}; + if (bytes.empty()) { + return out; + } + void* memory = std::malloc(bytes.size()); + if (memory == nullptr) { + return out; + } + out.data = static_cast(memory); + std::memcpy(out.data, bytes.data(), bytes.size()); + out.size = bytes.size(); + return out; +} + +} // namespace phaser::capi + +extern "C" { + +void phaser_free(void* p) { std::free(p); } + +void phaser_AnyMessage_free(phaser_AnyMessage* msg) { + ::phaser::capi::FreeHandle<::phaser::AnyMessage>(msg); +} + +void phaser_AnyMessage_clear(phaser_AnyMessage* msg) { + if (::phaser::AnyMessage* any = MutableAny(msg)) { + any->Clear(); + } +} + +void phaser_AnyMessage_set_type_url(phaser_AnyMessage* msg, const uint8_t* data, + size_t len) { + if (::phaser::AnyMessage* any = MutableAny(msg)) { + any->set_type_url(::phaser::capi::Bytes(data, len)); + } +} + +PhaserBytes phaser_AnyMessage_type_url(const phaser_AnyMessage* msg) { + const ::phaser::AnyMessage* any = ConstAny(msg); + if (any == nullptr) { + return PhaserBytes{nullptr, size_t{0}}; + } + return ::phaser::capi::Copy(any->type_url()); +} + +uint8_t phaser_AnyMessage_has_type_url(const phaser_AnyMessage* msg) { + const ::phaser::AnyMessage* any = ConstAny(msg); + return any == nullptr ? static_cast(0) : Flag(any->has_type_url()); +} + +void phaser_AnyMessage_clear_type_url(phaser_AnyMessage* msg) { + if (::phaser::AnyMessage* any = MutableAny(msg)) { + any->clear_type_url(); + } +} + +void phaser_AnyMessage_set_value(phaser_AnyMessage* msg, const uint8_t* data, + size_t len) { + if (::phaser::AnyMessage* any = MutableAny(msg)) { + any->set_value(::phaser::capi::Bytes(data, len)); + } +} + +PhaserBytes phaser_AnyMessage_value(const phaser_AnyMessage* msg) { + const ::phaser::AnyMessage* any = ConstAny(msg); + if (any == nullptr) { + return PhaserBytes{nullptr, size_t{0}}; + } + return ::phaser::capi::Copy(any->value()); +} + +uint8_t phaser_AnyMessage_has_value(const phaser_AnyMessage* msg) { + const ::phaser::AnyMessage* any = ConstAny(msg); + return any == nullptr ? static_cast(0) : Flag(any->has_value()); +} + +void phaser_AnyMessage_clear_value(phaser_AnyMessage* msg) { + if (::phaser::AnyMessage* any = MutableAny(msg)) { + any->clear_value(); + } +} + +PhaserBytes phaser_AnyMessage_serialize_as_string(const phaser_AnyMessage* msg) { + const ::phaser::AnyMessage* any = ConstAny(msg); + if (any == nullptr) { + return PhaserBytes{nullptr, size_t{0}}; + } + return ::phaser::capi::Copy(any->SerializeAsString()); +} + +uint8_t phaser_AnyMessage_parse_from_string(phaser_AnyMessage* msg, + const uint8_t* data, size_t len) { + ::phaser::AnyMessage* any = MutableAny(msg); + if (any == nullptr) { + return static_cast(0); + } + std::string bytes; + if (data != nullptr && len != 0) { + bytes.assign(reinterpret_cast(data), len); + } + return Flag(any->ParseFromString(bytes)); +} + +size_t phaser_AnyMessage_byte_size_long(const phaser_AnyMessage* msg) { + const ::phaser::AnyMessage* any = ConstAny(msg); + if (any == nullptr) { + return 0; + } + return any->ZeroCopySize(); +} + +} // extern "C" diff --git a/phaser/runtime/phaser_c.h b/phaser/runtime/phaser_c.h new file mode 100644 index 0000000..b4813b0 --- /dev/null +++ b/phaser/runtime/phaser_c.h @@ -0,0 +1,50 @@ +// Copyright 2024-2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// C frontend shared types. Generated message headers include this. +// +// A message pointer owns a small handle. Free it with the matching _free +// function. Freeing a handle returned by a field accessor does not free the +// parent. Free the pointer from _new last, after those handles. +// PhaserBytes owns its data. Free data with phaser_free. A null data pointer +// is an empty buffer. + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PhaserBytes { + uint8_t* data; + size_t size; +} PhaserBytes; + +void phaser_free(void* p); + +typedef struct phaser_AnyMessage phaser_AnyMessage; + +void phaser_AnyMessage_free(phaser_AnyMessage* msg); +void phaser_AnyMessage_clear(phaser_AnyMessage* msg); +void phaser_AnyMessage_set_type_url(phaser_AnyMessage* msg, const uint8_t* data, + size_t len); +PhaserBytes phaser_AnyMessage_type_url(const phaser_AnyMessage* msg); +uint8_t phaser_AnyMessage_has_type_url(const phaser_AnyMessage* msg); +void phaser_AnyMessage_clear_type_url(phaser_AnyMessage* msg); +void phaser_AnyMessage_set_value(phaser_AnyMessage* msg, const uint8_t* data, + size_t len); +PhaserBytes phaser_AnyMessage_value(const phaser_AnyMessage* msg); +uint8_t phaser_AnyMessage_has_value(const phaser_AnyMessage* msg); +void phaser_AnyMessage_clear_value(phaser_AnyMessage* msg); +PhaserBytes phaser_AnyMessage_serialize_as_string(const phaser_AnyMessage* msg); +uint8_t phaser_AnyMessage_parse_from_string(phaser_AnyMessage* msg, + const uint8_t* data, size_t len); +size_t phaser_AnyMessage_byte_size_long(const phaser_AnyMessage* msg); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/phaser/runtime/phaser_c_handle.h b/phaser/runtime/phaser_c_handle.h new file mode 100644 index 0000000..5f8d3b1 --- /dev/null +++ b/phaser/runtime/phaser_c_handle.h @@ -0,0 +1,103 @@ +// Copyright 2024-2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// Heap handle used by the C frontend. view_ is destroyed before the message +// objects it points into. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "phaser/runtime/any.h" +#include "phaser/runtime/phaser_c.h" + +namespace phaser::capi { + +struct NewMessage {}; + +template +class Handle { + public: + explicit Handle(NewMessage /*tag*/, size_t initial_size) + : owned_(std::in_place, initial_size) { + view_ = &*owned_; + } + explicit Handle(Msg* view) : view_(view) {} + explicit Handle(Msg owned) : owned_value_(std::move(owned)) { + view_ = &*owned_value_; + } + Handle(const Handle&) = delete; + Handle& operator=(const Handle&) = delete; + Handle(Handle&&) = delete; + Handle& operator=(Handle&&) = delete; + + Msg* get() const { return view_; } + + private: + std::optional owned_; + std::optional owned_value_; + Msg* view_ = nullptr; +}; + +template +Handle* AsHandle(Opaque* msg) { + return reinterpret_cast*>(msg); +} + +template +const Handle* AsHandle(const Opaque* msg) { + return reinterpret_cast*>(msg); +} + +template +Opaque* BoxNew(size_t initial_size) { + try { + return reinterpret_cast( + new Handle(NewMessage{}, initial_size)); + } catch (...) { + return nullptr; + } +} + +template +Opaque* BoxView(Msg* view) { + if (view == nullptr) { + return nullptr; + } + try { + return reinterpret_cast(new Handle(view)); + } catch (...) { + return nullptr; + } +} + +template +Opaque* BoxValue(Msg owned) { + try { + return reinterpret_cast(new Handle(std::move(owned))); + } catch (...) { + return nullptr; + } +} + +template +void FreeHandle(Opaque* msg) { + delete AsHandle(msg); +} + +inline std::string_view Bytes(const uint8_t* data, size_t len) { + if (data == nullptr || len == 0) { + return std::string_view(); + } + return std::string_view(reinterpret_cast(data), len); +} + +PhaserBytes Copy(std::string_view bytes); + +} // namespace phaser::capi diff --git a/phaser/runtime/rust_support.rs b/phaser/runtime/rust_support.rs new file mode 100644 index 0000000..7ef0834 --- /dev/null +++ b/phaser/runtime/rust_support.rs @@ -0,0 +1,155 @@ +#![allow( + non_camel_case_types, + non_snake_case, + non_upper_case_globals, + dead_code +)] + +use std::marker::PhantomData; + +#[repr(C)] +struct PhaserBytes { + data: *mut u8, + size: usize, +} + +#[repr(C)] +struct RawAnyMessage { + _private: [u8; 0], +} + +extern "C" { + fn phaser_free(p: *mut u8); + fn phaser_AnyMessage_free(msg: *mut RawAnyMessage); + fn phaser_AnyMessage_clear(msg: *mut RawAnyMessage); + fn phaser_AnyMessage_set_type_url(msg: *mut RawAnyMessage, data: *const u8, len: usize); + fn phaser_AnyMessage_type_url(msg: *const RawAnyMessage) -> PhaserBytes; + fn phaser_AnyMessage_has_type_url(msg: *const RawAnyMessage) -> u8; + fn phaser_AnyMessage_clear_type_url(msg: *mut RawAnyMessage); + fn phaser_AnyMessage_set_value(msg: *mut RawAnyMessage, data: *const u8, len: usize); + fn phaser_AnyMessage_value(msg: *const RawAnyMessage) -> PhaserBytes; + fn phaser_AnyMessage_has_value(msg: *const RawAnyMessage) -> u8; + fn phaser_AnyMessage_clear_value(msg: *mut RawAnyMessage); + fn phaser_AnyMessage_serialize_as_string(msg: *const RawAnyMessage) -> PhaserBytes; + fn phaser_AnyMessage_parse_from_string( + msg: *mut RawAnyMessage, + data: *const u8, + len: usize, + ) -> u8; + fn phaser_AnyMessage_byte_size_long(msg: *const RawAnyMessage) -> usize; +} + +fn flag(value: u8) -> bool { + value != 0 +} + +fn rust_ptr(ptr: *mut T) -> *mut T { + assert!(!ptr.is_null(), "phaser C call failed"); + ptr +} + +fn phaser_bytes_ptr(bytes: &[u8]) -> *const u8 { + if bytes.is_empty() { + std::ptr::null() + } else { + bytes.as_ptr() + } +} + +fn take_bytes(buf: PhaserBytes) -> Vec { + let out = if buf.data.is_null() || buf.size == 0 { + Vec::new() + } else { + unsafe { std::slice::from_raw_parts(buf.data, buf.size) }.to_vec() + }; + if !buf.data.is_null() { + unsafe { phaser_free(buf.data) } + } + out +} + +fn copy_bytes(buf: PhaserBytes) -> Vec { + take_bytes(buf) +} + +fn copy_string(buf: PhaserBytes) -> String { + let bytes = take_bytes(buf); + match String::from_utf8(bytes) { + Ok(text) => text, + Err(err) => String::from_utf8_lossy(err.as_bytes()).into_owned(), + } +} + +pub struct AnyMessage<'a> { + ptr: *mut RawAnyMessage, + _parent: PhantomData<&'a ()>, +} + +impl<'a> Drop for AnyMessage<'a> { + fn drop(&mut self) { + if !self.ptr.is_null() { + unsafe { phaser_AnyMessage_free(self.ptr) } + self.ptr = std::ptr::null_mut(); + } + } +} + +impl<'a> AnyMessage<'a> { + fn from_raw(ptr: *mut RawAnyMessage) -> AnyMessage<'a> { + AnyMessage { + ptr: rust_ptr(ptr), + _parent: PhantomData, + } + } + + pub fn clear(&mut self) { + unsafe { phaser_AnyMessage_clear(self.ptr) } + } + + pub fn set_type_url(&mut self, value: &str) { + let bytes = value.as_bytes(); + unsafe { phaser_AnyMessage_set_type_url(self.ptr, phaser_bytes_ptr(bytes), bytes.len()) } + } + + pub fn type_url(&self) -> String { + copy_string(unsafe { phaser_AnyMessage_type_url(self.ptr) }) + } + + pub fn has_type_url(&self) -> bool { + flag(unsafe { phaser_AnyMessage_has_type_url(self.ptr) }) + } + + pub fn clear_type_url(&mut self) { + unsafe { phaser_AnyMessage_clear_type_url(self.ptr) } + } + + pub fn set_value(&mut self, value: &[u8]) { + unsafe { phaser_AnyMessage_set_value(self.ptr, phaser_bytes_ptr(value), value.len()) } + } + + pub fn value(&self) -> Vec { + copy_bytes(unsafe { phaser_AnyMessage_value(self.ptr) }) + } + + pub fn has_value(&self) -> bool { + flag(unsafe { phaser_AnyMessage_has_value(self.ptr) }) + } + + pub fn clear_value(&mut self) { + unsafe { phaser_AnyMessage_clear_value(self.ptr) } + } + + pub fn serialize_as_string(&self) -> Vec { + copy_bytes(unsafe { phaser_AnyMessage_serialize_as_string(self.ptr) }) + } + + pub fn parse_from_string(&mut self, bytes: &[u8]) -> bool { + flag(unsafe { + phaser_AnyMessage_parse_from_string(self.ptr, phaser_bytes_ptr(bytes), bytes.len()) + }) + } + + pub fn byte_size_long(&self) -> usize { + unsafe { phaser_AnyMessage_byte_size_long(self.ptr) } + } +} diff --git a/phaser/testdata/BUILD b/phaser/testdata/BUILD index 655246c..e1dc9d1 100644 --- a/phaser/testdata/BUILD +++ b/phaser/testdata/BUILD @@ -1,12 +1,20 @@ load("@com_google_protobuf//bazel:cc_proto_library.bzl", "cc_proto_library") load("@com_google_protobuf//bazel:proto_library.bzl", "proto_library") -load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") +load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") load("@rules_python//python:defs.bzl", "py_test") +load("@rules_rust//rust:defs.bzl", "rust_test") load("@rules_shell//shell:sh_test.bzl", "sh_test") load("//phaser:phaser_library.bzl", "phaser_library") package(default_visibility = ["//visibility:public"]) +# Set by build:asan in .bazelrc. rust_test's platform transition ignores +# --test_tag_filters, so the Rust test uses this to stay out of ASan builds. +config_setting( + name = "asan", + define_values = {"asan": "1"}, +) + # libFuzzer regression inputs from CreateReadonly ASan crashes. exports_files([ "fuzz_crash_union_int64.bin", @@ -83,6 +91,47 @@ py_test( deps = ["@rules_python//python/runfiles"], ) +phaser_library( + name = "test_message_c_phaser", + add_namespace = "c_api", + # test_message_phaser owns the short TestMessage.phaser.h symlink. + direct_header_symlinks = False, + rust = True, + runtime = "//phaser/runtime:phaser_runtime", + deps = [":test_message_proto"], +) + +cc_test( + name = "phaser_c_api_test", + srcs = ["c_api_test.c"], + # Valgrind looks up phaser/valgrind.supp from the test runfiles. + data = ["//phaser:valgrind.supp"], + deps = [":test_message_c_phaser"], +) + +rust_test( + name = "phaser_rust_test", + srcs = ["rust_test.rs"], + crate_name = "phaser_rust_test", + data = ["//phaser:valgrind.supp"], + edition = "2021", + # rustc links libc before the C++ archives. On Linux, protobuf's port.o + # references atexit, so libc has to be named again at the end. + # rustc also does not link the ASan runtime for sanitized C++ objects, and + # the rust_test platform transition ignores --test_tag_filters, so this + # target is incompatible under --config=asan. The C API test still runs. + rustc_flags = select({ + "@platforms//os:linux": ["-Clink-arg=-lc"], + "//conditions:default": [], + }), + tags = ["no-asan"], + target_compatible_with = select({ + ":asan": ["@platforms//:incompatible"], + "//conditions:default": [], + }), + deps = [":test_message_c_phaser_rs"], +) + phaser_library( name = "test_phaser", add_namespace = "phaser", diff --git a/phaser/testdata/c_api_test.c b/phaser/testdata/c_api_test.c new file mode 100644 index 0000000..090229c --- /dev/null +++ b/phaser/testdata/c_api_test.c @@ -0,0 +1,203 @@ +#include "phaser/testdata/test_message_c_phaser/phaser/testdata/TestMessage.phaser.c.h" + +#include +#include +#include + +static int contains(PhaserBytes text, const char* needle) { + const size_t n = strlen(needle); + if (text.data == NULL || text.size < n) { + return 0; + } + for (size_t i = 0; i + n <= text.size; ++i) { + if (memcmp(text.data + i, needle, n) == 0) { + return 1; + } + } + return 0; +} + +static int bytes_eq(PhaserBytes got, const uint8_t* want, size_t len) { + return got.size == len && (len == 0 || memcmp(got.data, want, len) == 0); +} + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #cond); \ + return 1; \ + } \ + } while (0) + +int main(void) { + phaser_foo_bar_TestMessage* msg = phaser_foo_bar_TestMessage_new(8192); + CHECK(msg != NULL); + CHECK(!phaser_foo_bar_TestMessage_has_x(msg)); + phaser_foo_bar_TestMessage_set_x(msg, 0); + CHECK(phaser_foo_bar_TestMessage_has_x(msg)); + CHECK(phaser_foo_bar_TestMessage_x(msg) == 0); + phaser_foo_bar_TestMessage_clear_x(msg); + CHECK(!phaser_foo_bar_TestMessage_has_x(msg)); + + phaser_foo_bar_TestMessage_set_y(msg, -5); + phaser_foo_bar_TestMessage_set_s(msg, (const uint8_t*)"hi", 2); + const uint8_t raw_buf[] = {'a', 0, 'b'}; + phaser_foo_bar_TestMessage_set_buffer(msg, raw_buf, 3); + phaser_foo_bar_TestMessage_set_e(msg, phaser_foo_bar_EnumTest_FOO); + phaser_foo_bar_TestMessage_set_fl(msg, 1.5f); + phaser_foo_bar_TestMessage_set_db(msg, 2.5); + CHECK(phaser_foo_bar_TestMessage_y(msg) == -5); + PhaserBytes s = phaser_foo_bar_TestMessage_s(msg); + CHECK(bytes_eq(s, (const uint8_t*)"hi", 2)); + phaser_free(s.data); + PhaserBytes buffer = phaser_foo_bar_TestMessage_buffer(msg); + CHECK(bytes_eq(buffer, raw_buf, 3)); + phaser_free(buffer.data); + CHECK(phaser_foo_bar_TestMessage_e(msg) == phaser_foo_bar_EnumTest_FOO); + CHECK(phaser_foo_bar_TestMessage_has_e(msg)); + CHECK(phaser_foo_bar_TestMessage_fl(msg) == 1.5f); + CHECK(phaser_foo_bar_TestMessage_db(msg) == 2.5); + + phaser_foo_bar_TestMessage_add_vi32(msg, 3); + phaser_foo_bar_TestMessage_add_vi32(msg, 4); + phaser_foo_bar_TestMessage_set_vi32(msg, 1, 9); + CHECK(phaser_foo_bar_TestMessage_vi32_size(msg) == 2); + CHECK(phaser_foo_bar_TestMessage_vi32(msg, 0) == 3); + CHECK(phaser_foo_bar_TestMessage_vi32(msg, 1) == 9); + phaser_foo_bar_TestMessage_add_vstr(msg, (const uint8_t*)"ab", 2); + phaser_foo_bar_TestMessage_set_vstr(msg, 0, (const uint8_t*)"z", 1); + s = phaser_foo_bar_TestMessage_vstr(msg, 0); + CHECK(bytes_eq(s, (const uint8_t*)"z", 1)); + phaser_free(s.data); + + phaser_foo_bar_InnerMessage* nested = phaser_foo_bar_TestMessage_mutable_m(msg); + CHECK(nested != NULL); + phaser_foo_bar_InnerMessage_set_str(nested, (const uint8_t*)"nested", 6); + phaser_foo_bar_InnerMessage_set_f(nested, -2); + phaser_foo_bar_InnerMessage_add_ev(nested, phaser_foo_bar_EnumTest_BAR); + phaser_foo_bar_InnerMessage_free(nested); + CHECK(phaser_foo_bar_TestMessage_has_m(msg)); + nested = phaser_foo_bar_TestMessage_m(msg); + s = phaser_foo_bar_InnerMessage_str(nested); + CHECK(bytes_eq(s, (const uint8_t*)"nested", 6)); + phaser_free(s.data); + CHECK(phaser_foo_bar_InnerMessage_f(nested) == -2); + CHECK(phaser_foo_bar_InnerMessage_ev(nested, 0) == phaser_foo_bar_EnumTest_BAR); + phaser_foo_bar_InnerMessage_free(nested); + + phaser_foo_bar_InnerMessage* child = phaser_foo_bar_TestMessage_add_vm(msg); + phaser_foo_bar_InnerMessage_set_str(child, (const uint8_t*)"e0", 2); + phaser_foo_bar_InnerMessage_free(child); + child = phaser_foo_bar_TestMessage_mutable_vm(msg, 0); + phaser_foo_bar_InnerMessage_set_str(child, (const uint8_t*)"e1", 2); + phaser_foo_bar_InnerMessage_free(child); + CHECK(phaser_foo_bar_TestMessage_vm_size(msg) == 1); + child = phaser_foo_bar_TestMessage_vm(msg, 0); + s = phaser_foo_bar_InnerMessage_str(child); + CHECK(bytes_eq(s, (const uint8_t*)"e1", 2)); + phaser_free(s.data); + phaser_foo_bar_InnerMessage_free(child); + + CHECK(phaser_foo_bar_TestMessage_u1_case(msg) == 0); + phaser_foo_bar_TestMessage_set_u1a(msg, 7); + CHECK(phaser_foo_bar_TestMessage_u1_case(msg) == 107); + CHECK(phaser_foo_bar_TestMessage_u1a(msg) == 7); + CHECK(phaser_foo_bar_TestMessage_has_u1a(msg)); + phaser_foo_bar_TestMessage_set_u1b(msg, 8); + CHECK(phaser_foo_bar_TestMessage_u1_case(msg) == 108); + CHECK(!phaser_foo_bar_TestMessage_has_u1a(msg)); + CHECK(phaser_foo_bar_TestMessage_u1b(msg) == 8); + + phaser_foo_bar_TestMessage_set_u2b(msg, (const uint8_t*)"zz", 2); + CHECK(phaser_foo_bar_TestMessage_u2_case(msg) == 110); + s = phaser_foo_bar_TestMessage_u2b(msg); + CHECK(bytes_eq(s, (const uint8_t*)"zz", 2)); + phaser_free(s.data); + phaser_foo_bar_TestMessage_set_u2a(msg, 5); + CHECK(phaser_foo_bar_TestMessage_u2_case(msg) == 109); + CHECK(!phaser_foo_bar_TestMessage_has_u2b(msg)); + CHECK(phaser_foo_bar_TestMessage_u2a(msg) == 5); + + phaser_foo_bar_InnerMessage* arm = phaser_foo_bar_TestMessage_mutable_u3b(msg); + phaser_foo_bar_InnerMessage_set_str(arm, (const uint8_t*)"arm", 3); + phaser_foo_bar_InnerMessage_free(arm); + CHECK(phaser_foo_bar_TestMessage_u3_case(msg) == 112); + arm = phaser_foo_bar_TestMessage_u3b(msg); + s = phaser_foo_bar_InnerMessage_str(arm); + CHECK(bytes_eq(s, (const uint8_t*)"arm", 3)); + phaser_free(s.data); + phaser_foo_bar_InnerMessage_free(arm); + + phaser_foo_bar_TestMessage_ValuesEntry* entry = + phaser_foo_bar_TestMessage_add_values(msg); + phaser_foo_bar_TestMessage_ValuesEntry_set_key(entry, (const uint8_t*)"k", 1); + phaser_foo_bar_TestMessage_ValuesEntry_set_value(entry, 3); + phaser_foo_bar_TestMessage_ValuesEntry_free(entry); + CHECK(phaser_foo_bar_TestMessage_values_size(msg) == 1); + entry = phaser_foo_bar_TestMessage_values(msg, 0); + s = phaser_foo_bar_TestMessage_ValuesEntry_key(entry); + CHECK(bytes_eq(s, (const uint8_t*)"k", 1)); + phaser_free(s.data); + CHECK(phaser_foo_bar_TestMessage_ValuesEntry_value(entry) == 3); + phaser_foo_bar_TestMessage_ValuesEntry_free(entry); + + CHECK(!phaser_foo_bar_TestMessage_has_any(msg)); + const char* type_url = "type.googleapis.com/foo.bar.InnerMessage"; + phaser_AnyMessage* packed = phaser_foo_bar_TestMessage_mutable_any(msg); + phaser_AnyMessage_set_type_url(packed, (const uint8_t*)type_url, strlen(type_url)); + const uint8_t any_value[] = {0, 1}; + phaser_AnyMessage_set_value(packed, any_value, 2); + CHECK(phaser_foo_bar_TestMessage_has_any(msg)); + s = phaser_AnyMessage_type_url(packed); + CHECK(bytes_eq(s, (const uint8_t*)type_url, strlen(type_url))); + phaser_free(s.data); + buffer = phaser_AnyMessage_value(packed); + CHECK(bytes_eq(buffer, any_value, 2)); + phaser_free(buffer.data); + phaser_AnyMessage_free(packed); + + CHECK(phaser_foo_bar_TestMessage_byte_size_long(msg) > 0); + PhaserBytes debug = phaser_foo_bar_TestMessage_debug_string(msg); + CHECK(contains(debug, "nested")); + phaser_free(debug.data); + PhaserBytes blob = phaser_foo_bar_TestMessage_serialize_as_string(msg); + phaser_foo_bar_TestMessage* copy = phaser_foo_bar_TestMessage_new(1024); + CHECK(phaser_foo_bar_TestMessage_parse_from_string(copy, blob.data, blob.size)); + phaser_free(blob.data); + s = phaser_foo_bar_TestMessage_s(copy); + CHECK(bytes_eq(s, (const uint8_t*)"hi", 2)); + phaser_free(s.data); + buffer = phaser_foo_bar_TestMessage_buffer(copy); + CHECK(bytes_eq(buffer, raw_buf, 3)); + phaser_free(buffer.data); + CHECK(phaser_foo_bar_TestMessage_e(copy) == phaser_foo_bar_EnumTest_FOO); + nested = phaser_foo_bar_TestMessage_m(copy); + s = phaser_foo_bar_InnerMessage_str(nested); + CHECK(bytes_eq(s, (const uint8_t*)"nested", 6)); + phaser_free(s.data); + phaser_foo_bar_InnerMessage_free(nested); + child = phaser_foo_bar_TestMessage_vm(copy, 0); + s = phaser_foo_bar_InnerMessage_str(child); + CHECK(bytes_eq(s, (const uint8_t*)"e1", 2)); + phaser_free(s.data); + phaser_foo_bar_InnerMessage_free(child); + entry = phaser_foo_bar_TestMessage_values(copy, 0); + s = phaser_foo_bar_TestMessage_ValuesEntry_key(entry); + CHECK(bytes_eq(s, (const uint8_t*)"k", 1)); + phaser_free(s.data); + phaser_foo_bar_TestMessage_ValuesEntry_free(entry); + packed = phaser_foo_bar_TestMessage_any(copy); + s = phaser_AnyMessage_type_url(packed); + CHECK(bytes_eq(s, (const uint8_t*)type_url, strlen(type_url))); + phaser_free(s.data); + phaser_AnyMessage_free(packed); + CHECK(phaser_foo_bar_TestMessage_byte_size_long(copy) > 0); + phaser_foo_bar_TestMessage_clear(copy); + CHECK(!phaser_foo_bar_TestMessage_has_s(copy)); + CHECK(phaser_foo_bar_TestMessage_vstr_size(copy) == 0); + CHECK(!phaser_foo_bar_TestMessage_has_any(copy)); + + phaser_foo_bar_TestMessage_free(copy); + phaser_foo_bar_TestMessage_free(msg); + return 0; +} diff --git a/phaser/testdata/rust_test.rs b/phaser/testdata/rust_test.rs new file mode 100644 index 0000000..80e42af --- /dev/null +++ b/phaser/testdata/rust_test.rs @@ -0,0 +1,121 @@ +use test_message_c_phaser::{EnumTest, TestMessage}; + +#[test] +fn getters_setters_and_round_trip() { + let mut msg = TestMessage::new(8192); + assert!(!msg.has_x()); + msg.set_x(0); + assert!(msg.has_x()); + assert_eq!(msg.x(), 0); + msg.clear_x(); + assert!(!msg.has_x()); + + msg.set_y(-5i64); + msg.set_s("hi"); + msg.set_buffer(b"a\0b"); + msg.set_e(EnumTest::FOO); + msg.set_fl(1.5f32); + msg.set_db(2.5); + assert_eq!(msg.y(), -5i64); + assert_eq!(msg.s(), "hi"); + assert_eq!(msg.buffer(), b"a\0b"); + assert_eq!(msg.e(), EnumTest::FOO); + assert!(msg.has_e()); + assert_eq!(msg.fl(), 1.5f32); + assert_eq!(msg.db(), 2.5); + + msg.add_vi32(3); + msg.add_vi32(4); + msg.set_vi32(1, 9); + assert_eq!(msg.vi32_size(), 2); + assert_eq!(msg.vi32(0), 3); + assert_eq!(msg.vi32(1), 9); + msg.add_vstr("ab"); + msg.set_vstr(0, "z"); + assert_eq!(msg.vstr(0), "z"); + + { + let mut nested = msg.mutable_m(); + nested.set_str("nested"); + nested.set_f(-2i64); + nested.add_ev(EnumTest::BAR); + } + assert!(msg.has_m()); + assert_eq!(msg.m().str(), "nested"); + assert_eq!(msg.m().f(), -2i64); + assert_eq!(msg.m().ev(0), EnumTest::BAR); + + { + let mut child = msg.add_vm(); + child.set_str("e0"); + } + msg.mutable_vm(0).set_str("e1"); + assert_eq!(msg.vm_size(), 1); + assert_eq!(msg.vm(0).str(), "e1"); + + assert_eq!(msg.u1_case(), 0); + msg.set_u1a(7u32); + assert_eq!(msg.u1_case(), 107); + assert_eq!(msg.u1a(), 7u32); + assert!(msg.has_u1a()); + msg.set_u1b(8u64); + assert_eq!(msg.u1_case(), 108); + assert!(!msg.has_u1a()); + assert_eq!(msg.u1b(), 8u64); + + msg.set_u2b("zz"); + assert_eq!(msg.u2_case(), 110); + assert_eq!(msg.u2b(), "zz"); + msg.set_u2a(5i64); + assert_eq!(msg.u2_case(), 109); + assert!(!msg.has_u2b()); + assert_eq!(msg.u2a(), 5i64); + + { + let mut arm = msg.mutable_u3b(); + arm.set_str("arm"); + } + assert_eq!(msg.u3_case(), 112); + assert_eq!(msg.u3b().str(), "arm"); + + { + let mut entry = msg.add_values(); + entry.set_key("k"); + entry.set_value(3); + } + assert_eq!(msg.values_size(), 1); + assert_eq!(msg.values(0).key(), "k"); + assert_eq!(msg.values(0).value(), 3); + + assert!(!msg.has_any()); + let type_url = { + let mut packed = msg.mutable_any(); + packed.set_type_url("type.googleapis.com/foo.bar.InnerMessage"); + packed.set_value(&[0, 1]); + assert_eq!( + packed.type_url(), + "type.googleapis.com/foo.bar.InnerMessage" + ); + assert_eq!(packed.value(), &[0, 1]); + packed.type_url() + }; + assert!(msg.has_any()); + + assert!(msg.byte_size_long() > 0); + assert!(msg.debug_string().contains("nested")); + let blob = msg.serialize_as_string(); + let mut copy = TestMessage::new(1024); + assert!(copy.parse_from_string(&blob)); + assert_eq!(copy.s(), "hi"); + assert_eq!(copy.buffer(), b"a\0b"); + assert_eq!(copy.e(), EnumTest::FOO); + assert_eq!(copy.m().str(), "nested"); + assert_eq!(copy.vm(0).str(), "e1"); + assert_eq!(copy.values(0).key(), "k"); + assert_eq!(copy.any().type_url(), type_url); + assert!(copy.byte_size_long() > 0); + copy.clear(); + assert!(!copy.has_s()); + assert_eq!(copy.vstr_size(), 0); + assert!(!copy.has_any()); +}