Skip to content

Make the current crate's name available in Session#153924

Open
jyn514 wants to merge 3 commits intorust-lang:mainfrom
jyn514:jyn/sess-crate-name
Open

Make the current crate's name available in Session#153924
jyn514 wants to merge 3 commits intorust-lang:mainfrom
jyn514:jyn/sess-crate-name

Conversation

@jyn514
Copy link
Member

@jyn514 jyn514 commented Mar 15, 2026

Previously, this was only accessible with a full TyCtxt, or by looking at sess.opts.crate_name. The option is not reliable though -- it doesn't consider #![crate_name] and doesn't infer the name from the file stem.

Add all variants of the crate name to Session instead:

  • Add a new CrateName struct to make it more clear what's going on
  • Distinguish between the crate name and filestem (previously the
    filestem was often called the crate name even though it was
    unnormalized)
  • Add is_build_script helper
  • Distinguish between crate name and filestem in tools
  • Distinguish the normalized and unnormalized crate name while
    calculating the filestem
  • Remove unnecessary crate_name arguments

The short-term goal is slightly better correctness around crate-name handling, and easier to understand code, but the long-term goal for this is to be able to further split up the crate graph by removing dependencies on TyCtxt that only need the crate name, such as in rustc_attr_parsing.


I promise very hard that I did not change any behavior in this PR. Here is a transcript of some existing behavior on nightly:

$ cat x-y.rs
fn main() {}
$ rustc x-y.rs --print=file-names --crate-type=lib --crate-type=bin --crate-type=cdylib --crate-type=staticlib --crate-type=cdylib --crate-type=proc-macro  --print=crate-name
libx_y.rlib
x-y
libx_y.dylib
libx_y.a
libx_y.dylib
x_y
$ echo "fn main() {}" | rustc - --print=file-names --crate-type=bin --print=crate-name
rust_out
rust_out

@rustbot
Copy link
Collaborator

rustbot commented Mar 15, 2026

Some changes occurred in check-cfg diagnostics

cc @Urgau

Some changes occurred in src/tools/clippy

cc @rust-lang/clippy

The Miri subtree was changed

cc @rust-lang/miri

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-clippy Relevant to the Clippy team. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Mar 15, 2026
@rustbot
Copy link
Collaborator

rustbot commented Mar 15, 2026

r? @jdonszelmann

rustbot has assigned @jdonszelmann.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: compiler
  • compiler expanded to 69 candidates
  • Random selection from 15 candidates

@rustbot rustbot added T-rustdoc Relevant to the rustdoc team, which will review and decide on the PR/issue. T-rustdoc-frontend Relevant to the rustdoc-frontend team, which will review and decide on the web UI/UX output. labels Mar 15, 2026
@jyn514
Copy link
Member Author

jyn514 commented Mar 15, 2026

r? @WaffleLapkin

@rustbot rustbot assigned WaffleLapkin and unassigned jdonszelmann Mar 15, 2026
@rustbot
Copy link
Collaborator

rustbot commented Mar 15, 2026

WaffleLapkin is not on the review rotation at the moment.
They may take a while to respond.

@rust-log-analyzer

This comment has been minimized.

@Mark-Simulacrum
Copy link
Member

Do we have something ensuring that incremental compilation doesn't assume the crate name isn't changed? Maybe it's already part of the base key getting hashed into everything?

@jyn514 jyn514 force-pushed the jyn/sess-crate-name branch from cd84bcc to 376b6c8 Compare March 15, 2026 18:29
@jyn514
Copy link
Member Author

jyn514 commented Mar 15, 2026

Do we have something ensuring that incremental compilation doesn't assume the crate name isn't changed? Maybe it's already part of the base key getting hashed into everything?

We still don't allow changing the crate name during compilation. Once we set the OnceLock it can't be changed again. Everything that accesses the OnceLock panics if it isn't set.

