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
2 changes: 1 addition & 1 deletion compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
}
}

fn print_crate_info(
pub fn print_crate_info(
codegen_backend: &dyn CodegenBackend,
sess: &Session,
parse_attrs: bool,
Expand Down
22 changes: 15 additions & 7 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@ use tracing::debug;

pub use crate::config::cfg::{Cfg, CheckCfg, ExpectedValues};
use crate::config::native_libs::parse_native_libs;
pub use crate::config::print_request::{PrintKind, PrintRequest};
pub use crate::config::print_request::{
PrintCategory, PrintKind, PrintRequest, collect_print_requests,
};
use crate::diagnostics::FileWriteFail;
use crate::macros::AllVariants;
pub use crate::options::*;
use crate::search_paths::SearchPath;
use crate::utils::CanonicalizedPath;
Expand Down Expand Up @@ -1414,12 +1417,11 @@ impl Sysroot {
}
}

/// Get the host triple out of the build environment. This ensures that our
/// idea of the host triple is the same as for the set of libraries we've
/// actually built. We can't just take LLVM's host triple because they
/// normalize all ix86 architectures to i386.
pub fn host_tuple() -> &'static str {
// Get the host triple out of the build environment. This ensures that our
// idea of the host triple is the same as for the set of libraries we've
// actually built. We can't just take LLVM's host triple because they
// normalize all ix86 architectures to i386.
//
// Instead of grabbing the host triple (for the current host), we grab (at
// compile time) the target triple that this rustc is built with and
// calling that (at runtime) the host triple.
Expand Down Expand Up @@ -2898,7 +2900,13 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
));
}

let prints = print_request::collect_print_requests(early_dcx, &mut cg, &unstable_opts, matches);
let prints = print_request::collect_print_requests(
early_dcx,
&mut cg,
&unstable_opts,
matches,
PrintCategory::ALL_VARIANTS,
);

