Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unstable --print=crate-root-lint-levels #139184

Merged
merged 3 commits into from
Apr 2, 2025
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
28 changes: 28 additions & 0 deletions compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,34 @@ fn print_crate_info(
};
println_info!("{}", passes::get_crate_name(sess, attrs));
}
CrateRootLintLevels => {
let Some(attrs) = attrs.as_ref() else {
// no crate attributes, print out an error and exit
return Compilation::Continue;
};
let crate_name = passes::get_crate_name(sess, attrs);
let lint_store = crate::unerased_lint_store(sess);
let registered_tools = rustc_resolve::registered_tools_ast(sess.dcx(), attrs);
let features = rustc_expand::config::features(sess, attrs, crate_name);
let lint_levels = rustc_lint::LintLevelsBuilder::crate_root(
sess,
&features,
true,
lint_store,
&registered_tools,
attrs,
);
for lint in lint_store.get_lints() {
if let Some(feature_symbol) = lint.feature_gate
&& !features.enabled(feature_symbol)
{
// lint is unstable and feature gate isn't active, don't print
continue;
}
let level = lint_levels.lint_level(lint).0;
println_info!("{}={}", lint.name_lower(), level.as_str());
}
}
Cfg => {
let mut cfgs = sess
.psess
Expand Down
13 changes: 13 additions & 0 deletions compiler/rustc_lint/src/levels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,19 @@ impl<'s> LintLevelsBuilder<'s, TopDown> {
builder
}

pub fn crate_root(
sess: &'s Session,
features: &'s Features,
lint_added_lints: bool,
store: &'s LintStore,
registered_tools: &'s RegisteredTools,
crate_attrs: &[ast::Attribute],
) -> Self {
let mut builder = Self::new(sess, features, lint_added_lints, store, registered_tools);
builder.add(crate_attrs, true, None);
builder
}

fn process_command_line(&mut self) {
self.provider.cur = self
.provider
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ pub use context::{
};
pub use early::{EarlyCheckNode, check_ast_node};
pub use late::{check_crate, late_lint_mod, unerased_lint_store};
pub use levels::LintLevelsBuilder;
pub use passes::{EarlyLintPass, LateLintPass};
pub use rustc_session::lint::Level::{self, *};
pub use rustc_session::lint::{
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_resolve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ mod late;
mod macros;
pub mod rustdoc;

pub use macros::registered_tools_ast;

rustc_fluent_macro::fluent_messages! { "../messages.ftl" }

#[derive(Debug)]
Expand Down
15 changes: 11 additions & 4 deletions compiler/rustc_resolve/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use rustc_ast::{self as ast, Crate, NodeId, attr};
use rustc_ast_pretty::pprust;
use rustc_attr_parsing::{AttributeKind, StabilityLevel, find_attr};
use rustc_data_structures::intern::Interned;
use rustc_errors::{Applicability, StashKey};
use rustc_errors::{Applicability, DiagCtxtHandle, StashKey};
use rustc_expand::base::{
DeriveResolution, Indeterminate, ResolverExpand, SyntaxExtension, SyntaxExtensionKind,
};
Expand Down Expand Up @@ -124,22 +124,29 @@ fn fast_print_path(path: &ast::Path) -> Symbol {
}

pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
let mut registered_tools = RegisteredTools::default();
let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
registered_tools_ast(tcx.dcx(), pre_configured_attrs)
}

pub fn registered_tools_ast(
dcx: DiagCtxtHandle<'_>,
pre_configured_attrs: &[ast::Attribute],
) -> RegisteredTools {
let mut registered_tools = RegisteredTools::default();
for attr in attr::filter_by_name(pre_configured_attrs, sym::register_tool) {
for meta_item_inner in attr.meta_item_list().unwrap_or_default() {
match meta_item_inner.ident() {
Some(ident) => {
if let Some(old_ident) = registered_tools.replace(ident) {
tcx.dcx().emit_err(errors::ToolWasAlreadyRegistered {
dcx.emit_err(errors::ToolWasAlreadyRegistered {
span: ident.span,
tool: ident,
old_ident_span: old_ident.span,
});
}
}
None => {
tcx.dcx().emit_err(errors::ToolOnlyAcceptsIdentifiers {
dcx.emit_err(errors::ToolOnlyAcceptsIdentifiers {
span: meta_item_inner.span(),
tool: sym::register_tool,
});
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ pub const PRINT_KINDS: &[(&str, PrintKind)] = &[
("check-cfg", PrintKind::CheckCfg),
("code-models", PrintKind::CodeModels),
("crate-name", PrintKind::CrateName),
("crate-root-lint-levels", PrintKind::CrateRootLintLevels),
("deployment-target", PrintKind::DeploymentTarget),
("file-names", PrintKind::FileNames),
("host-tuple", PrintKind::HostTuple),
Expand Down Expand Up @@ -881,6 +882,7 @@ pub enum PrintKind {
CheckCfg,
CodeModels,
CrateName,
CrateRootLintLevels,
DeploymentTarget,
FileNames,
HostTuple,
Expand Down Expand Up @@ -2067,6 +2069,7 @@ fn check_print_request_stability(
match print_kind {
PrintKind::AllTargetSpecsJson
| PrintKind::CheckCfg
| PrintKind::CrateRootLintLevels
| PrintKind::SupportedCrateTypes
| PrintKind::TargetSpecJson
if !unstable_opts.unstable_options =>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# `print=crate-root-lint-levels`

The tracking issue for this feature is: [#139180](https://github.com/rust-lang/rust/issues/139180).

------------------------

This option of the `--print` flag print the list of lints with print out all the lints and their associated levels (`allow`, `warn`, `deny`, `forbid`) based on the regular Rust rules at crate root, that is *(roughly)*:
- command line args (`-W`, `-A`, `--force-warn`, `--cap-lints`, ...)
- crate root attributes (`#![allow]`, `#![warn]`, `#[expect]`, ...)
- *the special `warnings` lint group*
- the default lint level

The output format is `LINT_NAME=LINT_LEVEL`, e.g.:
```text
unknown_lint=warn
arithmetic_overflow=deny
```

To be used like this:

```bash
rustc --print=crate-root-lint-levels -Zunstable-options lib.rs
```
5 changes: 5 additions & 0 deletions tests/run-make/print-crate-root-lint-levels/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#![allow(unexpected_cfgs)]
#![expect(unused_mut)]

#[deny(unknown_lints)]
mod my_mod {}
118 changes: 118 additions & 0 deletions tests/run-make/print-crate-root-lint-levels/rmake.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
//! This checks the output of `--print=crate-root-lint-levels`

extern crate run_make_support;

use std::collections::HashSet;
use std::iter::FromIterator;

use run_make_support::rustc;

struct CrateRootLintLevels {
args: &'static [&'static str],
contains: Contains,
}

struct Contains {
contains: &'static [&'static str],
doesnt_contain: &'static [&'static str],
}

fn main() {
check(CrateRootLintLevels {
args: &[],
contains: Contains {
contains: &[
"unexpected_cfgs=allow",
"unused_mut=expect",
"warnings=warn",
"stable_features=warn",
"unknown_lints=warn",
],
doesnt_contain: &["unexpected_cfgs=warn", "unused_mut=warn"],
},
});
check(CrateRootLintLevels {
args: &["-Wunexpected_cfgs"],
contains: Contains {
contains: &["unexpected_cfgs=allow", "warnings=warn"],
doesnt_contain: &["unexpected_cfgs=warn"],
},
});
check(CrateRootLintLevels {
args: &["-Dwarnings"],
contains: Contains {
contains: &[
"unexpected_cfgs=allow",
"warnings=deny",
"stable_features=deny",
"unknown_lints=deny",
],
doesnt_contain: &["warnings=warn"],
},
});
check(CrateRootLintLevels {
args: &["-Dstable_features"],
contains: Contains {
contains: &["warnings=warn", "stable_features=deny", "unexpected_cfgs=allow"],
doesnt_contain: &["warnings=deny"],
},
});
check(CrateRootLintLevels {
args: &["-Dwarnings", "--force-warn=stable_features"],
contains: Contains {
contains: &["warnings=deny", "stable_features=force-warn", "unknown_lints=deny"],
doesnt_contain: &["warnings=warn"],
},
});
check(CrateRootLintLevels {
args: &["-Dwarnings", "--cap-lints=warn"],
contains: Contains {
contains: &[
"unexpected_cfgs=allow",
"warnings=warn",
"stable_features=warn",
"unknown_lints=warn",
],
doesnt_contain: &["warnings=deny"],
},
});
}

#[track_caller]
fn check(CrateRootLintLevels { args, contains }: CrateRootLintLevels) {
let output = rustc()
.input("lib.rs")
.arg("-Zunstable-options")
.print("crate-root-lint-levels")
.args(args)
.run();

let stdout = output.stdout_utf8();

let mut found = HashSet::<String>::new();

for l in stdout.lines() {
assert!(l == l.trim());
if let Some((left, right)) = l.split_once('=') {
assert!(!left.contains("\""));
assert!(!right.contains("\""));
} else {
assert!(l.contains('='));
}
assert!(found.insert(l.to_string()), "{}", &l);
}

let Contains { contains, doesnt_contain } = contains;

{
let should_found = HashSet::<String>::from_iter(contains.iter().map(|s| s.to_string()));
let diff: Vec<_> = should_found.difference(&found).collect();
assert!(diff.is_empty(), "should found: {:?}, didn't found {:?}", &should_found, &diff);
}
{
let should_not_find =
HashSet::<String>::from_iter(doesnt_contain.iter().map(|s| s.to_string()));
let diff: Vec<_> = should_not_find.intersection(&found).collect();
assert!(diff.is_empty(), "should not find {:?}, did found {:?}", &should_not_find, &diff);
}
}
2 changes: 1 addition & 1 deletion tests/run-make/rustc-help/help-v.stdout
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Options:
--emit [asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]
Comma separated list of types of output for the
compiler to emit
--print [all-target-specs-json|calling-conventions|cfg|check-cfg|code-models|crate-name|deployment-target|file-names|host-tuple|link-args|native-static-libs|relocation-models|split-debuginfo|stack-protector-strategies|supported-crate-types|sysroot|target-cpus|target-features|target-libdir|target-list|target-spec-json|tls-models]
--print [all-target-specs-json|calling-conventions|cfg|check-cfg|code-models|crate-name|crate-root-lint-levels|deployment-target|file-names|host-tuple|link-args|native-static-libs|relocation-models|split-debuginfo|stack-protector-strategies|supported-crate-types|sysroot|target-cpus|target-features|target-libdir|target-list|target-spec-json|tls-models]
Compiler information to print on stdout
-g Equivalent to -C debuginfo=2
-O Equivalent to -C opt-level=3
Expand Down
2 changes: 1 addition & 1 deletion tests/run-make/rustc-help/help.stdout
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Options:
--emit [asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]
Comma separated list of types of output for the
compiler to emit
--print [all-target-specs-json|calling-conventions|cfg|check-cfg|code-models|crate-name|deployment-target|file-names|host-tuple|link-args|native-static-libs|relocation-models|split-debuginfo|stack-protector-strategies|supported-crate-types|sysroot|target-cpus|target-features|target-libdir|target-list|target-spec-json|tls-models]
--print [all-target-specs-json|calling-conventions|cfg|check-cfg|code-models|crate-name|crate-root-lint-levels|deployment-target|file-names|host-tuple|link-args|native-static-libs|relocation-models|split-debuginfo|stack-protector-strategies|supported-crate-types|sysroot|target-cpus|target-features|target-libdir|target-list|target-spec-json|tls-models]
Compiler information to print on stdout
-g Equivalent to -C debuginfo=2
-O Equivalent to -C opt-level=3
Expand Down
2 changes: 1 addition & 1 deletion tests/ui/invalid-compile-flags/print-without-arg.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: Argument to option 'print' missing
Usage:
--print [all-target-specs-json|calling-conventions|cfg|check-cfg|code-models|crate-name|deployment-target|file-names|host-tuple|link-args|native-static-libs|relocation-models|split-debuginfo|stack-protector-strategies|supported-crate-types|sysroot|target-cpus|target-features|target-libdir|target-list|target-spec-json|tls-models]
--print [all-target-specs-json|calling-conventions|cfg|check-cfg|code-models|crate-name|crate-root-lint-levels|deployment-target|file-names|host-tuple|link-args|native-static-libs|relocation-models|split-debuginfo|stack-protector-strategies|supported-crate-types|sysroot|target-cpus|target-features|target-libdir|target-list|target-spec-json|tls-models]
Compiler information to print on stdout

2 changes: 1 addition & 1 deletion tests/ui/invalid-compile-flags/print.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: unknown print request: `yyyy`
|
= help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `tls-models`
= help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `tls-models`
= help: for more information, see the rustc book: https://doc.rust-lang.org/rustc/command-line-arguments.html#--print-print-compiler-information

2 changes: 1 addition & 1 deletion tests/ui/print-request/print-lints-help.stderr
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
error: unknown print request: `lints`
|
= help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `tls-models`
= help: valid print requests are: `all-target-specs-json`, `calling-conventions`, `cfg`, `check-cfg`, `code-models`, `crate-name`, `crate-root-lint-levels`, `deployment-target`, `file-names`, `host-tuple`, `link-args`, `native-static-libs`, `relocation-models`, `split-debuginfo`, `stack-protector-strategies`, `supported-crate-types`, `sysroot`, `target-cpus`, `target-features`, `target-libdir`, `target-list`, `target-spec-json`, `tls-models`
= help: use `-Whelp` to print a list of lints
= help: for more information, see the rustc book: https://doc.rust-lang.org/rustc/command-line-arguments.html#--print-print-compiler-information

4 changes: 4 additions & 0 deletions tests/ui/print-request/stability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
//@[all_target_specs_json] compile-flags: --print=all-target-specs-json
//@[all_target_specs_json] error-pattern: the `-Z unstable-options` flag must also be passed

//@ revisions: crate_root_lint_levels
//@[crate_root_lint_levels] compile-flags: --print=crate-root-lint-levels
//@[crate_root_lint_levels] error-pattern: the `-Z unstable-options` flag must also be passed

//@ revisions: check_cfg
//@[check_cfg] compile-flags: --print=check-cfg
//@[check_cfg] error-pattern: the `-Z unstable-options` flag must also be passed
Expand Down
Loading