Skip to content

Commit 8823684

Browse files
committed
Auto merge of #6244 - mikerite:invalid_paths_20201027, r=flip1995
New internal lint: Invalid paths Add a new internal lint that detects invalid paths in the `util::paths` and fix some invalid paths found. This commit partially addresses #6047 but the lint would have to be run before running tests to close that issue. changelog: none
2 parents afbac89 + f79c4af commit 8823684

File tree

8 files changed

+163
-15
lines changed

8 files changed

+163
-15
lines changed

clippy_lints/src/derive.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::utils::paths;
22
use crate::utils::{
3-
get_trait_def_id, is_allowed, is_automatically_derived, is_copy, match_path, span_lint_and_help,
3+
get_trait_def_id, is_allowed, is_automatically_derived, is_copy, match_def_path, match_path, span_lint_and_help,
44
span_lint_and_note, span_lint_and_then,
55
};
66
use if_chain::if_chain;
@@ -193,10 +193,9 @@ fn check_hash_peq<'tcx>(
193193
hash_is_automatically_derived: bool,
194194
) {
195195
if_chain! {
196-
if match_path(&trait_ref.path, &paths::HASH);
197196
if let Some(peq_trait_def_id) = cx.tcx.lang_items().eq_trait();
198-
if let Some(def_id) = &trait_ref.trait_def_id();
199-
if !def_id.is_local();
197+
if let Some(def_id) = trait_ref.trait_def_id();
198+
if match_def_path(cx, def_id, &paths::HASH);
200199
then {
201200
// Look for the PartialEq implementations for `ty`
202201
cx.tcx.for_each_relevant_impl(peq_trait_def_id, ty, |impl_id| {
@@ -352,7 +351,8 @@ fn check_unsafe_derive_deserialize<'tcx>(
352351
}
353352

354353
if_chain! {
355-
if match_path(&trait_ref.path, &paths::SERDE_DESERIALIZE);
354+
if let Some(trait_def_id) = trait_ref.trait_def_id();
355+
if match_def_path(cx, trait_def_id, &paths::SERDE_DESERIALIZE);
356356
if let ty::Adt(def, _) = ty.kind();
357357
if let Some(local_def_id) = def.did.as_local();
358358
let adt_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_def_id);

clippy_lints/src/float_equality_without_abs.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
use crate::utils::{match_qpath, paths, span_lint_and_then, sugg};
1+
use crate::utils::{match_def_path, paths, span_lint_and_then, sugg};
22
use if_chain::if_chain;
33
use rustc_ast::util::parser::AssocOp;
44
use rustc_errors::Applicability;
5+
use rustc_hir::def::{DefKind, Res};
56
use rustc_hir::{BinOpKind, Expr, ExprKind};
67
use rustc_lint::{LateContext, LateLintPass};
78
use rustc_middle::ty;
@@ -76,7 +77,8 @@ impl<'tcx> LateLintPass<'tcx> for FloatEqualityWithoutAbs {
7677

7778
// right hand side matches either f32::EPSILON or f64::EPSILON
7879
if let ExprKind::Path(ref epsilon_path) = rhs.kind;
79-
if match_qpath(epsilon_path, &paths::F32_EPSILON) || match_qpath(epsilon_path, &paths::F64_EPSILON);
80+
if let Res::Def(DefKind::AssocConst, def_id) = cx.qpath_res(epsilon_path, rhs.hir_id);
81+
if match_def_path(cx, def_id, &paths::F32_EPSILON) || match_def_path(cx, def_id, &paths::F64_EPSILON);
8082

8183
// values of the substractions on the left hand side are of the type float
8284
let t_val_l = cx.typeck_results().expr_ty(val_l);

clippy_lints/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
892892
&utils::internal_lints::COLLAPSIBLE_SPAN_LINT_CALLS,
893893
&utils::internal_lints::COMPILER_LINT_FUNCTIONS,
894894
&utils::internal_lints::DEFAULT_LINT,
895+
&utils::internal_lints::INVALID_PATHS,
895896
&utils::internal_lints::LINT_WITHOUT_LINT_PASS,
896897
&utils::internal_lints::MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
897898
&utils::internal_lints::OUTER_EXPN_EXPN_DATA,
@@ -919,6 +920,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
919920
store.register_late_pass(|| box utils::internal_lints::CompilerLintFunctions::new());
920921
store.register_late_pass(|| box utils::internal_lints::LintWithoutLintPass::default());
921922
store.register_late_pass(|| box utils::internal_lints::OuterExpnDataPass);
923+
store.register_late_pass(|| box utils::internal_lints::InvalidPaths);
922924
store.register_late_pass(|| box utils::inspector::DeepCodeInspector);
923925
store.register_late_pass(|| box utils::author::Author);
924926
let vec_box_size_threshold = conf.vec_box_size_threshold;
@@ -1280,6 +1282,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12801282
LintId::of(&utils::internal_lints::COLLAPSIBLE_SPAN_LINT_CALLS),
12811283
LintId::of(&utils::internal_lints::COMPILER_LINT_FUNCTIONS),
12821284
LintId::of(&utils::internal_lints::DEFAULT_LINT),
1285+
LintId::of(&utils::internal_lints::INVALID_PATHS),
12831286
LintId::of(&utils::internal_lints::LINT_WITHOUT_LINT_PASS),
12841287
LintId::of(&utils::internal_lints::MATCH_TYPE_ON_DIAGNOSTIC_ITEM),
12851288
LintId::of(&utils::internal_lints::OUTER_EXPN_EXPN_DATA),

clippy_lints/src/utils/internal_lints.rs

+79
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::consts::{constant_simple, Constant};
12
use crate::utils::{
23
is_expn_of, match_def_path, match_qpath, match_type, method_calls, path_to_res, paths, qpath_res, run_lints,
34
snippet, span_lint, span_lint_and_help, span_lint_and_sugg, SpanlessEq,
@@ -14,9 +15,11 @@ use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
1415
use rustc_hir::{Crate, Expr, ExprKind, HirId, Item, MutTy, Mutability, Node, Path, StmtKind, Ty, TyKind};
1516
use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
1617
use rustc_middle::hir::map::Map;
18+
use rustc_middle::ty;
1719
use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
1820
use rustc_span::source_map::{Span, Spanned};
1921
use rustc_span::symbol::{Symbol, SymbolStr};
22+
use rustc_typeck::hir_ty_to_ty;
2023

2124
use std::borrow::{Borrow, Cow};
2225

@@ -229,6 +232,21 @@ declare_clippy_lint! {
229232
"using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
230233
}
231234

235+
declare_clippy_lint! {
236+
/// **What it does:**
237+
/// Checks the paths module for invalid paths.
238+
///
239+
/// **Why is this bad?**
240+
/// It indicates a bug in the code.
241+
///
242+
/// **Known problems:** None.
243+
///
244+
/// **Example:** None.
245+
pub INVALID_PATHS,
246+
internal,
247+
"invalid path"
248+
}
249+
232250
declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
233251

234252
impl EarlyLintPass for ClippyLintsInternal {
@@ -761,3 +779,64 @@ fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Ve
761779

762780
None
763781
}
782+
783+
// This is not a complete resolver for paths. It works on all the paths currently used in the paths
784+
// module. That's all it does and all it needs to do.
785+
pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
786+
if path_to_res(cx, path).is_some() {
787+
return true;
788+
}
789+
790+
// Some implementations can't be found by `path_to_res`, particularly inherent
791+
// implementations of native types. Check lang items.
792+
let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
793+
let lang_items = cx.tcx.lang_items();
794+
for lang_item in lang_items.items() {
795+
if let Some(def_id) = lang_item {
796+
let lang_item_path = cx.get_def_path(*def_id);
797+
if path_syms.starts_with(&lang_item_path) {
798+
if let [item] = &path_syms[lang_item_path.len()..] {
799+
for child in cx.tcx.item_children(*def_id) {
800+
if child.ident.name == *item {
801+
return true;
802+
}
803+
}
804+
}
805+
}
806+
}
807+
}
808+
809+
false
810+
}
811+
812+
declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
813+
814+
impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
815+
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
816+
let local_def_id = &cx.tcx.parent_module(item.hir_id);
817+
let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
818+
if_chain! {
819+
if mod_name.as_str() == "paths";
820+
if let hir::ItemKind::Const(ty, body_id) = item.kind;
821+
let ty = hir_ty_to_ty(cx.tcx, ty);
822+
if let ty::Array(el_ty, _) = &ty.kind();
823+
if let ty::Ref(_, el_ty, _) = &el_ty.kind();
824+
if el_ty.is_str();
825+
let body = cx.tcx.hir().body(body_id);
826+
let typeck_results = cx.tcx.typeck_body(body_id);
827+
if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
828+
let path: Vec<&str> = path.iter().map(|x| {
829+
if let Constant::Str(s) = x {
830+
s.as_str()
831+
} else {
832+
// We checked the type of the constant above
833+
unreachable!()
834+
}
835+
}).collect();
836+
if !check_path(cx, &path[..]);
837+
then {
838+
span_lint(cx, CLIPPY_LINTS_INTERNAL, item.span, "invalid path");
839+
}
840+
}
841+
}
842+
}

clippy_lints/src/utils/mod.rs

+25
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@ pub fn path_to_res(cx: &LateContext<'_>, path: &[&str]) -> Option<def::Res> {
268268
krate: *krate,
269269
index: CRATE_DEF_INDEX,
270270
};
271+
let mut current_item = None;
271272
let mut items = cx.tcx.item_children(krate);
272273
let mut path_it = path.iter().skip(1).peekable();
273274

@@ -277,17 +278,41 @@ pub fn path_to_res(cx: &LateContext<'_>, path: &[&str]) -> Option<def::Res> {
277278
None => return None,
278279
};
279280

281+
// `get_def_path` seems to generate these empty segments for extern blocks.
282+
// We can just ignore them.
283+
if segment.is_empty() {
284+
continue;
285+
}
286+
280287
let result = SmallVec::<[_; 8]>::new();
281288
for item in mem::replace(&mut items, cx.tcx.arena.alloc_slice(&result)).iter() {
282289
if item.ident.name.as_str() == *segment {
283290
if path_it.peek().is_none() {
284291
return Some(item.res);
285292
}
286293

294+
current_item = Some(item);
287295
items = cx.tcx.item_children(item.res.def_id());
288296
break;
289297
}
290298
}
299+
300+
// The segment isn't a child_item.
301+
// Try to find it under an inherent impl.
302+
if_chain! {
303+
if path_it.peek().is_none();
304+
if let Some(current_item) = current_item;
305+
let item_def_id = current_item.res.def_id();
306+
if cx.tcx.def_kind(item_def_id) == DefKind::Struct;
307+
then {
308+
// Bad `find_map` suggestion. See #4193.
309+
#[allow(clippy::find_map)]
310+
return cx.tcx.inherent_impls(item_def_id).iter()
311+
.flat_map(|&impl_def_id| cx.tcx.item_children(impl_def_id))
312+
.find(|item| item.ident.name.as_str() == *segment)
313+
.map(|item| item.res);
314+
}
315+
}
291316
}
292317
} else {
293318
None

clippy_lints/src/utils/paths.rs

+8-8
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@ pub const DISPLAY_TRAIT: [&str; 3] = ["core", "fmt", "Display"];
3232
pub const DOUBLE_ENDED_ITERATOR: [&str; 4] = ["core", "iter", "traits", "DoubleEndedIterator"];
3333
pub const DROP: [&str; 3] = ["core", "mem", "drop"];
3434
pub const DURATION: [&str; 3] = ["core", "time", "Duration"];
35-
pub const EARLY_CONTEXT: [&str; 4] = ["rustc", "lint", "context", "EarlyContext"];
35+
pub const EARLY_CONTEXT: [&str; 2] = ["rustc_lint", "EarlyContext"];
3636
pub const EXIT: [&str; 3] = ["std", "process", "exit"];
37-
pub const F32_EPSILON: [&str; 2] = ["f32", "EPSILON"];
38-
pub const F64_EPSILON: [&str; 2] = ["f64", "EPSILON"];
37+
pub const F32_EPSILON: [&str; 4] = ["core", "f32", "<impl f32>", "EPSILON"];
38+
pub const F64_EPSILON: [&str; 4] = ["core", "f64", "<impl f64>", "EPSILON"];
3939
pub const FILE: [&str; 3] = ["std", "fs", "File"];
4040
pub const FILE_TYPE: [&str; 3] = ["std", "fs", "FileType"];
4141
pub const FMT_ARGUMENTS_NEW_V1: [&str; 4] = ["core", "fmt", "Arguments", "new_v1"];
@@ -47,7 +47,7 @@ pub const FN_ONCE: [&str; 3] = ["core", "ops", "FnOnce"];
4747
pub const FROM_FROM: [&str; 4] = ["core", "convert", "From", "from"];
4848
pub const FROM_TRAIT: [&str; 3] = ["core", "convert", "From"];
4949
pub const FUTURE_FROM_GENERATOR: [&str; 3] = ["core", "future", "from_generator"];
50-
pub const HASH: [&str; 2] = ["hash", "Hash"];
50+
pub const HASH: [&str; 3] = ["core", "hash", "Hash"];
5151
pub const HASHMAP: [&str; 5] = ["std", "collections", "hash", "map", "HashMap"];
5252
pub const HASHMAP_ENTRY: [&str; 5] = ["std", "collections", "hash", "map", "Entry"];
5353
pub const HASHSET: [&str; 5] = ["std", "collections", "hash", "set", "HashSet"];
@@ -58,7 +58,7 @@ pub const INTO_ITERATOR: [&str; 5] = ["core", "iter", "traits", "collect", "Into
5858
pub const IO_READ: [&str; 3] = ["std", "io", "Read"];
5959
pub const IO_WRITE: [&str; 3] = ["std", "io", "Write"];
6060
pub const ITERATOR: [&str; 5] = ["core", "iter", "traits", "iterator", "Iterator"];
61-
pub const LATE_CONTEXT: [&str; 4] = ["rustc", "lint", "context", "LateContext"];
61+
pub const LATE_CONTEXT: [&str; 2] = ["rustc_lint", "LateContext"];
6262
pub const LINKED_LIST: [&str; 4] = ["alloc", "collections", "linked_list", "LinkedList"];
6363
pub const LINT: [&str; 3] = ["rustc_session", "lint", "Lint"];
6464
pub const MEM_DISCRIMINANT: [&str; 3] = ["core", "mem", "discriminant"];
@@ -86,8 +86,8 @@ pub const PATH_BUF_AS_PATH: [&str; 4] = ["std", "path", "PathBuf", "as_path"];
8686
pub const PATH_TO_PATH_BUF: [&str; 4] = ["std", "path", "Path", "to_path_buf"];
8787
pub const POLL: [&str; 4] = ["core", "task", "poll", "Poll"];
8888
pub const PTR_EQ: [&str; 3] = ["core", "ptr", "eq"];
89-
pub const PTR_NULL: [&str; 2] = ["ptr", "null"];
90-
pub const PTR_NULL_MUT: [&str; 2] = ["ptr", "null_mut"];
89+
pub const PTR_NULL: [&str; 3] = ["core", "ptr", "null"];
90+
pub const PTR_NULL_MUT: [&str; 3] = ["core", "ptr", "null_mut"];
9191
pub const PUSH_STR: [&str; 4] = ["alloc", "string", "String", "push_str"];
9292
pub const RANGE_ARGUMENT_TRAIT: [&str; 3] = ["core", "ops", "RangeBounds"];
9393
pub const RC: [&str; 3] = ["alloc", "rc", "Rc"];
@@ -107,7 +107,7 @@ pub const RESULT_ERR: [&str; 4] = ["core", "result", "Result", "Err"];
107107
pub const RESULT_OK: [&str; 4] = ["core", "result", "Result", "Ok"];
108108
pub const RWLOCK_READ_GUARD: [&str; 4] = ["std", "sync", "rwlock", "RwLockReadGuard"];
109109
pub const RWLOCK_WRITE_GUARD: [&str; 4] = ["std", "sync", "rwlock", "RwLockWriteGuard"];
110-
pub const SERDE_DESERIALIZE: [&str; 2] = ["_serde", "Deserialize"];
110+
pub const SERDE_DESERIALIZE: [&str; 3] = ["serde", "de", "Deserialize"];
111111
pub const SERDE_DE_VISITOR: [&str; 3] = ["serde", "de", "Visitor"];
112112
pub const SLICE_INTO_VEC: [&str; 4] = ["alloc", "slice", "<impl [T]>", "into_vec"];
113113
pub const SLICE_ITER: [&str; 4] = ["core", "slice", "iter", "Iter"];

tests/ui/invalid_paths.rs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#![warn(clippy::internal)]
2+
3+
mod paths {
4+
// Good path
5+
pub const ANY_TRAIT: [&str; 3] = ["std", "any", "Any"];
6+
7+
// Path to method on inherent impl of a primitive type
8+
pub const F32_EPSILON: [&str; 4] = ["core", "f32", "<impl f32>", "EPSILON"];
9+
10+
// Path to method on inherent impl
11+
pub const ARC_PTR_EQ: [&str; 4] = ["alloc", "sync", "Arc", "ptr_eq"];
12+
13+
// Path with empty segment
14+
pub const TRANSMUTE: [&str; 4] = ["core", "intrinsics", "", "transmute"];
15+
16+
// Path with bad crate
17+
pub const BAD_CRATE_PATH: [&str; 2] = ["bad", "path"];
18+
19+
// Path with bad module
20+
pub const BAD_MOD_PATH: [&str; 2] = ["std", "xxx"];
21+
}
22+
23+
fn main() {}

tests/ui/invalid_paths.stderr

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error: invalid path
2+
--> $DIR/invalid_paths.rs:17:5
3+
|
4+
LL | pub const BAD_CRATE_PATH: [&str; 2] = ["bad", "path"];
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: `-D clippy::clippy-lints-internal` implied by `-D warnings`
8+
9+
error: invalid path
10+
--> $DIR/invalid_paths.rs:20:5
11+
|
12+
LL | pub const BAD_MOD_PATH: [&str; 2] = ["std", "xxx"];
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
14+
15+
error: aborting due to 2 previous errors
16+

0 commit comments

Comments
 (0)