2017-07-27 04:51:09 +00:00
|
|
|
use std::cmp;
|
|
|
|
|
2021-06-04 21:21:43 +00:00
|
|
|
use rustc_data_structures::fx::FxHashMap;
|
2019-11-12 17:09:20 +00:00
|
|
|
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
|
2022-01-23 00:49:12 +00:00
|
|
|
use rustc_errors::{
|
|
|
|
Diagnostic, DiagnosticBuilder, DiagnosticId, EmissionGuarantee, ErrorGuaranteed,
|
|
|
|
};
|
2020-01-05 01:37:57 +00:00
|
|
|
use rustc_hir::HirId;
|
2020-12-01 20:47:41 +00:00
|
|
|
use rustc_index::vec::IndexVec;
|
2020-11-14 15:48:54 +00:00
|
|
|
use rustc_query_system::ich::StableHashingContext;
|
2021-01-30 00:06:00 +00:00
|
|
|
use rustc_session::lint::{
|
|
|
|
builtin::{self, FORBIDDEN_LINT_GROUPS},
|
2021-11-20 19:45:27 +00:00
|
|
|
FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId,
|
2021-01-30 00:06:00 +00:00
|
|
|
};
|
2020-01-09 04:57:07 +00:00
|
|
|
use rustc_session::{DiagnosticMessageId, Session};
|
|
|
|
use rustc_span::hygiene::MacroKind;
|
|
|
|
use rustc_span::source_map::{DesugaringKind, ExpnKind, MultiSpan};
|
2020-06-15 18:17:35 +00:00
|
|
|
use rustc_span::{symbol, Span, Symbol, DUMMY_SP};
|
2020-01-09 05:42:42 +00:00
|
|
|
|
2020-01-09 04:20:28 +00:00
|
|
|
/// How a lint level was set.
|
2021-01-03 14:19:16 +00:00
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, HashStable, Debug)]
|
2020-12-21 22:17:53 +00:00
|
|
|
pub enum LintLevelSource {
|
2020-01-09 04:20:28 +00:00
|
|
|
/// Lint is at the default level as declared
|
|
|
|
/// in rustc or a plugin.
|
|
|
|
Default,
|
|
|
|
|
|
|
|
/// Lint level was set by an attribute.
|
|
|
|
Node(Symbol, Span, Option<Symbol> /* RFC 2383 reason */),
|
|
|
|
|
|
|
|
/// Lint level was set by a command-line flag.
|
2020-12-19 22:08:41 +00:00
|
|
|
/// The provided `Level` is the level specified on the command line.
|
|
|
|
/// (The actual level may be lower due to `--cap-lints`.)
|
2020-11-02 06:37:26 +00:00
|
|
|
CommandLine(Symbol, Level),
|
2020-01-09 04:20:28 +00:00
|
|
|
}
|
|
|
|
|
2020-12-21 22:17:53 +00:00
|
|
|
impl LintLevelSource {
|
2020-06-15 18:17:35 +00:00
|
|
|
pub fn name(&self) -> Symbol {
|
|
|
|
match *self {
|
2020-12-21 22:17:53 +00:00
|
|
|
LintLevelSource::Default => symbol::kw::Default,
|
|
|
|
LintLevelSource::Node(name, _, _) => name,
|
|
|
|
LintLevelSource::CommandLine(name, _) => name,
|
2020-06-15 18:17:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn span(&self) -> Span {
|
|
|
|
match *self {
|
2020-12-21 22:17:53 +00:00
|
|
|
LintLevelSource::Default => DUMMY_SP,
|
|
|
|
LintLevelSource::Node(_, span, _) => span,
|
|
|
|
LintLevelSource::CommandLine(_, _) => DUMMY_SP,
|
2020-06-15 18:17:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-21 22:40:50 +00:00
|
|
|
/// A tuple of a lint level and its source.
|
2021-01-12 02:02:09 +00:00
|
|
|
pub type LevelAndSource = (Level, LintLevelSource);
|
2020-01-09 04:20:28 +00:00
|
|
|
|
2020-12-01 20:37:45 +00:00
|
|
|
#[derive(Debug, HashStable)]
|
2017-07-27 04:51:09 +00:00
|
|
|
pub struct LintLevelSets {
|
2020-12-01 20:47:41 +00:00
|
|
|
pub list: IndexVec<LintStackIndex, LintSet>,
|
2020-01-09 06:52:01 +00:00
|
|
|
pub lint_cap: Level,
|
2017-07-27 04:51:09 +00:00
|
|
|
}
|
|
|
|
|
2020-12-01 20:47:41 +00:00
|
|
|
rustc_index::newtype_index! {
|
|
|
|
#[derive(HashStable)]
|
|
|
|
pub struct LintStackIndex {
|
|
|
|
const COMMAND_LINE = 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-01 20:37:45 +00:00
|
|
|
#[derive(Debug, HashStable)]
|
2020-12-01 20:56:15 +00:00
|
|
|
pub struct LintSet {
|
|
|
|
// -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which
|
|
|
|
// flag.
|
|
|
|
pub specs: FxHashMap<LintId, LevelAndSource>,
|
|
|
|
|
|
|
|
pub parent: LintStackIndex,
|
2017-07-27 04:51:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl LintLevelSets {
|
2020-01-09 04:20:28 +00:00
|
|
|
pub fn new() -> Self {
|
2020-12-01 20:47:41 +00:00
|
|
|
LintLevelSets { list: IndexVec::new(), lint_cap: Level::Forbid }
|
2017-07-27 04:51:09 +00:00
|
|
|
}
|
|
|
|
|
2020-01-09 04:20:28 +00:00
|
|
|
pub fn get_lint_level(
|
2019-12-22 22:42:04 +00:00
|
|
|
&self,
|
|
|
|
lint: &'static Lint,
|
2020-12-01 20:47:41 +00:00
|
|
|
idx: LintStackIndex,
|
2021-01-12 02:02:09 +00:00
|
|
|
aux: Option<&FxHashMap<LintId, LevelAndSource>>,
|
2019-12-22 22:42:04 +00:00
|
|
|
sess: &Session,
|
2021-01-12 02:02:09 +00:00
|
|
|
) -> LevelAndSource {
|
2017-08-13 12:37:24 +00:00
|
|
|
let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux);
|
2017-07-27 04:51:09 +00:00
|
|
|
|
|
|
|
// If `level` is none then we actually assume the default level for this
|
|
|
|
// lint.
|
2019-11-12 16:52:26 +00:00
|
|
|
let mut level = level.unwrap_or_else(|| lint.default_level(sess.edition()));
|
2017-07-27 04:51:09 +00:00
|
|
|
|
|
|
|
// If we're about to issue a warning, check at the last minute for any
|
|
|
|
// directives against the warnings "lint". If, for example, there's an
|
|
|
|
// `allow(warnings)` in scope then we want to respect that instead.
|
2021-01-30 00:06:00 +00:00
|
|
|
//
|
|
|
|
// We exempt `FORBIDDEN_LINT_GROUPS` from this because it specifically
|
|
|
|
// triggers in cases (like #80988) where you have `forbid(warnings)`,
|
|
|
|
// and so if we turned that into an error, it'd defeat the purpose of the
|
|
|
|
// future compatibility warning.
|
|
|
|
if level == Level::Warn && LintId::of(lint) != LintId::of(FORBIDDEN_LINT_GROUPS) {
|
2017-07-27 04:51:09 +00:00
|
|
|
let (warnings_level, warnings_src) =
|
2020-01-09 04:20:28 +00:00
|
|
|
self.get_lint_id_level(LintId::of(builtin::WARNINGS), idx, aux);
|
2017-07-27 04:51:09 +00:00
|
|
|
if let Some(configured_warning_level) = warnings_level {
|
|
|
|
if configured_warning_level != Level::Warn {
|
|
|
|
level = configured_warning_level;
|
|
|
|
src = warnings_src;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-01 10:29:20 +00:00
|
|
|
// Ensure that we never exceed the `--cap-lints` argument
|
|
|
|
// unless the source is a --force-warn
|
|
|
|
level = if let LintLevelSource::CommandLine(_, Level::ForceWarn) = src {
|
|
|
|
level
|
|
|
|
} else {
|
|
|
|
cmp::min(level, self.lint_cap)
|
|
|
|
};
|
2017-07-27 04:51:09 +00:00
|
|
|
|
2018-06-30 22:27:44 +00:00
|
|
|
if let Some(driver_level) = sess.driver_lint_caps.get(&LintId::of(lint)) {
|
|
|
|
// Ensure that we never exceed driver level.
|
|
|
|
level = cmp::min(*driver_level, level);
|
|
|
|
}
|
|
|
|
|
2020-03-20 14:03:11 +00:00
|
|
|
(level, src)
|
2017-07-27 04:51:09 +00:00
|
|
|
}
|
|
|
|
|
2020-01-09 04:20:28 +00:00
|
|
|
pub fn get_lint_id_level(
|
2019-12-22 22:42:04 +00:00
|
|
|
&self,
|
|
|
|
id: LintId,
|
2020-12-01 20:47:41 +00:00
|
|
|
mut idx: LintStackIndex,
|
2021-01-12 02:02:09 +00:00
|
|
|
aux: Option<&FxHashMap<LintId, LevelAndSource>>,
|
2020-12-21 22:17:53 +00:00
|
|
|
) -> (Option<Level>, LintLevelSource) {
|
2017-08-13 12:37:24 +00:00
|
|
|
if let Some(specs) = aux {
|
|
|
|
if let Some(&(level, src)) = specs.get(&id) {
|
2019-12-22 22:42:04 +00:00
|
|
|
return (Some(level), src);
|
2017-08-13 12:37:24 +00:00
|
|
|
}
|
|
|
|
}
|
2017-07-27 04:51:09 +00:00
|
|
|
loop {
|
2020-12-01 20:56:15 +00:00
|
|
|
let LintSet { ref specs, parent } = self.list[idx];
|
|
|
|
if let Some(&(level, src)) = specs.get(&id) {
|
|
|
|
return (Some(level), src);
|
|
|
|
}
|
|
|
|
if idx == COMMAND_LINE {
|
|
|
|
return (None, LintLevelSource::Default);
|
2017-07-27 04:51:09 +00:00
|
|
|
}
|
2020-12-01 20:56:15 +00:00
|
|
|
idx = parent;
|
2017-07-27 04:51:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-03 14:19:16 +00:00
|
|
|
#[derive(Debug)]
|
2017-07-27 04:51:09 +00:00
|
|
|
pub struct LintLevelMap {
|
2021-08-06 21:28:58 +00:00
|
|
|
/// This is a collection of lint expectations as described in RFC 2383, that
|
|
|
|
/// can be fulfilled during this compilation session. This means that at least
|
|
|
|
/// one expected lint is currently registered in the lint store.
|
|
|
|
///
|
|
|
|
/// The [`LintExpectationId`] is stored as a part of the [`Expect`](Level::Expect)
|
|
|
|
/// lint level.
|
2022-03-02 17:10:07 +00:00
|
|
|
pub lint_expectations: Vec<(LintExpectationId, LintExpectation)>,
|
2020-01-09 06:52:01 +00:00
|
|
|
pub sets: LintLevelSets,
|
2020-12-01 20:47:41 +00:00
|
|
|
pub id_to_set: FxHashMap<HirId, LintStackIndex>,
|
2017-07-27 04:51:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl LintLevelMap {
|
|
|
|
/// If the `id` was previously registered with `register_id` when building
|
|
|
|
/// this `LintLevelMap` this returns the corresponding lint level and source
|
|
|
|
/// of the lint level for the lint provided.
|
|
|
|
///
|
|
|
|
/// If the `id` was not previously registered, returns `None`. If `None` is
|
|
|
|
/// returned then the parent of `id` should be acquired and this function
|
|
|
|
/// should be called again.
|
2019-12-22 22:42:04 +00:00
|
|
|
pub fn level_and_source(
|
|
|
|
&self,
|
|
|
|
lint: &'static Lint,
|
|
|
|
id: HirId,
|
|
|
|
session: &Session,
|
2021-01-12 02:02:09 +00:00
|
|
|
) -> Option<LevelAndSource> {
|
2019-12-22 22:42:04 +00:00
|
|
|
self.id_to_set.get(&id).map(|idx| self.sets.get_lint_level(lint, *idx, None, session))
|
2017-07-27 04:51:09 +00:00
|
|
|
}
|
|
|
|
}
|
2017-08-14 16:19:42 +00:00
|
|
|
|
2018-01-16 09:16:38 +00:00
|
|
|
impl<'a> HashStable<StableHashingContext<'a>> for LintLevelMap {
|
2017-08-14 16:19:42 +00:00
|
|
|
#[inline]
|
2019-09-26 22:54:39 +00:00
|
|
|
fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
|
2021-08-06 21:28:58 +00:00
|
|
|
let LintLevelMap { ref sets, ref id_to_set, ref lint_expectations } = *self;
|
2017-08-14 16:19:42 +00:00
|
|
|
|
2017-09-13 16:20:27 +00:00
|
|
|
id_to_set.hash_stable(hcx, hasher);
|
2021-08-06 21:28:58 +00:00
|
|
|
lint_expectations.hash_stable(hcx, hasher);
|
2017-08-14 16:19:42 +00:00
|
|
|
|
2020-12-01 20:37:45 +00:00
|
|
|
hcx.while_hashing_spans(true, |hcx| sets.hash_stable(hcx, hasher))
|
2017-08-14 16:19:42 +00:00
|
|
|
}
|
|
|
|
}
|
2020-01-09 04:57:07 +00:00
|
|
|
|
2021-08-06 21:28:58 +00:00
|
|
|
/// This struct represents a lint expectation and holds all required information
|
|
|
|
/// to emit the `unfulfilled_lint_expectations` lint if it is unfulfilled after
|
|
|
|
/// the `LateLintPass` has completed.
|
|
|
|
#[derive(Clone, Debug, HashStable)]
|
|
|
|
pub struct LintExpectation {
|
|
|
|
/// The reason for this expectation that can optionally be added as part of
|
|
|
|
/// the attribute. It will be displayed as part of the lint message.
|
|
|
|
pub reason: Option<Symbol>,
|
|
|
|
/// The [`Span`] of the attribute that this expectation originated from.
|
|
|
|
pub emission_span: Span,
|
2022-03-06 13:18:28 +00:00
|
|
|
/// Lint messages for the `unfulfilled_lint_expectations` lint will be
|
|
|
|
/// adjusted to include an additional note. Therefore, we have to track if
|
|
|
|
/// the expectation is for the lint.
|
|
|
|
pub is_unfulfilled_lint_expectations: bool,
|
2021-08-06 21:28:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl LintExpectation {
|
2022-03-06 13:18:28 +00:00
|
|
|
pub fn new(
|
|
|
|
reason: Option<Symbol>,
|
|
|
|
emission_span: Span,
|
|
|
|
is_unfulfilled_lint_expectations: bool,
|
|
|
|
) -> Self {
|
|
|
|
Self { reason, emission_span, is_unfulfilled_lint_expectations }
|
2021-08-06 21:28:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-23 00:49:12 +00:00
|
|
|
pub struct LintDiagnosticBuilder<'a, G: EmissionGuarantee>(DiagnosticBuilder<'a, G>);
|
2020-01-31 12:24:57 +00:00
|
|
|
|
2022-01-23 00:49:12 +00:00
|
|
|
impl<'a, G: EmissionGuarantee> LintDiagnosticBuilder<'a, G> {
|
|
|
|
/// Return the inner `DiagnosticBuilder`, first setting the primary message to `msg`.
|
|
|
|
pub fn build(mut self, msg: &str) -> DiagnosticBuilder<'a, G> {
|
2020-01-31 12:24:57 +00:00
|
|
|
self.0.set_primary_message(msg);
|
2021-09-04 11:26:25 +00:00
|
|
|
self.0.set_is_lint();
|
2020-01-31 12:24:57 +00:00
|
|
|
self.0
|
|
|
|
}
|
|
|
|
|
2022-01-23 00:49:12 +00:00
|
|
|
/// Create a `LintDiagnosticBuilder` from some existing `DiagnosticBuilder`.
|
|
|
|
pub fn new(err: DiagnosticBuilder<'a, G>) -> LintDiagnosticBuilder<'a, G> {
|
2020-01-31 12:24:57 +00:00
|
|
|
LintDiagnosticBuilder(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-23 00:49:12 +00:00
|
|
|
impl<'a> LintDiagnosticBuilder<'a, ErrorGuaranteed> {
|
|
|
|
pub fn forget_guarantee(self) -> LintDiagnosticBuilder<'a, ()> {
|
|
|
|
LintDiagnosticBuilder(self.0.forget_guarantee())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-23 20:41:46 +00:00
|
|
|
pub fn explain_lint_level_source(
|
|
|
|
sess: &Session,
|
Improve `unused_unsafe` lint
Main motivation: Fixes some issues with the current behavior. This PR is
more-or-less completely re-implementing the unused_unsafe lint; it’s also only
done in the MIR-version of the lint, the set of tests for the `-Zthir-unsafeck`
version no longer succeeds (and is thus disabled, see `lint-unused-unsafe.rs`).
On current nightly,
```rs
unsafe fn unsf() {}
fn inner_ignored() {
unsafe {
#[allow(unused_unsafe)]
unsafe {
unsf()
}
}
}
```
doesn’t create any warnings. This situation is not unrealistic to come by, the
inner `unsafe` block could e.g. come from a macro. Actually, this PR even
includes removal of one unused `unsafe` in the standard library that was missed
in a similar situation. (The inner `unsafe` coming from an external macro hides
the warning, too.)
The reason behind this problem is how the check currently works:
* While generating MIR, it already skips nested unsafe blocks (i.e. unsafe
nested in other unsafe) so that the inner one is always the one considered
unused
* To differentiate the cases of no unsafe operations inside the `unsafe` vs.
a surrounding `unsafe` block, there’s some ad-hoc magic walking up the HIR to
look for surrounding used `unsafe` blocks.
There’s a lot of problems with this approach besides the one presented above.
E.g. the MIR-building uses checks for `unsafe_op_in_unsafe_fn` lint to decide
early whether or not `unsafe` blocks in an `unsafe fn` are redundant and ought
to be removed.
```rs
unsafe fn granular_disallow_op_in_unsafe_fn() {
unsafe {
#[deny(unsafe_op_in_unsafe_fn)]
{
unsf();
}
}
}
```
```
error: call to unsafe function is unsafe and requires unsafe block (error E0133)
--> src/main.rs:13:13
|
13 | unsf();
| ^^^^^^ call to unsafe function
|
note: the lint level is defined here
--> src/main.rs:11:16
|
11 | #[deny(unsafe_op_in_unsafe_fn)]
| ^^^^^^^^^^^^^^^^^^^^^^
= note: consult the function's documentation for information on how to avoid undefined behavior
warning: unnecessary `unsafe` block
--> src/main.rs:10:5
|
9 | unsafe fn granular_disallow_op_in_unsafe_fn() {
| --------------------------------------------- because it's nested under this `unsafe` fn
10 | unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
Here, the intermediate `unsafe` was ignored, even though it contains a unsafe
operation that is not allowed to happen in an `unsafe fn` without an additional `unsafe` block.
Also closures were problematic and the workaround/algorithms used on current
nightly didn’t work properly. (I skipped trying to fully understand what it was
supposed to do, because this PR uses a completely different approach.)
```rs
fn nested() {
unsafe {
unsafe { unsf() }
}
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
vs
```rs
fn nested() {
let _ = || unsafe {
let _ = || unsafe { unsf() };
};
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:9:16
|
9 | let _ = || unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:10:20
|
10 | let _ = || unsafe { unsf() };
| ^^^^^^ unnecessary `unsafe` block
```
*note that this warning kind-of suggests that **both** unsafe blocks are redundant*
--------------------------------------------------------------------------------
I also dislike the fact that it always suggests keeping the outermost `unsafe`.
E.g. for
```rs
fn granularity() {
unsafe {
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
I prefer if `rustc` suggests removing the more-course outer-level `unsafe`
instead of the fine-grained inner `unsafe` blocks, which it currently does on nightly:
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
--------------------------------------------------------------------------------
Needless to say, this PR addresses all these points. For context, as far as my
understanding goes, the main advantage of skipping inner unsafe blocks was that
a test case like
```rs
fn top_level_used() {
unsafe {
unsf();
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
should generate some warning because there’s redundant nested `unsafe`, however
every single `unsafe` block _does_ contain some statement that uses it. Of course
this PR doesn’t aim change the warnings on this kind of code example, because
the current behavior, warning on all the inner `unsafe` blocks, makes sense in this case.
As mentioned, during MIR building all the unsafe blocks *are* kept now, and usage
is attributed to them. The way to still generate a warning like
```
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsf();
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:13:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
13 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
in this case is by emitting a `unused_unsafe` warning for all of the `unsafe`
blocks that are _within a **used** unsafe block_.
The previous code had a little HIR traversal already anyways to collect a set of
all the unsafe blocks (in order to afterwards determine which ones are unused
afterwards). This PR uses such a traversal to do additional things including logic
like _always_ warn for an `unsafe` block that’s inside of another **used**
unsafe block. The traversal is expanded to include nested closures in the same go,
this simplifies a lot of things.
The whole logic around `unsafe_op_in_unsafe_fn` is a little complicated, there’s
some test cases of corner-cases in this PR. (The implementation involves
differentiating between whether a used unsafe block was used exclusively by
operations where `allow(unsafe_op_in_unsafe_fn)` was active.) The main goal was
to make sure that code should compile successfully if all the `unused_unsafe`-warnings
are addressed _simultaneously_ (by removing the respective `unsafe` blocks)
no matter how complicated the patterns of `unsafe_op_in_unsafe_fn` being
disallowed and allowed throughout the function are.
--------------------------------------------------------------------------------
One noteworthy design decision I took here: An `unsafe` block
with `allow(unused_unsafe)` **is considered used** for the purposes of
linting about redundant contained unsafe blocks. So while
```rs
fn granularity() {
unsafe { //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
warns for the outer `unsafe` block,
```rs
fn top_level_ignored() {
#[allow(unused_unsafe)]
unsafe {
#[deny(unused_unsafe)]
{
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
}
}
}
```
warns on the inner ones.
2022-02-03 21:16:06 +00:00
|
|
|
lint: &'static Lint,
|
|
|
|
level: Level,
|
|
|
|
src: LintLevelSource,
|
2022-01-23 20:41:46 +00:00
|
|
|
err: &mut Diagnostic,
|
Improve `unused_unsafe` lint
Main motivation: Fixes some issues with the current behavior. This PR is
more-or-less completely re-implementing the unused_unsafe lint; it’s also only
done in the MIR-version of the lint, the set of tests for the `-Zthir-unsafeck`
version no longer succeeds (and is thus disabled, see `lint-unused-unsafe.rs`).
On current nightly,
```rs
unsafe fn unsf() {}
fn inner_ignored() {
unsafe {
#[allow(unused_unsafe)]
unsafe {
unsf()
}
}
}
```
doesn’t create any warnings. This situation is not unrealistic to come by, the
inner `unsafe` block could e.g. come from a macro. Actually, this PR even
includes removal of one unused `unsafe` in the standard library that was missed
in a similar situation. (The inner `unsafe` coming from an external macro hides
the warning, too.)
The reason behind this problem is how the check currently works:
* While generating MIR, it already skips nested unsafe blocks (i.e. unsafe
nested in other unsafe) so that the inner one is always the one considered
unused
* To differentiate the cases of no unsafe operations inside the `unsafe` vs.
a surrounding `unsafe` block, there’s some ad-hoc magic walking up the HIR to
look for surrounding used `unsafe` blocks.
There’s a lot of problems with this approach besides the one presented above.
E.g. the MIR-building uses checks for `unsafe_op_in_unsafe_fn` lint to decide
early whether or not `unsafe` blocks in an `unsafe fn` are redundant and ought
to be removed.
```rs
unsafe fn granular_disallow_op_in_unsafe_fn() {
unsafe {
#[deny(unsafe_op_in_unsafe_fn)]
{
unsf();
}
}
}
```
```
error: call to unsafe function is unsafe and requires unsafe block (error E0133)
--> src/main.rs:13:13
|
13 | unsf();
| ^^^^^^ call to unsafe function
|
note: the lint level is defined here
--> src/main.rs:11:16
|
11 | #[deny(unsafe_op_in_unsafe_fn)]
| ^^^^^^^^^^^^^^^^^^^^^^
= note: consult the function's documentation for information on how to avoid undefined behavior
warning: unnecessary `unsafe` block
--> src/main.rs:10:5
|
9 | unsafe fn granular_disallow_op_in_unsafe_fn() {
| --------------------------------------------- because it's nested under this `unsafe` fn
10 | unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
Here, the intermediate `unsafe` was ignored, even though it contains a unsafe
operation that is not allowed to happen in an `unsafe fn` without an additional `unsafe` block.
Also closures were problematic and the workaround/algorithms used on current
nightly didn’t work properly. (I skipped trying to fully understand what it was
supposed to do, because this PR uses a completely different approach.)
```rs
fn nested() {
unsafe {
unsafe { unsf() }
}
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
vs
```rs
fn nested() {
let _ = || unsafe {
let _ = || unsafe { unsf() };
};
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:9:16
|
9 | let _ = || unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:10:20
|
10 | let _ = || unsafe { unsf() };
| ^^^^^^ unnecessary `unsafe` block
```
*note that this warning kind-of suggests that **both** unsafe blocks are redundant*
--------------------------------------------------------------------------------
I also dislike the fact that it always suggests keeping the outermost `unsafe`.
E.g. for
```rs
fn granularity() {
unsafe {
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
I prefer if `rustc` suggests removing the more-course outer-level `unsafe`
instead of the fine-grained inner `unsafe` blocks, which it currently does on nightly:
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
--------------------------------------------------------------------------------
Needless to say, this PR addresses all these points. For context, as far as my
understanding goes, the main advantage of skipping inner unsafe blocks was that
a test case like
```rs
fn top_level_used() {
unsafe {
unsf();
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
should generate some warning because there’s redundant nested `unsafe`, however
every single `unsafe` block _does_ contain some statement that uses it. Of course
this PR doesn’t aim change the warnings on this kind of code example, because
the current behavior, warning on all the inner `unsafe` blocks, makes sense in this case.
As mentioned, during MIR building all the unsafe blocks *are* kept now, and usage
is attributed to them. The way to still generate a warning like
```
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsf();
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:13:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
13 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
in this case is by emitting a `unused_unsafe` warning for all of the `unsafe`
blocks that are _within a **used** unsafe block_.
The previous code had a little HIR traversal already anyways to collect a set of
all the unsafe blocks (in order to afterwards determine which ones are unused
afterwards). This PR uses such a traversal to do additional things including logic
like _always_ warn for an `unsafe` block that’s inside of another **used**
unsafe block. The traversal is expanded to include nested closures in the same go,
this simplifies a lot of things.
The whole logic around `unsafe_op_in_unsafe_fn` is a little complicated, there’s
some test cases of corner-cases in this PR. (The implementation involves
differentiating between whether a used unsafe block was used exclusively by
operations where `allow(unsafe_op_in_unsafe_fn)` was active.) The main goal was
to make sure that code should compile successfully if all the `unused_unsafe`-warnings
are addressed _simultaneously_ (by removing the respective `unsafe` blocks)
no matter how complicated the patterns of `unsafe_op_in_unsafe_fn` being
disallowed and allowed throughout the function are.
--------------------------------------------------------------------------------
One noteworthy design decision I took here: An `unsafe` block
with `allow(unused_unsafe)` **is considered used** for the purposes of
linting about redundant contained unsafe blocks. So while
```rs
fn granularity() {
unsafe { //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
warns for the outer `unsafe` block,
```rs
fn top_level_ignored() {
#[allow(unused_unsafe)]
unsafe {
#[deny(unused_unsafe)]
{
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
}
}
}
```
warns on the inner ones.
2022-02-03 21:16:06 +00:00
|
|
|
) {
|
|
|
|
let name = lint.name_lower();
|
|
|
|
match src {
|
|
|
|
LintLevelSource::Default => {
|
|
|
|
sess.diag_note_once(
|
|
|
|
err,
|
|
|
|
DiagnosticMessageId::from(lint),
|
|
|
|
&format!("`#[{}({})]` on by default", level.as_str(), name),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
LintLevelSource::CommandLine(lint_flag_val, orig_level) => {
|
|
|
|
let flag = match orig_level {
|
|
|
|
Level::Warn => "-W",
|
|
|
|
Level::Deny => "-D",
|
|
|
|
Level::Forbid => "-F",
|
|
|
|
Level::Allow => "-A",
|
|
|
|
Level::ForceWarn => "--force-warn",
|
2021-08-06 21:28:58 +00:00
|
|
|
Level::Expect(_) => {
|
|
|
|
unreachable!("the expect level does not have a commandline flag")
|
|
|
|
}
|
Improve `unused_unsafe` lint
Main motivation: Fixes some issues with the current behavior. This PR is
more-or-less completely re-implementing the unused_unsafe lint; it’s also only
done in the MIR-version of the lint, the set of tests for the `-Zthir-unsafeck`
version no longer succeeds (and is thus disabled, see `lint-unused-unsafe.rs`).
On current nightly,
```rs
unsafe fn unsf() {}
fn inner_ignored() {
unsafe {
#[allow(unused_unsafe)]
unsafe {
unsf()
}
}
}
```
doesn’t create any warnings. This situation is not unrealistic to come by, the
inner `unsafe` block could e.g. come from a macro. Actually, this PR even
includes removal of one unused `unsafe` in the standard library that was missed
in a similar situation. (The inner `unsafe` coming from an external macro hides
the warning, too.)
The reason behind this problem is how the check currently works:
* While generating MIR, it already skips nested unsafe blocks (i.e. unsafe
nested in other unsafe) so that the inner one is always the one considered
unused
* To differentiate the cases of no unsafe operations inside the `unsafe` vs.
a surrounding `unsafe` block, there’s some ad-hoc magic walking up the HIR to
look for surrounding used `unsafe` blocks.
There’s a lot of problems with this approach besides the one presented above.
E.g. the MIR-building uses checks for `unsafe_op_in_unsafe_fn` lint to decide
early whether or not `unsafe` blocks in an `unsafe fn` are redundant and ought
to be removed.
```rs
unsafe fn granular_disallow_op_in_unsafe_fn() {
unsafe {
#[deny(unsafe_op_in_unsafe_fn)]
{
unsf();
}
}
}
```
```
error: call to unsafe function is unsafe and requires unsafe block (error E0133)
--> src/main.rs:13:13
|
13 | unsf();
| ^^^^^^ call to unsafe function
|
note: the lint level is defined here
--> src/main.rs:11:16
|
11 | #[deny(unsafe_op_in_unsafe_fn)]
| ^^^^^^^^^^^^^^^^^^^^^^
= note: consult the function's documentation for information on how to avoid undefined behavior
warning: unnecessary `unsafe` block
--> src/main.rs:10:5
|
9 | unsafe fn granular_disallow_op_in_unsafe_fn() {
| --------------------------------------------- because it's nested under this `unsafe` fn
10 | unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
Here, the intermediate `unsafe` was ignored, even though it contains a unsafe
operation that is not allowed to happen in an `unsafe fn` without an additional `unsafe` block.
Also closures were problematic and the workaround/algorithms used on current
nightly didn’t work properly. (I skipped trying to fully understand what it was
supposed to do, because this PR uses a completely different approach.)
```rs
fn nested() {
unsafe {
unsafe { unsf() }
}
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
vs
```rs
fn nested() {
let _ = || unsafe {
let _ = || unsafe { unsf() };
};
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:9:16
|
9 | let _ = || unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:10:20
|
10 | let _ = || unsafe { unsf() };
| ^^^^^^ unnecessary `unsafe` block
```
*note that this warning kind-of suggests that **both** unsafe blocks are redundant*
--------------------------------------------------------------------------------
I also dislike the fact that it always suggests keeping the outermost `unsafe`.
E.g. for
```rs
fn granularity() {
unsafe {
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
I prefer if `rustc` suggests removing the more-course outer-level `unsafe`
instead of the fine-grained inner `unsafe` blocks, which it currently does on nightly:
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
--------------------------------------------------------------------------------
Needless to say, this PR addresses all these points. For context, as far as my
understanding goes, the main advantage of skipping inner unsafe blocks was that
a test case like
```rs
fn top_level_used() {
unsafe {
unsf();
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
should generate some warning because there’s redundant nested `unsafe`, however
every single `unsafe` block _does_ contain some statement that uses it. Of course
this PR doesn’t aim change the warnings on this kind of code example, because
the current behavior, warning on all the inner `unsafe` blocks, makes sense in this case.
As mentioned, during MIR building all the unsafe blocks *are* kept now, and usage
is attributed to them. The way to still generate a warning like
```
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsf();
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:13:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
13 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
in this case is by emitting a `unused_unsafe` warning for all of the `unsafe`
blocks that are _within a **used** unsafe block_.
The previous code had a little HIR traversal already anyways to collect a set of
all the unsafe blocks (in order to afterwards determine which ones are unused
afterwards). This PR uses such a traversal to do additional things including logic
like _always_ warn for an `unsafe` block that’s inside of another **used**
unsafe block. The traversal is expanded to include nested closures in the same go,
this simplifies a lot of things.
The whole logic around `unsafe_op_in_unsafe_fn` is a little complicated, there’s
some test cases of corner-cases in this PR. (The implementation involves
differentiating between whether a used unsafe block was used exclusively by
operations where `allow(unsafe_op_in_unsafe_fn)` was active.) The main goal was
to make sure that code should compile successfully if all the `unused_unsafe`-warnings
are addressed _simultaneously_ (by removing the respective `unsafe` blocks)
no matter how complicated the patterns of `unsafe_op_in_unsafe_fn` being
disallowed and allowed throughout the function are.
--------------------------------------------------------------------------------
One noteworthy design decision I took here: An `unsafe` block
with `allow(unused_unsafe)` **is considered used** for the purposes of
linting about redundant contained unsafe blocks. So while
```rs
fn granularity() {
unsafe { //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
warns for the outer `unsafe` block,
```rs
fn top_level_ignored() {
#[allow(unused_unsafe)]
unsafe {
#[deny(unused_unsafe)]
{
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
}
}
}
```
warns on the inner ones.
2022-02-03 21:16:06 +00:00
|
|
|
};
|
|
|
|
let hyphen_case_lint_name = name.replace('_', "-");
|
|
|
|
if lint_flag_val.as_str() == name {
|
|
|
|
sess.diag_note_once(
|
|
|
|
err,
|
|
|
|
DiagnosticMessageId::from(lint),
|
|
|
|
&format!(
|
|
|
|
"requested on the command line with `{} {}`",
|
|
|
|
flag, hyphen_case_lint_name
|
|
|
|
),
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
let hyphen_case_flag_val = lint_flag_val.as_str().replace('_', "-");
|
|
|
|
sess.diag_note_once(
|
|
|
|
err,
|
|
|
|
DiagnosticMessageId::from(lint),
|
|
|
|
&format!(
|
|
|
|
"`{} {}` implied by `{} {}`",
|
|
|
|
flag, hyphen_case_lint_name, flag, hyphen_case_flag_val
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
LintLevelSource::Node(lint_attr_name, src, reason) => {
|
|
|
|
if let Some(rationale) = reason {
|
|
|
|
err.note(rationale.as_str());
|
|
|
|
}
|
|
|
|
sess.diag_span_note_once(
|
|
|
|
err,
|
|
|
|
DiagnosticMessageId::from(lint),
|
|
|
|
src,
|
|
|
|
"the lint level is defined here",
|
|
|
|
);
|
|
|
|
if lint_attr_name.as_str() != name {
|
|
|
|
let level_str = level.as_str();
|
|
|
|
sess.diag_note_once(
|
|
|
|
err,
|
|
|
|
DiagnosticMessageId::from(lint),
|
|
|
|
&format!(
|
|
|
|
"`#[{}({})]` implied by `#[{}({})]`",
|
|
|
|
level_str, name, level_str, lint_attr_name
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-31 20:57:50 +00:00
|
|
|
pub fn struct_lint_level<'s, 'd>(
|
2020-01-31 12:24:57 +00:00
|
|
|
sess: &'s Session,
|
2020-01-09 04:57:07 +00:00
|
|
|
lint: &'static Lint,
|
|
|
|
level: Level,
|
2020-12-21 22:17:53 +00:00
|
|
|
src: LintLevelSource,
|
2020-01-09 04:57:07 +00:00
|
|
|
span: Option<MultiSpan>,
|
2022-01-23 00:49:12 +00:00
|
|
|
decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>) + 'd,
|
2020-01-31 20:57:50 +00:00
|
|
|
) {
|
|
|
|
// Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to
|
|
|
|
// the "real" work.
|
2021-12-16 00:32:30 +00:00
|
|
|
fn struct_lint_level_impl<'s, 'd>(
|
2020-01-31 20:57:50 +00:00
|
|
|
sess: &'s Session,
|
|
|
|
lint: &'static Lint,
|
|
|
|
level: Level,
|
2020-12-21 22:17:53 +00:00
|
|
|
src: LintLevelSource,
|
2020-01-31 20:57:50 +00:00
|
|
|
span: Option<MultiSpan>,
|
2022-01-23 00:49:12 +00:00
|
|
|
decorate: Box<dyn for<'b> FnOnce(LintDiagnosticBuilder<'b, ()>) + 'd>,
|
2020-02-01 23:47:58 +00:00
|
|
|
) {
|
2020-08-13 19:41:52 +00:00
|
|
|
// Check for future incompatibility lints and issue a stronger warning.
|
|
|
|
let future_incompatible = lint.future_incompatible;
|
|
|
|
|
2021-06-20 00:06:46 +00:00
|
|
|
let has_future_breakage = future_incompatible.map_or(
|
|
|
|
// Default allow lints trigger too often for testing.
|
|
|
|
sess.opts.debugging_opts.future_incompat_test && lint.default_level != Level::Allow,
|
|
|
|
|incompat| {
|
|
|
|
matches!(incompat.reason, FutureIncompatibilityReason::FutureReleaseErrorReportNow)
|
|
|
|
},
|
2021-07-11 20:08:58 +00:00
|
|
|
);
|
2020-08-13 19:41:52 +00:00
|
|
|
|
2020-01-31 20:57:50 +00:00
|
|
|
let mut err = match (level, span) {
|
2020-08-13 19:41:52 +00:00
|
|
|
(Level::Allow, span) => {
|
|
|
|
if has_future_breakage {
|
|
|
|
if let Some(span) = span {
|
|
|
|
sess.struct_span_allow(span, "")
|
|
|
|
} else {
|
|
|
|
sess.struct_allow("")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
}
|
2020-01-31 20:57:50 +00:00
|
|
|
}
|
2021-08-06 21:18:16 +00:00
|
|
|
(Level::Expect(expect_id), _) => {
|
|
|
|
// This case is special as we actually allow the lint itself in this context, but
|
|
|
|
// we can't return early like in the case for `Level::Allow` because we still
|
|
|
|
// need the lint diagnostic to be emitted to `rustc_error::HanderInner`.
|
|
|
|
//
|
|
|
|
// We can also not mark the lint expectation as fulfilled here right away, as it
|
|
|
|
// can still be cancelled in the decorate function. All of this means that we simply
|
|
|
|
// create a `DiagnosticBuilder` and continue as we would for warnings.
|
|
|
|
sess.struct_expect("", expect_id)
|
|
|
|
}
|
2022-01-26 03:46:56 +00:00
|
|
|
(Level::Warn | Level::ForceWarn, Some(span)) => sess.struct_span_warn(span, ""),
|
|
|
|
(Level::Warn | Level::ForceWarn, None) => sess.struct_warn(""),
|
2021-07-21 03:23:22 +00:00
|
|
|
(Level::Deny | Level::Forbid, Some(span)) => {
|
|
|
|
let mut builder = sess.diagnostic().struct_err_lint("");
|
|
|
|
builder.set_span(span);
|
|
|
|
builder
|
|
|
|
}
|
|
|
|
(Level::Deny | Level::Forbid, None) => sess.diagnostic().struct_err_lint(""),
|
2020-01-31 20:57:50 +00:00
|
|
|
};
|
2020-01-09 04:57:07 +00:00
|
|
|
|
2020-01-31 20:57:50 +00:00
|
|
|
// If this code originates in a foreign macro, aka something that this crate
|
|
|
|
// did not itself author, then it's likely that there's nothing this crate
|
|
|
|
// can do about it. We probably want to skip the lint entirely.
|
|
|
|
if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
|
|
|
|
// Any suggestions made here are likely to be incorrect, so anything we
|
|
|
|
// emit shouldn't be automatically fixed by rustfix.
|
2022-01-24 09:19:33 +00:00
|
|
|
err.disable_suggestions();
|
2020-01-31 20:57:50 +00:00
|
|
|
|
2021-04-14 16:56:13 +00:00
|
|
|
// If this is a future incompatible that is not an edition fixing lint
|
|
|
|
// it'll become a hard error, so we have to emit *something*. Also,
|
|
|
|
// if this lint occurs in the expansion of a macro from an external crate,
|
|
|
|
// allow individual lints to opt-out from being reported.
|
|
|
|
let not_future_incompatible =
|
2021-06-15 15:16:21 +00:00
|
|
|
future_incompatible.map(|f| f.reason.edition().is_some()).unwrap_or(true);
|
2021-04-14 16:56:13 +00:00
|
|
|
if not_future_incompatible && !lint.report_in_external_macro {
|
2020-01-31 20:57:50 +00:00
|
|
|
err.cancel();
|
|
|
|
// Don't continue further, since we don't want to have
|
|
|
|
// `diag_span_note_once` called for a diagnostic that isn't emitted.
|
|
|
|
return;
|
|
|
|
}
|
2020-01-09 04:57:07 +00:00
|
|
|
}
|
2020-01-31 20:57:50 +00:00
|
|
|
|
2021-08-06 21:18:16 +00:00
|
|
|
// Lint diagnostics that are covered by the expect level will not be emitted outside
|
|
|
|
// the compiler. It is therefore not necessary to add any information for the user.
|
2022-02-18 11:00:16 +00:00
|
|
|
// This will therefore directly call the decorate function which will in turn emit
|
2021-08-06 21:18:16 +00:00
|
|
|
// the `Diagnostic`.
|
|
|
|
if let Level::Expect(_) = level {
|
|
|
|
let name = lint.name_lower();
|
|
|
|
err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn: false });
|
|
|
|
decorate(LintDiagnosticBuilder::new(err));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
Improve `unused_unsafe` lint
Main motivation: Fixes some issues with the current behavior. This PR is
more-or-less completely re-implementing the unused_unsafe lint; it’s also only
done in the MIR-version of the lint, the set of tests for the `-Zthir-unsafeck`
version no longer succeeds (and is thus disabled, see `lint-unused-unsafe.rs`).
On current nightly,
```rs
unsafe fn unsf() {}
fn inner_ignored() {
unsafe {
#[allow(unused_unsafe)]
unsafe {
unsf()
}
}
}
```
doesn’t create any warnings. This situation is not unrealistic to come by, the
inner `unsafe` block could e.g. come from a macro. Actually, this PR even
includes removal of one unused `unsafe` in the standard library that was missed
in a similar situation. (The inner `unsafe` coming from an external macro hides
the warning, too.)
The reason behind this problem is how the check currently works:
* While generating MIR, it already skips nested unsafe blocks (i.e. unsafe
nested in other unsafe) so that the inner one is always the one considered
unused
* To differentiate the cases of no unsafe operations inside the `unsafe` vs.
a surrounding `unsafe` block, there’s some ad-hoc magic walking up the HIR to
look for surrounding used `unsafe` blocks.
There’s a lot of problems with this approach besides the one presented above.
E.g. the MIR-building uses checks for `unsafe_op_in_unsafe_fn` lint to decide
early whether or not `unsafe` blocks in an `unsafe fn` are redundant and ought
to be removed.
```rs
unsafe fn granular_disallow_op_in_unsafe_fn() {
unsafe {
#[deny(unsafe_op_in_unsafe_fn)]
{
unsf();
}
}
}
```
```
error: call to unsafe function is unsafe and requires unsafe block (error E0133)
--> src/main.rs:13:13
|
13 | unsf();
| ^^^^^^ call to unsafe function
|
note: the lint level is defined here
--> src/main.rs:11:16
|
11 | #[deny(unsafe_op_in_unsafe_fn)]
| ^^^^^^^^^^^^^^^^^^^^^^
= note: consult the function's documentation for information on how to avoid undefined behavior
warning: unnecessary `unsafe` block
--> src/main.rs:10:5
|
9 | unsafe fn granular_disallow_op_in_unsafe_fn() {
| --------------------------------------------- because it's nested under this `unsafe` fn
10 | unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
Here, the intermediate `unsafe` was ignored, even though it contains a unsafe
operation that is not allowed to happen in an `unsafe fn` without an additional `unsafe` block.
Also closures were problematic and the workaround/algorithms used on current
nightly didn’t work properly. (I skipped trying to fully understand what it was
supposed to do, because this PR uses a completely different approach.)
```rs
fn nested() {
unsafe {
unsafe { unsf() }
}
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
vs
```rs
fn nested() {
let _ = || unsafe {
let _ = || unsafe { unsf() };
};
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:9:16
|
9 | let _ = || unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:10:20
|
10 | let _ = || unsafe { unsf() };
| ^^^^^^ unnecessary `unsafe` block
```
*note that this warning kind-of suggests that **both** unsafe blocks are redundant*
--------------------------------------------------------------------------------
I also dislike the fact that it always suggests keeping the outermost `unsafe`.
E.g. for
```rs
fn granularity() {
unsafe {
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
I prefer if `rustc` suggests removing the more-course outer-level `unsafe`
instead of the fine-grained inner `unsafe` blocks, which it currently does on nightly:
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
--------------------------------------------------------------------------------
Needless to say, this PR addresses all these points. For context, as far as my
understanding goes, the main advantage of skipping inner unsafe blocks was that
a test case like
```rs
fn top_level_used() {
unsafe {
unsf();
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
should generate some warning because there’s redundant nested `unsafe`, however
every single `unsafe` block _does_ contain some statement that uses it. Of course
this PR doesn’t aim change the warnings on this kind of code example, because
the current behavior, warning on all the inner `unsafe` blocks, makes sense in this case.
As mentioned, during MIR building all the unsafe blocks *are* kept now, and usage
is attributed to them. The way to still generate a warning like
```
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsf();
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:13:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
13 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
in this case is by emitting a `unused_unsafe` warning for all of the `unsafe`
blocks that are _within a **used** unsafe block_.
The previous code had a little HIR traversal already anyways to collect a set of
all the unsafe blocks (in order to afterwards determine which ones are unused
afterwards). This PR uses such a traversal to do additional things including logic
like _always_ warn for an `unsafe` block that’s inside of another **used**
unsafe block. The traversal is expanded to include nested closures in the same go,
this simplifies a lot of things.
The whole logic around `unsafe_op_in_unsafe_fn` is a little complicated, there’s
some test cases of corner-cases in this PR. (The implementation involves
differentiating between whether a used unsafe block was used exclusively by
operations where `allow(unsafe_op_in_unsafe_fn)` was active.) The main goal was
to make sure that code should compile successfully if all the `unused_unsafe`-warnings
are addressed _simultaneously_ (by removing the respective `unsafe` blocks)
no matter how complicated the patterns of `unsafe_op_in_unsafe_fn` being
disallowed and allowed throughout the function are.
--------------------------------------------------------------------------------
One noteworthy design decision I took here: An `unsafe` block
with `allow(unused_unsafe)` **is considered used** for the purposes of
linting about redundant contained unsafe blocks. So while
```rs
fn granularity() {
unsafe { //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
warns for the outer `unsafe` block,
```rs
fn top_level_ignored() {
#[allow(unused_unsafe)]
unsafe {
#[deny(unused_unsafe)]
{
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
}
}
}
```
warns on the inner ones.
2022-02-03 21:16:06 +00:00
|
|
|
explain_lint_level_source(sess, lint, level, src, &mut err);
|
2020-01-09 04:57:07 +00:00
|
|
|
|
Improve `unused_unsafe` lint
Main motivation: Fixes some issues with the current behavior. This PR is
more-or-less completely re-implementing the unused_unsafe lint; it’s also only
done in the MIR-version of the lint, the set of tests for the `-Zthir-unsafeck`
version no longer succeeds (and is thus disabled, see `lint-unused-unsafe.rs`).
On current nightly,
```rs
unsafe fn unsf() {}
fn inner_ignored() {
unsafe {
#[allow(unused_unsafe)]
unsafe {
unsf()
}
}
}
```
doesn’t create any warnings. This situation is not unrealistic to come by, the
inner `unsafe` block could e.g. come from a macro. Actually, this PR even
includes removal of one unused `unsafe` in the standard library that was missed
in a similar situation. (The inner `unsafe` coming from an external macro hides
the warning, too.)
The reason behind this problem is how the check currently works:
* While generating MIR, it already skips nested unsafe blocks (i.e. unsafe
nested in other unsafe) so that the inner one is always the one considered
unused
* To differentiate the cases of no unsafe operations inside the `unsafe` vs.
a surrounding `unsafe` block, there’s some ad-hoc magic walking up the HIR to
look for surrounding used `unsafe` blocks.
There’s a lot of problems with this approach besides the one presented above.
E.g. the MIR-building uses checks for `unsafe_op_in_unsafe_fn` lint to decide
early whether or not `unsafe` blocks in an `unsafe fn` are redundant and ought
to be removed.
```rs
unsafe fn granular_disallow_op_in_unsafe_fn() {
unsafe {
#[deny(unsafe_op_in_unsafe_fn)]
{
unsf();
}
}
}
```
```
error: call to unsafe function is unsafe and requires unsafe block (error E0133)
--> src/main.rs:13:13
|
13 | unsf();
| ^^^^^^ call to unsafe function
|
note: the lint level is defined here
--> src/main.rs:11:16
|
11 | #[deny(unsafe_op_in_unsafe_fn)]
| ^^^^^^^^^^^^^^^^^^^^^^
= note: consult the function's documentation for information on how to avoid undefined behavior
warning: unnecessary `unsafe` block
--> src/main.rs:10:5
|
9 | unsafe fn granular_disallow_op_in_unsafe_fn() {
| --------------------------------------------- because it's nested under this `unsafe` fn
10 | unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
Here, the intermediate `unsafe` was ignored, even though it contains a unsafe
operation that is not allowed to happen in an `unsafe fn` without an additional `unsafe` block.
Also closures were problematic and the workaround/algorithms used on current
nightly didn’t work properly. (I skipped trying to fully understand what it was
supposed to do, because this PR uses a completely different approach.)
```rs
fn nested() {
unsafe {
unsafe { unsf() }
}
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
```
vs
```rs
fn nested() {
let _ = || unsafe {
let _ = || unsafe { unsf() };
};
}
```
```
warning: unnecessary `unsafe` block
--> src/main.rs:9:16
|
9 | let _ = || unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:10:20
|
10 | let _ = || unsafe { unsf() };
| ^^^^^^ unnecessary `unsafe` block
```
*note that this warning kind-of suggests that **both** unsafe blocks are redundant*
--------------------------------------------------------------------------------
I also dislike the fact that it always suggests keeping the outermost `unsafe`.
E.g. for
```rs
fn granularity() {
unsafe {
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
I prefer if `rustc` suggests removing the more-course outer-level `unsafe`
instead of the fine-grained inner `unsafe` blocks, which it currently does on nightly:
```
warning: unnecessary `unsafe` block
--> src/main.rs:10:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsafe { unsf() }
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
--------------------------------------------------------------------------------
Needless to say, this PR addresses all these points. For context, as far as my
understanding goes, the main advantage of skipping inner unsafe blocks was that
a test case like
```rs
fn top_level_used() {
unsafe {
unsf();
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
should generate some warning because there’s redundant nested `unsafe`, however
every single `unsafe` block _does_ contain some statement that uses it. Of course
this PR doesn’t aim change the warnings on this kind of code example, because
the current behavior, warning on all the inner `unsafe` blocks, makes sense in this case.
As mentioned, during MIR building all the unsafe blocks *are* kept now, and usage
is attributed to them. The way to still generate a warning like
```
warning: unnecessary `unsafe` block
--> src/main.rs:11:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
10 | unsf();
11 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` on by default
warning: unnecessary `unsafe` block
--> src/main.rs:12:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
12 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
warning: unnecessary `unsafe` block
--> src/main.rs:13:9
|
9 | unsafe {
| ------ because it's nested under this `unsafe` block
...
13 | unsafe { unsf() }
| ^^^^^^ unnecessary `unsafe` block
```
in this case is by emitting a `unused_unsafe` warning for all of the `unsafe`
blocks that are _within a **used** unsafe block_.
The previous code had a little HIR traversal already anyways to collect a set of
all the unsafe blocks (in order to afterwards determine which ones are unused
afterwards). This PR uses such a traversal to do additional things including logic
like _always_ warn for an `unsafe` block that’s inside of another **used**
unsafe block. The traversal is expanded to include nested closures in the same go,
this simplifies a lot of things.
The whole logic around `unsafe_op_in_unsafe_fn` is a little complicated, there’s
some test cases of corner-cases in this PR. (The implementation involves
differentiating between whether a used unsafe block was used exclusively by
operations where `allow(unsafe_op_in_unsafe_fn)` was active.) The main goal was
to make sure that code should compile successfully if all the `unused_unsafe`-warnings
are addressed _simultaneously_ (by removing the respective `unsafe` blocks)
no matter how complicated the patterns of `unsafe_op_in_unsafe_fn` being
disallowed and allowed throughout the function are.
--------------------------------------------------------------------------------
One noteworthy design decision I took here: An `unsafe` block
with `allow(unused_unsafe)` **is considered used** for the purposes of
linting about redundant contained unsafe blocks. So while
```rs
fn granularity() {
unsafe { //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() }
unsafe { unsf() }
unsafe { unsf() }
}
}
```
warns for the outer `unsafe` block,
```rs
fn top_level_ignored() {
#[allow(unused_unsafe)]
unsafe {
#[deny(unused_unsafe)]
{
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
unsafe { unsf() } //~ ERROR: unnecessary `unsafe` block
}
}
}
```
warns on the inner ones.
2022-02-03 21:16:06 +00:00
|
|
|
let name = lint.name_lower();
|
2021-07-06 11:47:03 +00:00
|
|
|
let is_force_warn = matches!(level, Level::ForceWarn);
|
2021-06-04 12:37:20 +00:00
|
|
|
err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn });
|
2020-01-31 20:57:50 +00:00
|
|
|
|
|
|
|
if let Some(future_incompatible) = future_incompatible {
|
2022-01-27 09:49:32 +00:00
|
|
|
let explanation = match future_incompatible.reason {
|
|
|
|
FutureIncompatibilityReason::FutureReleaseError
|
|
|
|
| FutureIncompatibilityReason::FutureReleaseErrorReportNow => {
|
|
|
|
"this was previously accepted by the compiler but is being phased out; \
|
|
|
|
it will become a hard error in a future release!"
|
|
|
|
.to_owned()
|
|
|
|
}
|
|
|
|
FutureIncompatibilityReason::FutureReleaseSemanticsChange => {
|
|
|
|
"this will change its meaning in a future release!".to_owned()
|
|
|
|
}
|
|
|
|
FutureIncompatibilityReason::EditionError(edition) => {
|
|
|
|
let current_edition = sess.edition();
|
|
|
|
format!(
|
|
|
|
"this is accepted in the current edition (Rust {}) but is a hard error in Rust {}!",
|
|
|
|
current_edition, edition
|
|
|
|
)
|
|
|
|
}
|
|
|
|
FutureIncompatibilityReason::EditionSemanticsChange(edition) => {
|
|
|
|
format!("this changes meaning in Rust {}", edition)
|
|
|
|
}
|
|
|
|
FutureIncompatibilityReason::Custom(reason) => reason.to_owned(),
|
2020-01-31 20:57:50 +00:00
|
|
|
};
|
2022-01-27 09:49:32 +00:00
|
|
|
|
2021-06-27 14:45:54 +00:00
|
|
|
if future_incompatible.explain_reason {
|
|
|
|
err.warn(&explanation);
|
|
|
|
}
|
|
|
|
if !future_incompatible.reference.is_empty() {
|
|
|
|
let citation =
|
|
|
|
format!("for more information, see {}", future_incompatible.reference);
|
|
|
|
err.note(&citation);
|
|
|
|
}
|
2020-01-31 20:57:50 +00:00
|
|
|
}
|
2020-01-09 04:57:07 +00:00
|
|
|
|
2020-01-31 20:57:50 +00:00
|
|
|
// Finally, run `decorate`. This function is also responsible for emitting the diagnostic.
|
|
|
|
decorate(LintDiagnosticBuilder::new(err));
|
|
|
|
}
|
|
|
|
struct_lint_level_impl(sess, lint, level, src, span, Box::new(decorate))
|
2020-01-09 04:57:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns whether `span` originates in a foreign crate's external macro.
|
|
|
|
///
|
|
|
|
/// This is used to test whether a lint should not even begin to figure out whether it should
|
|
|
|
/// be reported on the current node.
|
|
|
|
pub fn in_external_macro(sess: &Session, span: Span) -> bool {
|
|
|
|
let expn_data = span.ctxt().outer_expn_data();
|
|
|
|
match expn_data.kind {
|
2021-08-19 21:57:15 +00:00
|
|
|
ExpnKind::Inlined
|
|
|
|
| ExpnKind::Root
|
2021-10-26 04:33:12 +00:00
|
|
|
| ExpnKind::Desugaring(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => false,
|
2020-01-09 04:57:07 +00:00
|
|
|
ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
|
2021-07-10 19:14:52 +00:00
|
|
|
ExpnKind::Macro(MacroKind::Bang, _) => {
|
2019-11-13 12:01:43 +00:00
|
|
|
// Dummy span for the `def_site` means it's an external macro.
|
|
|
|
expn_data.def_site.is_dummy() || sess.source_map().is_imported(expn_data.def_site)
|
2020-01-09 04:57:07 +00:00
|
|
|
}
|
2020-03-17 15:45:02 +00:00
|
|
|
ExpnKind::Macro { .. } => true, // definitely a plugin
|
2020-01-09 04:57:07 +00:00
|
|
|
}
|
|
|
|
}
|