Skip to content

Commit

Permalink
use quote to generate code
Browse files Browse the repository at this point in the history
  • Loading branch information
pompon0 committed Nov 8, 2023
1 parent 3598b33 commit 2c9fb49
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 24 deletions.
1 change: 1 addition & 0 deletions node/Cargo.lock

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

1 change: 1 addition & 0 deletions node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ protox-parse = "0.5.0"
prettyplease = "0.2.6"
pretty_assertions = "1.4.0"
quick-protobuf = "0.8.1"
quote = "1.0.33"
rand = "0.8.0"
rocksdb = "0.21.0"
serde = { version = "1.0", features = ["derive"] }
Expand Down
1 change: 1 addition & 0 deletions node/libs/protobuf_build/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ prost-types.workspace = true
prost-reflect.workspace = true
protox.workspace = true
protox-parse.workspace = true
quote.workspace = true
rand.workspace = true
syn.workspace = true

41 changes: 24 additions & 17 deletions node/libs/protobuf_build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@
//! It is not possible to depend on a different proto bundle within the same crate (because
//! these are being built simultaneously from the same build script).
#![allow(clippy::print_stdout)]
// Imports accessed from the generated code.
pub use self::syntax::*;
use anyhow::Context as _;
// Imports accessed from the generated code.
pub use once_cell::sync::Lazy;
pub use prost;
use prost::Message as _;
Expand Down Expand Up @@ -144,16 +144,19 @@ impl Config {
.unwrap()
.to_rust_type()
.to_string();
let rust_name: syn::Path = syn::parse_str(&rust_name).context("rust_name")?;
let proto_name = proto_name.to_string();
let this = self.this_crate().to_string();
Ok(format!("impl {this}::prost_reflect::ReflectMessage for {rust_name} {{\
fn descriptor(&self) -> {this}::prost_reflect::MessageDescriptor {{\
static INIT : {this}::Lazy<{this}::prost_reflect::MessageDescriptor> = {this}::Lazy::new(|| {{\
DESCRIPTOR.get_message_by_name({proto_name:?}).unwrap()\
}});\
INIT.clone()\
}}\
}}"))
let this: syn::Path = syn::parse_str(&self.this_crate().to_string()).context("this")?;
Ok(quote::quote! {
impl #this::prost_reflect::ReflectMessage for #rust_name {
fn descriptor(&self) -> #this::prost_reflect::MessageDescriptor {
static INIT : #this::Lazy<#this::prost_reflect::MessageDescriptor> = #this::Lazy::new(|| {
DESCRIPTOR.get_message_by_name(#proto_name).unwrap()
});
INIT.clone()
}
}
}.to_string())
}

/// Generates rust code from the proto files according to the config.
Expand Down Expand Up @@ -208,6 +211,7 @@ impl Config {
// rewrapping the error, so that source location is included in the error message.
.map_err(|err| anyhow::anyhow!("{err:?}"))?;
let descriptor = compiler.file_descriptor_set();
// Unwrap is ok, because we add a descriptor from a successful compilation.
pool.add_file_descriptor_set(descriptor.clone()).unwrap();

// Check that the compiled proto files belong to the declared proto package.
Expand Down Expand Up @@ -275,13 +279,16 @@ impl Config {
let rust_deps = self
.dependencies
.iter()
.map(|d| d.0.to_string())
.collect::<Vec<_>>()
.join(",");
let this = self.this_crate().to_string();
output.append(&format!(
"{this}::declare_descriptor!(\"{package_root}\",{descriptor_path:?},{rust_deps});"
));
.map(|d| syn::parse_str::<syn::Path>(&d.0.to_string()).unwrap());
let this: syn::Path = syn::parse_str(&self.this_crate().to_string())?;
let package_root = package_root.to_string();
let descriptor_path = descriptor_path.display().to_string();
output.append(
&quote::quote! {
#this::declare_descriptor!(#package_root,#descriptor_path,#(#rust_deps),*);
}
.to_string(),
);

// Save output.
fs::write(output_path, output.format().context("output.format()")?)?;
Expand Down
9 changes: 2 additions & 7 deletions node/libs/protobuf_build/src/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,6 @@ impl fmt::Display for RustName {
}
}

impl From<prost_build::Module> for RustName {
fn from(s: prost_build::Module) -> Self {
Self(s.parts().map(Part::from).collect())
}
}

impl From<&str> for RustName {
fn from(s: &str) -> Self {
Self(s.split("::").map(Part::from).collect())
Expand Down Expand Up @@ -165,8 +159,9 @@ impl RustModule {

/// Collects the code of the module and formats it.
pub(crate) fn format(&self) -> anyhow::Result<String> {
let s = self.collect();
Ok(prettyplease::unparse(
&syn::parse_str(&self.collect()).context("syn::parse_str()")?,
&syn::parse_str(&s).with_context(|| format!("syn::parse_str({s:?})"))?,
))
}
}
Expand Down

0 comments on commit 2c9fb49

Please sign in to comment.