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

Implement unused crate lint for 2018 edition #69203

Closed
Closed
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
9 changes: 0 additions & 9 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3505,7 +3505,6 @@ version = "0.0.0"
dependencies = [
"log",
"rustc_ast",
"rustc_data_structures",
"rustc_span",
]

Expand All @@ -3522,7 +3521,6 @@ dependencies = [
"rustc_session",
"rustc_span",
"serialize",
"smallvec 1.0.0",
]

[[package]]
Expand Down Expand Up @@ -3781,7 +3779,6 @@ dependencies = [
"rustc_ast",
"rustc_attr",
"rustc_data_structures",
"rustc_error_codes",
"rustc_errors",
"rustc_hir",
"rustc_index",
Expand Down Expand Up @@ -3948,7 +3945,6 @@ dependencies = [
"rustc_hir",
"rustc_index",
"rustc_infer",
"rustc_macros",
"rustc_session",
"rustc_span",
"rustc_target",
Expand Down Expand Up @@ -3985,7 +3981,6 @@ dependencies = [
"rustc_attr",
"rustc_data_structures",
"rustc_errors",
"rustc_feature",
"rustc_hir",
"rustc_index",
"rustc_infer",
Expand Down Expand Up @@ -4039,7 +4034,6 @@ dependencies = [
"rustc_expand",
"rustc_feature",
"rustc_hir",
"rustc_infer",
"rustc_metadata",
"rustc_session",
"rustc_span",
Expand Down Expand Up @@ -4075,7 +4069,6 @@ dependencies = [
"rustc_errors",
"rustc_feature",
"rustc_fs_util",
"rustc_index",
"rustc_span",
"rustc_target",
"serialize",
Expand Down Expand Up @@ -4129,9 +4122,7 @@ dependencies = [
"rustc_data_structures",
"rustc_hir",
"rustc_infer",
"rustc_macros",
"rustc_span",
"rustc_target",
"smallvec 1.0.0",
]

Expand Down
1 change: 1 addition & 0 deletions src/bootstrap/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,7 @@ def build_bootstrap(self):
target_linker = self.get_toml("linker", build_section)
if target_linker is not None:
env["RUSTFLAGS"] += " -C linker=" + target_linker
# After the next cfg(bootstrap) bump, add "-Wunused_extern_options" to RUSTFLAGS
env["RUSTFLAGS"] += " -Wrust_2018_idioms -Wunused_lifetimes"
if self.get_toml("deny-warnings", "rust") != "false":
env["RUSTFLAGS"] += " -Dwarnings"
Expand Down
4 changes: 4 additions & 0 deletions src/bootstrap/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1067,6 +1067,10 @@ impl<'a> Builder<'a> {
// some code doesn't go through this `rustc` wrapper.
rustflags.arg("-Wrust_2018_idioms");
rustflags.arg("-Wunused_lifetimes");
// Remove this after the next cfg(bootstrap) bump
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
// Remove this after the next cfg(bootstrap) bump
// Remove this condition after the next cfg(bootstrap) bump

if stage != 0 {
rustflags.arg("-Wunused_extern_options");
}

if self.config.deny_warnings {
rustflags.arg("-Dwarnings");
Expand Down
4 changes: 4 additions & 0 deletions src/liballoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,7 @@ mod std {
pub mod __export {
pub use core::format_args;
}

// Suppress warning: this is only used in benchmarks
#[cfg(test)]
use rand_xorshift as _;
7 changes: 7 additions & 0 deletions src/liballoc/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

// Supress warning: this crate is only used in benchmarks
use rand_xorshift as _;

// Supress warning: these crates are used indirectly
use alloc as _;
use compiler_builtins as _;

mod arc;
mod binary_heap;
mod boxed;
Expand Down
5 changes: 5 additions & 0 deletions src/librustc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,8 @@ pub mod util {

// Allows macros to refer to this crate as `::rustc`
extern crate self as rustc;

// Suppress warning: these crates will be unused when cfg(parallel_compiler) is not enabled
use jobserver as _;
use rustc_rayon as _;
use rustc_rayon_core as _;
5 changes: 4 additions & 1 deletion src/librustc/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ use rustc_ast::ast::{self, Ident, Name};
use rustc_ast::node_id::{NodeId, NodeMap, NodeSet};
use rustc_attr as attr;
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sorted_map::SortedIndexMultiMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator};
Expand Down Expand Up @@ -136,6 +136,9 @@ pub struct ResolverOutputs {
/// Extern prelude entries. The value is `true` if the entry was introduced
/// via `extern crate` item and not `--extern` option or compiler built-in.
pub extern_prelude: FxHashMap<Name, bool>,
/// All crates that ended up getting loaded.
/// Used to determine which `--extern` entries are unused
pub used_crates: Option<FxHashSet<Symbol>>,
Copy link
Contributor

Choose a reason for hiding this comment

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

Putting this list into ResolverOutputs should be unnecessary, the lint can be reported before ResolverOutputs are constructed.
The whole lint logic should be able to live entirely inside rustc_metadata, I suggested the point to report it in #69203 (comment) (CrateLoader::postprocess).

Copy link
Member Author

@Aaron1011 Aaron1011 Mar 13, 2020

Choose a reason for hiding this comment

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

@petrochenkov: Things are not actually done when postprocess is called - while we won't resolve any more crates, we may register additional names for crates that are already loaded. I initially finalized things in postprocess, but that ended up causing false positives.

Copy link
Contributor

Choose a reason for hiding this comment

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

we may register additional names for crates that are already loaded.

How?
(Ignoring rustdoc, which shouldn't report this lint.)

Copy link
Member Author

Choose a reason for hiding this comment

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

If we find a previous crate when loading a crate:

result = LoadResult::Previous(cnum);

then we may map a different name in the extern prelude to an already loaded crate.

Copy link
Contributor

@petrochenkov petrochenkov Mar 14, 2020

Choose a reason for hiding this comment

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

CrateLoader::load can only happen before postprocess.
(Or rather it can happen later during AST lowering when resolving std paths, but if lowering actually loads new crates, it will break more than just this lint.)
Could you give some examples of the false positives?

}

#[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ pub trait PrettyPrinter<'tcx>:
.tcx()
.item_children(visible_parent)
.iter()
.find(|child| child.res.def_id() == def_id)
.find(|child| child.res.opt_def_id() == Some(def_id))
.map(|child| child.ident.name);
if let Some(reexport) = reexport {
*name = reexport;
Expand Down
1 change: 0 additions & 1 deletion src/librustc_ast_pretty/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,4 @@ doctest = false
[dependencies]
log = "0.4"
rustc_span = { path = "../librustc_span" }
rustc_data_structures = { path = "../librustc_data_structures" }
rustc_ast = { path = "../librustc_ast" }
1 change: 0 additions & 1 deletion src/librustc_attr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,5 @@ rustc_span = { path = "../librustc_span" }
rustc_data_structures = { path = "../librustc_data_structures" }
rustc_feature = { path = "../librustc_feature" }
rustc_macros = { path = "../librustc_macros" }
smallvec = { version = "1.0", features = ["union", "may_dangle"] }
rustc_session = { path = "../librustc_session" }
rustc_ast = { path = "../librustc_ast" }
5 changes: 5 additions & 0 deletions src/librustc_data_structures/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
#![feature(thread_id_value)]
#![allow(rustc::default_hash_types)]

// Suppress warning: these crates will be unused when cfg(parallel_compiler) is not enabled
use crossbeam_utils as _;
use rayon as _;
use rayon_core as _;

#[macro_use]
extern crate log;
#[cfg(unix)]
Expand Down
1 change: 0 additions & 1 deletion src/librustc_infer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ rustc_attr = { path = "../librustc_attr" }
rustc = { path = "../librustc" }
rustc_data_structures = { path = "../librustc_data_structures" }
rustc_errors = { path = "../librustc_errors" }
rustc_error_codes = { path = "../librustc_error_codes" }
rustc_hir = { path = "../librustc_hir" }
rustc_index = { path = "../librustc_index" }
rustc_macros = { path = "../librustc_macros" }
Expand Down
3 changes: 3 additions & 0 deletions src/librustc_interface/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,6 @@ pub use queries::Queries;

#[cfg(test)]
mod tests;

// Suppress warning: this crate will be unused when cfg(parallel_compiler) is not enable
use rayon as _;
58 changes: 57 additions & 1 deletion src/librustc_interface/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use rustc_data_structures::{box_region_allow_access, declare_box_region_type, pa
use rustc_errors::PResult;
use rustc_expand::base::ExtCtxt;
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc_hir::Crate;
use rustc_hir::{Crate, CRATE_HIR_ID};
use rustc_infer::traits;
use rustc_lint::LintStore;
use rustc_mir as mir;
Expand All @@ -35,6 +35,7 @@ use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str};
use rustc_passes::{self, hir_stats, layout_test};
use rustc_plugin_impl as plugin;
use rustc_resolve::{Resolver, ResolverArenas};
use rustc_span::symbol::sym;
use rustc_span::symbol::Symbol;
use rustc_span::FileName;
use rustc_typeck as typeck;
Expand All @@ -50,6 +51,9 @@ use std::path::PathBuf;
use std::rc::Rc;
use std::{env, fs, iter, mem};

use log::debug;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};

pub fn parse<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
let krate = sess.time("parse_crate", || match input {
Input::File(file) => parse_crate_from_file(file, &sess.parse_sess),
Expand Down Expand Up @@ -733,6 +737,9 @@ pub fn create_global_ctxt<'tcx>(
callback(sess, &mut local_providers, &mut extern_providers);
}

let extern_prelude = resolver_outputs.extern_prelude.clone();
let used_crates = resolver_outputs.used_crates.as_ref().unwrap().clone();

let gcx = sess.time("setup_global_ctxt", || {
global_ctxt.init_locking(|| {
TyCtxt::create_global_ctxt(
Expand All @@ -753,11 +760,60 @@ pub fn create_global_ctxt<'tcx>(
// Do some initialization of the DepGraph that can only be done with the tcx available.
ty::tls::enter_global(&gcx, |tcx| {
tcx.sess.time("dep_graph_tcx_init", || rustc_incremental::dep_graph_tcx_init(tcx));
check_unused_crates(tcx, &extern_prelude, &used_crates);
});

QueryContext(gcx)
}

fn check_unused_crates(
tcx: TyCtxt<'_>,
extern_prelude: &FxHashMap<Symbol, bool>,
used_crates: &FxHashSet<Symbol>,
) {
for (krate, introduced_by_item) in extern_prelude {
let krate = *krate;
if *introduced_by_item {
debug!("check_unused_crate: crate {:?} added by `extern crate`, skipping", krate);
continue;
}
if used_crates.contains(&krate) {
debug!("check_unused_crate: crate {:?} was used, skipping", krate);
continue;
}

// HACK: These should not be hardcoded. However, libstd needs
// both of them mentioned in its Cargo.tonl, and trying to
// add 'use' or 'extern crate' statements for both crates
// causes an error.
//
// If either of these crates is unused, we will never have loaded
// their metadata (otherwise, they would be used). This means that we have
// no way of checking the `panic_runtime` field in the metadata, and must
// instead rely on the crate name itself.
if krate.as_str() == "panic_abort" || krate.as_str() == "panic_unwind" {
debug!("check_unused_crate: skipping panic runtime crate {:?}", krate);
continue;
}

if krate == sym::core || krate == sym::std {
debug!("check_unused_crate: skipping builtin crate {:?}", krate);
continue;
}

if tcx.sess.rust_2018() && krate == sym::meta {
debug!("check_unused_crate: skipping `meta` crate");
continue;
}

tcx.struct_lint_node(lint::builtin::UNUSED_EXTERN_OPTIONS, CRATE_HIR_ID, |lint| {
lint.build(&format!("crate `{}` is unused in crate `{}`", krate, tcx.crate_name))
.help(&format!("try removing `{}` from your `Cargo.toml`", krate))
.emit();
});
}
}

/// Runs the resolution, type-checking, region checking and other
/// miscellaneous analysis passes on the crate.
fn analysis(tcx: TyCtxt<'_>, cnum: CrateNum) -> Result<()> {
Expand Down
Loading