Skip to content

Commit 2e12508

Browse files
committed
Allow printing a fully-qualified path in def_path_str
Previously, the local crate would always be printed as a leading `crate::`. Allow resolving it to the crate name instead. This allows printing a fully qualified path with: ```rust let qualified_name = with_no_visible_paths!(with_resolve_crate_name!( with_no_trimmed_paths!(tcx.def_path_str(def_id)) )); ``` I found this useful for an out-of-tree rustc-driver. I do not currently have a usecase in mind upstream; I'm ok if you don't want this PR for that reason. This does not currently have tests. I am not aware of an easy way to test def-id printing, since it requires having access to a TyCtxt.
1 parent dc2c356 commit 2e12508

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

compiler/rustc_middle/src/ty/print/pretty.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ use crate::ty::{
3131

3232
thread_local! {
3333
static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
34+
static SHOULD_PREFIX_WITH_CRATE_NAME: Cell<bool> = const { Cell::new(false) };
3435
static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
3536
static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
3637
static FORCE_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
@@ -98,6 +99,10 @@ define_helper!(
9899
/// cycle errors, this can result in extra or suboptimal error output,
99100
/// so this variable disables that check.
100101
fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
102+
/// Adds the crate name prefix to paths where appropriate.
103+
/// Unlike `with_crate_prefix`, this unconditionally uses `tcx.crate_name` instead of sometimes
104+
/// using `crate::` for local items.
105+
fn with_resolve_crate_name(CrateNamePrefixGuard, SHOULD_PREFIX_WITH_CRATE_NAME);
101106
/// Adds the `crate::` prefix to paths where appropriate.
102107
fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
103108
/// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
@@ -2313,7 +2318,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
23132318

23142319
fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError> {
23152320
self.empty_path = true;
2316-
if cnum == LOCAL_CRATE {
2321+
if cnum == LOCAL_CRATE && !with_resolve_crate_name() {
23172322
if self.tcx.sess.at_least_rust_2018() {
23182323
// We add the `crate::` keyword on Rust 2018, only when desired.
23192324
if with_crate_prefix() {

0 commit comments

Comments
 (0)