let feed = tcx.create_crate_num(stable_crate_id).unwrap();
assert_eq!(feed.key(), LOCAL_CRATE);
feed.crate_name(crate_name);
feed.crate_name(sess.crate_name());
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this needs to stay a query so that it's possible to look up the crate name for other dependent crates.

Copy link
Member

@WaffleLapkin WaffleLapkin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rustc changes look good to me, haven't reviewed miri/rustdoc

View changes since this review

@saethlin
Copy link
Member

The Miri changes seem like a straightforward adaptation of the subtree to an API change. LGTM.

@rust-log-analyzer

This comment has been minimized.

@jyn514
Copy link
Member Author

jyn514 commented Mar 15, 2026

r? rustdoc

@rustbot rustbot assigned fmease and unassigned WaffleLapkin Mar 15, 2026
@jyn514
Copy link
Member Author

jyn514 commented Mar 15, 2026

@fmease Waffle has already reviewed the compiler changes, could you look at the rustdoc changes and see if they look good?

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

Previously, this was only accessible with a full `TyCtxt`, or by looking
at `sess.opts.crate_name`. The option is not reliable though -- it
doesn't consider `#![crate_name]` and doesn't infer the name from the
file stem.

Add all variants of the crate name to `Session` instead:
- Add a new `CrateName` struct to make it more clear what's going on
- Distinguish between the crate name and filestem (previously the
  filestem was often called the crate name even though it was
  unnormalized)
- Add `is_build_script` helper
- Distinguish between crate name and filestem in tools
- Distinguish the normalized and unnormalized crate name while
  calculating the filestem
- Remove unnecessary `crate_name` arguments
@jyn514 jyn514 force-pushed the jyn/sess-crate-name branch from 09bffb5 to f53995d Compare March 16, 2026 09:18
@petrochenkov petrochenkov self-assigned this Mar 16, 2026
@petrochenkov
Copy link
Contributor

I need to review, from the description it seems like it may go into a wrong direction generally.

{
return;
}
sess.crate_name.set(new_name).expect("`load_crate_name` called more than once!");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not that big of a fan of modifying global state.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you see an alternative? I document on the crate_name session option why it's hard to get this before Session construction.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Respecting #![crate_name] in compiler/rustc_metadata/src/locator.rs is just cosmetic and src/tools/miri/src/machine.rs it is not that much of an issue either as miri doesn't have a stable way of invoking it without cargo miri either. For the rest of the places manually passing crate_name like we currently do works fine, right?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, if tcx is directly available, then use tcx.crate_name(), otherwise pass crate name from the outside (probably from the same tcx).
tcx is created very early now, almost immediately after pre-configuring crate root attributes and evaluating get_crate_name, so there's a very small window in which the non-approximated crate name is available, but tcx is not.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing dependencies on TyCtxt that only need the crate name, such as in rustc_attr_parsing

I don't think parsing should depend on knowing the crate name in general, I guess occasionally it may be useful for diagnostics (but need examples), but then it can be passed from the outside as well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My inclination would also have been to figure out how to have TyCtxt available earlier or do the parts that need the crate name later.

I'd need to do a dive to get the full picture here, but I'm happy to do that and then do some brainstorming session to see what other options we have to make this all nicer

@rust-log-analyzer
Copy link
Collaborator

The job pr-check-2 failed! Check out the build log: (web) (plain enhanced) (plain)

Click to see the possible cause of the failure (guessed by this bot)
    Checking rustc_middle v0.0.0 (/checkout/compiler/rustc_middle)
warning: unresolved link to `OutFileName`
  --> compiler/rustc_session/src/utils.rs:43:63
   |
43 |     /// Get the unnormalized crate name, as suitable for an [`OutFileName`].
   |                                                               ^^^^^^^^^^^ no item named `OutFileName` in scope
   |
   = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]`
   = note: `#[warn(rustdoc::broken_intra_doc_links)]` on by default

