Skip to content

Commit

Permalink
Rust: remove extern crate declaration for std from generated code
Browse files Browse the repository at this point in the history
Starting from the 2018 edition of Rust, paths starting with `::` must refer to
a crate, so when we refer to `::std` there is no risk of accidental collision
with another identifier.

Using `::std` instead of `::__std` is useful because it works even when the
generated code is in a module rather than directly in the crate root. This
allows us to remove one of the post-processing steps from the codegen crate.

PiperOrigin-RevId: 702858213
  • Loading branch information
acozzette authored and copybara-github committed Dec 4, 2024
1 parent 2ca39a2 commit 6a0ff9d
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 8 deletions.
3 changes: 1 addition & 2 deletions rust/release_crates/protobuf_codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,7 @@ impl CodeGen {
.unwrap()
.replace("crate::", "")
.replace("protobuf_upb", "protobuf")
.replace("::__pb", "__pb")
.replace("::__std", "__std");
.replace("::__pb", "__pb");
let mut file = OpenOptions::new().write(true).truncate(true).open(path).unwrap();
file.write(contents.as_bytes()).unwrap();
}
Expand Down
11 changes: 5 additions & 6 deletions src/google/protobuf/compiler/rust/generator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -147,19 +147,18 @@ bool RustGenerator::Generate(const FileDescriptor* file,

// Convenience shorthands for common symbols.
auto v = ctx.printer().WithVars({
{"std", "::__std"},
{"std", "::std"},
{"pb", "::__pb"},
{"pbi", "::__pb::__internal"},
{"pbr", "::__pb::__runtime"},
{"NonNull", "::__std::ptr::NonNull"},
{"Phantom", "::__std::marker::PhantomData"},
{"Result", "::__std::result::Result"},
{"Option", "::__std::option::Option"},
{"NonNull", "::std::ptr::NonNull"},
{"Phantom", "::std::marker::PhantomData"},
{"Result", "::std::result::Result"},
{"Option", "::std::option::Option"},
});

ctx.Emit({{"kernel", KernelRsName(ctx.opts().kernel)}}, R"rs(
extern crate protobuf_$kernel$ as __pb;
extern crate std as __std;
)rs");

Expand Down

0 comments on commit 6a0ff9d

Please sign in to comment.