// -Zretpoline-external-thunk also requires -Zretpoline
if unstable_opts.retpoline_external_thunk {
Expand Down
108 changes: 102 additions & 6 deletions compiler/rustc_session/src/config/print_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,36 +22,98 @@ pub struct PrintRequest {
#[derive(AllVariants)]
pub enum PrintKind {
// tidy-alphabetical-start
/// All target JSON specifications.
AllTargetSpecsJson,

/// Does the backend supports the [`PrintRequest::arg`] `asm!()` mnemonic? (perma-unstable)
BackendHasMnemonic,

/// Does the backend supports Zstd compression? (perma-unstable)
BackendHasZstd,

/// List of all calling conventions supported by rustc.
CallingConventions,

/// List of cfg values.
Cfg,

/// List of check-cfg values.
CheckCfg,

/// List of available code models for the current backend.
CodeModels,

/// Name of the crate being compiled.
CrateName,

/// Lint levels of the crate's root module.
CrateRootLintLevels,

/// The current selected deployment target. (Apple only)
DeploymentTarget,

/// The names of the files created by the `--emit=link` option. (e.g. `libfoo.a`)
FileNames,

/// Target-tuple of the host compiler.
HostTuple,

/// Linker invocations.
LinkArgs,

/// When compiling a `staticlib` crate, print the linker flags used.
NativeStaticLibs,

/// List of available relocation models for the current backend.
RelocationModels,

/// List of available split debuginfos for the current target.
SplitDebuginfo,

/// List of available stack protector strategies for the current backend.
StackProtectorStrategies,

/// List of available crate types for the current target.
SupportedCrateTypes,

/// Path to the sysroot.
Sysroot,

/// List of available CPU values for the current target.
TargetCPUs,

/// List of available target features for the current target.
TargetFeatures,

/// Path to the target libdir.
TargetLibdir,

/// List of supported targets.
TargetList,

/// Current target JSON specification.
TargetSpecJson,

/// Target JSON specification schema.
TargetSpecJsonSchema,

/// List of available TLS models for the current backend.
TlsModels,

/// Target-tuple for WebAssembly's proc-macro crates.
WasmProcMacroTuple,
// tidy-alphabetical-end
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[derive(AllVariants)]
pub enum PrintCategory {
Target,
Codegen,
Linker,
Crate,
}

impl PrintKind {
fn name(self) -> &'static str {
use PrintKind::*;
Expand Down Expand Up @@ -88,6 +150,28 @@ impl PrintKind {
}
}

fn category(self) -> PrintCategory {
use PrintKind::*;
match self {
TargetList | TargetSpecJsonSchema | AllTargetSpecsJson | TargetSpecJson
| TargetCPUs | TargetFeatures | DeploymentTarget | HostTuple | SupportedCrateTypes
| Sysroot | TargetLibdir | Cfg | CheckCfg | WasmProcMacroTuple => PrintCategory::Target,

BackendHasMnemonic
| BackendHasZstd
| CallingConventions
| CodeModels
| SplitDebuginfo
| StackProtectorStrategies
| TlsModels
| RelocationModels => PrintCategory::Codegen,

LinkArgs | NativeStaticLibs => PrintCategory::Linker,

CrateName | CrateRootLintLevels | FileNames => PrintCategory::Crate,
}
}

fn is_stable(self) -> bool {
use PrintKind::*;
match self {
Expand Down Expand Up @@ -144,11 +228,12 @@ pub(crate) static PRINT_HELP: LazyLock<String> = LazyLock::new(|| {
)
});

pub(crate) fn collect_print_requests(
pub fn collect_print_requests(
early_dcx: &EarlyDiagCtxt,
cg: &mut CodegenOptions,
unstable_opts: &UnstableOptions,
matches: &getopts::Matches,
allowed: &[PrintCategory],
) -> Vec<PrintRequest> {
let mut prints = Vec::<PrintRequest>::new();
if cg.target_cpu.as_deref() == Some("help") {
Expand Down Expand Up @@ -190,12 +275,14 @@ pub(crate) fn collect_print_requests(
for example: `--print=backend-has-mnemonic:RET`",
);
}
} else if let Some(print_kind) = PrintKind::from_str(req) {
} else if let Some(print_kind) = PrintKind::from_str(req)
&& allowed.contains(&print_kind.category())
{
check_print_request_stability(early_dcx, unstable_opts, print_kind);
(print_kind, None)
} else {
let is_nightly = nightly_options::match_is_nightly_build(matches);
emit_unknown_print_request_help(early_dcx, req, is_nightly)
emit_unknown_print_request_help(early_dcx, req, is_nightly, allowed)
};

let out = out.unwrap_or(OutFileName::Stdout);
Expand Down Expand Up @@ -226,11 +313,17 @@ fn check_print_request_stability(
}
}

fn emit_unknown_print_request_help(early_dcx: &EarlyDiagCtxt, req: &str, is_nightly: bool) -> ! {
fn emit_unknown_print_request_help(
early_dcx: &EarlyDiagCtxt,
req: &str,
is_nightly: bool,
allowed: &[PrintCategory],
) -> ! {
let prints = PrintKind::ALL_VARIANTS
.iter()
// If we're not on nightly, we don't want to print unstable options
.filter(|kind| is_nightly || kind.is_stable())
.filter(|kind| allowed.contains(&kind.category()))
.map(|kind| format!("`{kind}`"))
.collect::<Vec<_>>()
.join(", ");
Expand All @@ -239,9 +332,12 @@ fn emit_unknown_print_request_help(early_dcx: &EarlyDiagCtxt, req: &str, is_nigh
diag.help(format!("valid print requests are: {prints}"));

if req == "lints" {
diag.help(format!("use `-Whelp` to print a list of lints"));
diag.help("use `-Whelp` to print a list of lints");
}

if allowed == PrintCategory::ALL_VARIANTS {
diag.help("for more information, see the rustc book: https://doc.rust-lang.org/rustc/command-line-arguments.html#--print-print-compiler-information");
}

diag.help(format!("for more information, see the rustc book: https://doc.rust-lang.org/rustc/command-line-arguments.html#--print-print-compiler-information"));
diag.emit()
}
20 changes: 16 additions & 4 deletions src/librustdoc/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ use rustc_errors::DiagCtxtHandle;
use rustc_lint::Level;
use rustc_session::config::{
self, CodegenOptions, ErrorOutputType, Externs, Input, JsonUnusedExterns,
OptionsTargetModifiers, OutFileName, Sysroot, UnstableOptions, get_cmd_lint_options,
nightly_options, parse_crate_types_from_list, parse_externs, parse_target_triple,
OptionsTargetModifiers, OutFileName, PrintCategory, PrintRequest, Sysroot, UnstableOptions,
collect_print_requests, get_cmd_lint_options, nightly_options, parse_crate_types_from_list,
parse_externs, parse_target_triple,
};
use rustc_session::search_paths::SearchPath;
use rustc_session::{EarlyDiagCtxt, getopts};
Expand Down Expand Up @@ -105,6 +106,8 @@ pub(crate) struct Options {
pub(crate) describe_lints: bool,
/// What level to cap lints at.
pub(crate) lint_cap: Option<Level>,
/// Print requests to hand to the compiler.
pub(crate) prints: Vec<PrintRequest>,

// Options specific to running doctests
/// Whether we should run doctests instead of generating docs.
Expand Down Expand Up @@ -198,6 +201,7 @@ impl fmt::Debug for Options {
.field("lint_opts", &self.lint_opts)
.field("describe_lints", &self.describe_lints)
.field("lint_cap", &self.lint_cap)
.field("prints", &self.prints)
.field("should_test", &self.should_test)
.field("test_args", &self.test_args)
.field("test_run_directory", &self.test_run_directory)
Expand Down Expand Up @@ -336,7 +340,6 @@ impl FromStr for EmitType {

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
// modern choices
"html-static-files" => Ok(Self::HtmlStaticFiles),
"html-non-static-files" => Ok(Self::HtmlNonStaticFiles),
"dep-info" => Ok(Self::DepInfo(None)),
Expand Down Expand Up @@ -409,7 +412,7 @@ impl Options {
let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();

let mut collected_options = Default::default();
let codegen_options = CodegenOptions::build(early_dcx, matches, &mut collected_options);
let mut codegen_options = CodegenOptions::build(early_dcx, matches, &mut collected_options);
let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut collected_options);

let remap_path_prefix = match parse_remap_path_prefix(matches) {
Expand Down Expand Up @@ -571,6 +574,14 @@ impl Options {
Err(err) => dcx.fatal(err),
};

let prints = collect_print_requests(
early_dcx,
&mut codegen_options,
&unstable_opts,
matches,
&[PrintCategory::Target, PrintCategory::Crate],
);

let mut parts_out_dir =
match matches.opt_str("write-doc-meta-dir").map(PathToParts::from_flag).transpose() {
Ok(parts_out_dir) => parts_out_dir,
Expand Down Expand Up @@ -906,6 +917,7 @@ impl Options {
lint_opts,
describe_lints,
lint_cap,
prints,
should_test,
test_args,
show_coverage,
Expand Down
2 changes: 2 additions & 0 deletions src/librustdoc/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ pub(crate) fn create_config(
lint_opts,
describe_lints,
lint_cap,
prints,
scrape_examples_options,
remap_path_prefix,
remap_path_scope,
Expand Down Expand Up @@ -284,6 +285,7 @@ pub(crate) fn create_config(
diagnostic_width,
edition,
describe_lints,
prints,
crate_name,
test,
remap_path_prefix,
Expand Down
12 changes: 11 additions & 1 deletion src/librustdoc/doctest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ pub(crate) fn run(dcx: DiagCtxtHandle<'_>, input: Input, options: RustdocOptions
unstable_opts: options.unstable_opts.clone(),
error_format: options.error_format.clone(),
target_modifiers: options.target_modifiers.clone(),
describe_lints: options.describe_lints,
..config::Options::default()
};

Expand Down Expand Up @@ -215,8 +216,17 @@ pub(crate) fn run(dcx: DiagCtxtHandle<'_>, input: Input, options: RustdocOptions

let extract_doctests = options.output_format == OutputFormat::Doctest;
let save_temps = options.codegen_options.save_temps;
let registered_lints = config.register_lints.is_some();
let result = interface::run_compiler(config, |compiler| {
let krate = rustc_interface::passes::parse(&compiler.sess);
let sess = &compiler.sess;

// -W help
if sess.opts.describe_lints {
rustc_driver::describe_lints(sess, registered_lints);
return Ok(None);
}
Comment on lines +223 to +227

@ShE3py ShE3py Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixes -W help when running doctests:

$ rustdoc +nightly -Whelp --test /dev/null 
error: couldn't find file ``

View changes since the review


let krate = rustc_interface::passes::parse(sess);

let (collector, _incr_comp_session) =
rustc_interface::create_and_enter_global_ctxt(compiler, krate, |tcx| {
Expand Down
Loading
Loading