warning: `rustc_session` (lib doc) generated 1 warning
---
 Documenting rustc_error_codes v0.0.0 (/checkout/compiler/rustc_error_codes)
    Finished `release` profile [optimized] target(s) in 4m 42s
error: warnings are denied by `build.warnings` configuration
Bootstrap failed while executing `doc compiler --stage 1`
Command `/checkout/obj/build/x86_64-unknown-linux-gnu/stage0/bin/cargo doc -Zwarnings --target x86_64-unknown-linux-gnu -Zbinary-dep-depinfo -j 4 -Zroot-dir=/checkout --locked --color=always --profile=release --features llvm --manifest-path /checkout/compiler/rustc/Cargo.toml -Zskip-rustdoc-fingerprint --no-deps -Zrustdoc-map -p rustc-main -p rustc_abi -p rustc_arena -p rustc_ast -p rustc_ast_ir -p rustc_ast_lowering -p rustc_ast_passes -p rustc_ast_pretty -p rustc_attr_parsing -p rustc_baked_icu_data -p rustc_borrowck -p rustc_builtin_macros -p rustc_codegen_llvm -p rustc_codegen_ssa -p rustc_const_eval -p rustc_data_structures -p rustc_driver -p rustc_driver_impl -p rustc_error_codes -p rustc_error_messages -p rustc_errors -p rustc_expand -p rustc_feature -p rustc_fs_util -p rustc_graphviz -p rustc_hashes -p rustc_hir -p rustc_hir_analysis -p rustc_hir_id -p rustc_hir_pretty -p rustc_hir_typeck -p rustc_incremental -p rustc_index -p rustc_index_macros -p rustc_infer -p rustc_interface -p rustc_lexer -p rustc_lint -p rustc_lint_defs -p rustc_llvm -p rustc_log -p rustc_macros -p rustc_metadata -p rustc_middle -p rustc_mir_build -p rustc_mir_dataflow -p rustc_mir_transform -p rustc_monomorphize -p rustc_next_trait_solver -p rustc_parse -p rustc_parse_format -p rustc_passes -p rustc_pattern_analysis -p rustc_privacy -p rustc_proc_macro -p rustc_public -p rustc_public_bridge -p rustc_query_impl -p rustc_resolve -p rustc_sanitizers -p rustc_serialize -p rustc_session -p rustc_span -p rustc_symbol_mangling -p rustc_target -p rustc_thread_pool -p rustc_trait_selection -p rustc_traits -p rustc_transmute -p rustc_ty_utils -p rustc_type_ir -p rustc_type_ir_macros -p rustc_windows_rc [workdir=/checkout]` failed with exit code 101
Created at: src/bootstrap/src/core/build_steps/doc.rs:916:25
Executed at: src/bootstrap/src/core/build_steps/doc.rs:983:26

Command has failed. Rerun with -v to see more details.
Build completed unsuccessfully in 0:04:43
  local time: Mon Mar 16 10:12:11 UTC 2026
  network time: Mon, 16 Mar 2026 10:12:11 GMT
##[error]Process completed with exit code 1.
##[group]Run echo "disk usage:"

prints: Vec<PrintRequest> [UNTRACKED],
cg: CodegenOptions [SUBSTRUCT CodegenOptionsTargetModifiers CodegenOptions],
externs: Externs [UNTRACKED],
#[deprecated = "use `Session::crate_name()` instead, which accounts for `#![crate_name]`"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe rustc::bad_opt_access is a better option?

@rust-bors
Copy link
Contributor

rust-bors bot commented Mar 18, 2026

☔ The latest upstream changes (presumably #154032) made this pull request unmergeable. Please resolve the merge conflicts.

@petrochenkov petrochenkov removed their assignment Mar 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-clippy Relevant to the Clippy team. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-rustdoc Relevant to the rustdoc team, which will review and decide on the PR/issue. T-rustdoc-frontend Relevant to the rustdoc-frontend team, which will review and decide on the web UI/UX output.

Projects

None yet

Development

Successfully merging this pull request may close these issues.