Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .bazelrc
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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")
7 changes: 6 additions & 1 deletion MODULE.bazel.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

57 changes: 46 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)**.

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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"],
)
Expand All @@ -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(
Expand All @@ -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 `<name>_py` over the protobuf accessors. `frontend = "c"` emits `Foo.phaser.c.h`. `rust = True` builds a crate named `<name>_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"
Expand Down Expand Up @@ -538,8 +572,8 @@ accessor, so that presence accessor is named `_phaser_has_<name>()` 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). |
Expand All @@ -548,6 +582,7 @@ accessor, so that presence accessor is named `_phaser_has_<name>()` 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).
Expand Down
1 change: 1 addition & 0 deletions phaser/compiler/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
70 changes: 66 additions & 4 deletions phaser/compiler/gen.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <fstream>
#include <functional>
#include <set>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>
Expand Down Expand Up @@ -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<google::protobuf::io::ZeroCopyOutputStream> 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) {
Expand Down Expand Up @@ -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_);
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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");
Expand Down
10 changes: 7 additions & 3 deletions phaser/compiler/gen.h
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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:
Expand All @@ -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);

Expand Down
18 changes: 17 additions & 1 deletion phaser/compiler/message_gen.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

namespace phaser {

enum class FrontendStyle { kProtobuf, kRos };
enum class FrontendStyle { kProtobuf, kRos, kC };

struct FieldInfo {
// Constructor.
Expand Down Expand Up @@ -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<std::string>* 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);
Expand Down Expand Up @@ -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<std::string>* 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<std::unique_ptr<MessageGenerator>> nested_message_gens_;
Expand Down
Loading
Loading