Replace str path utils with new PathLookup type
This commit is contained in:
parent
ea13461967
commit
b768fbe4bc
70 changed files with 799 additions and 1400 deletions
|
|
@ -1,6 +1,6 @@
|
|||
use clippy_utils::diagnostics::span_lint_and_sugg;
|
||||
use clippy_utils::source::snippet;
|
||||
use clippy_utils::{SpanlessEq, is_expr_path_def_path, is_lint_allowed, peel_blocks_with_stmt};
|
||||
use clippy_utils::{SpanlessEq, is_lint_allowed, peel_blocks_with_stmt};
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir::{Closure, Expr, ExprKind};
|
||||
use rustc_lint::{LateContext, LateLintPass};
|
||||
|
|
@ -10,6 +10,8 @@ use rustc_span::Span;
|
|||
|
||||
use std::borrow::{Borrow, Cow};
|
||||
|
||||
use crate::internal_paths;
|
||||
|
||||
declare_tool_lint! {
|
||||
/// ### What it does
|
||||
/// Lints `span_lint_and_then` function calls, where the
|
||||
|
|
@ -80,7 +82,7 @@ impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
|
|||
}
|
||||
|
||||
if let ExprKind::Call(func, [call_cx, call_lint, call_sp, call_msg, call_f]) = expr.kind
|
||||
&& is_expr_path_def_path(cx, func, &["clippy_utils", "diagnostics", "span_lint_and_then"])
|
||||
&& internal_paths::SPAN_LINT_AND_THEN.matches_path(cx, func)
|
||||
&& let ExprKind::Closure(&Closure { body, .. }) = call_f.kind
|
||||
&& let body = cx.tcx.hir_body(body)
|
||||
&& let only_expr = peel_blocks_with_stmt(body.value)
|
||||
|
|
|
|||
17
clippy_lints_internal/src/internal_paths.rs
Normal file
17
clippy_lints_internal/src/internal_paths.rs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
use clippy_utils::paths::PathLookup;
|
||||
use clippy_utils::{PathNS, sym, type_path, value_path};
|
||||
|
||||
// Paths inside rustc
|
||||
pub static EARLY_LINT_PASS: PathLookup = type_path!(rustc_lint::passes::EarlyLintPass);
|
||||
pub static KW_MODULE: PathLookup = type_path!(rustc_span::symbol::kw);
|
||||
pub static LINT: PathLookup = type_path!(rustc_lint_defs::Lint);
|
||||
pub static SYMBOL: PathLookup = type_path!(rustc_span::symbol::Symbol);
|
||||
pub static SYMBOL_AS_STR: PathLookup = value_path!(rustc_span::symbol::Symbol::as_str);
|
||||
pub static SYM_MODULE: PathLookup = type_path!(rustc_span::symbol::sym);
|
||||
pub static SYNTAX_CONTEXT: PathLookup = type_path!(rustc_span::hygiene::SyntaxContext);
|
||||
|
||||
// Paths in clippy itself
|
||||
pub static CLIPPY_SYM_MODULE: PathLookup = type_path!(clippy_utils::sym);
|
||||
pub static MSRV_STACK: PathLookup = type_path!(clippy_utils::msrvs::MsrvStack);
|
||||
pub static PATH_LOOKUP_NEW: PathLookup = value_path!(clippy_utils::paths::PathLookup::new);
|
||||
pub static SPAN_LINT_AND_THEN: PathLookup = value_path!(clippy_utils::diagnostics::span_lint_and_then);
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
use clippy_utils::consts::{ConstEvalCtxt, Constant};
|
||||
use clippy_utils::def_path_res;
|
||||
use clippy_utils::diagnostics::span_lint;
|
||||
use rustc_hir as hir;
|
||||
use rustc_hir::Item;
|
||||
use rustc_hir::def::DefKind;
|
||||
use rustc_lint::{LateContext, LateLintPass};
|
||||
use rustc_lint_defs::declare_tool_lint;
|
||||
use rustc_middle::ty::fast_reject::SimplifiedType;
|
||||
use rustc_middle::ty::{self, FloatTy};
|
||||
use rustc_session::declare_lint_pass;
|
||||
use rustc_span::symbol::Symbol;
|
||||
|
||||
declare_tool_lint! {
|
||||
/// ### What it does
|
||||
/// Checks the paths module for invalid paths.
|
||||
///
|
||||
/// ### Why is this bad?
|
||||
/// It indicates a bug in the code.
|
||||
///
|
||||
/// ### Example
|
||||
/// None.
|
||||
pub clippy::INVALID_PATHS,
|
||||
Warn,
|
||||
"invalid path",
|
||||
report_in_external_macro: true
|
||||
}
|
||||
|
||||
declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
|
||||
|
||||
impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
|
||||
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
|
||||
let local_def_id = &cx.tcx.parent_module(item.hir_id());
|
||||
let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
|
||||
if mod_name.as_str() == "paths"
|
||||
&& let hir::ItemKind::Const(.., body_id) = item.kind
|
||||
&& let Some(Constant::Vec(path)) = ConstEvalCtxt::with_env(
|
||||
cx.tcx,
|
||||
ty::TypingEnv::post_analysis(cx.tcx, item.owner_id),
|
||||
cx.tcx.typeck(item.owner_id),
|
||||
)
|
||||
.eval_simple(cx.tcx.hir_body(body_id).value)
|
||||
&& let Some(path) = path
|
||||
.iter()
|
||||
.map(|x| {
|
||||
if let Constant::Str(s) = x {
|
||||
Some(s.as_str())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Option<Vec<&str>>>()
|
||||
&& !check_path(cx, &path[..])
|
||||
{
|
||||
span_lint(cx, INVALID_PATHS, item.span, "invalid path");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This is not a complete resolver for paths. It works on all the paths currently used in the paths
|
||||
// module. That's all it does and all it needs to do.
|
||||
pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
|
||||
if !def_path_res(cx.tcx, path).is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Some implementations can't be found by `path_to_res`, particularly inherent
|
||||
// implementations of native types. Check lang items.
|
||||
let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
|
||||
let lang_items = cx.tcx.lang_items();
|
||||
// This list isn't complete, but good enough for our current list of paths.
|
||||
let incoherent_impls = [
|
||||
SimplifiedType::Float(FloatTy::F32),
|
||||
SimplifiedType::Float(FloatTy::F64),
|
||||
SimplifiedType::Slice,
|
||||
SimplifiedType::Str,
|
||||
SimplifiedType::Bool,
|
||||
SimplifiedType::Char,
|
||||
]
|
||||
.iter()
|
||||
.flat_map(|&ty| cx.tcx.incoherent_impls(ty).iter())
|
||||
.copied();
|
||||
for item_def_id in lang_items.iter().map(|(_, def_id)| def_id).chain(incoherent_impls) {
|
||||
let lang_item_path = cx.get_def_path(item_def_id);
|
||||
if path_syms.starts_with(&lang_item_path)
|
||||
&& let [item] = &path_syms[lang_item_path.len()..]
|
||||
{
|
||||
if matches!(
|
||||
cx.tcx.def_kind(item_def_id),
|
||||
DefKind::Mod | DefKind::Enum | DefKind::Trait
|
||||
) {
|
||||
for child in cx.tcx.module_children(item_def_id) {
|
||||
if child.ident.name == *item {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for child in cx.tcx.associated_item_def_ids(item_def_id) {
|
||||
if cx.tcx.item_name(*child) == *item {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
|
@ -32,7 +32,7 @@ extern crate rustc_span;
|
|||
|
||||
mod almost_standard_lint_formulation;
|
||||
mod collapsible_calls;
|
||||
mod invalid_paths;
|
||||
mod internal_paths;
|
||||
mod lint_without_lint_pass;
|
||||
mod msrv_attr_impl;
|
||||
mod outer_expn_data_pass;
|
||||
|
|
@ -46,7 +46,6 @@ use rustc_lint::{Lint, LintStore};
|
|||
static LINTS: &[&Lint] = &[
|
||||
almost_standard_lint_formulation::ALMOST_STANDARD_LINT_FORMULATION,
|
||||
collapsible_calls::COLLAPSIBLE_SPAN_LINT_CALLS,
|
||||
invalid_paths::INVALID_PATHS,
|
||||
lint_without_lint_pass::DEFAULT_LINT,
|
||||
lint_without_lint_pass::INVALID_CLIPPY_VERSION_ATTRIBUTE,
|
||||
lint_without_lint_pass::LINT_WITHOUT_LINT_PASS,
|
||||
|
|
@ -66,10 +65,9 @@ pub fn register_lints(store: &mut LintStore) {
|
|||
store.register_early_pass(|| Box::new(unsorted_clippy_utils_paths::UnsortedClippyUtilsPaths));
|
||||
store.register_early_pass(|| Box::new(produce_ice::ProduceIce));
|
||||
store.register_late_pass(|_| Box::new(collapsible_calls::CollapsibleCalls));
|
||||
store.register_late_pass(|_| Box::new(invalid_paths::InvalidPaths));
|
||||
store.register_late_pass(|_| Box::<symbols::Symbols>::default());
|
||||
store.register_late_pass(|_| Box::<lint_without_lint_pass::LintWithoutLintPass>::default());
|
||||
store.register_late_pass(|_| Box::<unnecessary_def_path::UnnecessaryDefPath>::default());
|
||||
store.register_late_pass(|_| Box::new(unnecessary_def_path::UnnecessaryDefPath));
|
||||
store.register_late_pass(|_| Box::new(outer_expn_data_pass::OuterExpnDataPass));
|
||||
store.register_late_pass(|_| Box::new(msrv_attr_impl::MsrvAttrImpl));
|
||||
store.register_late_pass(|_| Box::new(almost_standard_lint_formulation::AlmostStandardFormulation::new()));
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
use crate::internal_paths;
|
||||
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
|
||||
use clippy_utils::is_lint_allowed;
|
||||
use clippy_utils::macros::root_macro_call_first_node;
|
||||
use clippy_utils::{is_lint_allowed, match_def_path, paths};
|
||||
use rustc_ast::ast::LitKind;
|
||||
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
|
||||
use rustc_hir as hir;
|
||||
|
|
@ -209,10 +210,10 @@ pub(super) fn is_lint_ref_type(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
|
|||
&& let TyKind::Path(ref path) = inner.kind
|
||||
&& let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id)
|
||||
{
|
||||
return match_def_path(cx, def_id, &paths::LINT);
|
||||
internal_paths::LINT.matches(cx, def_id)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn check_invalid_clippy_version_attribute(cx: &LateContext<'_>, item: &'_ Item<'_>) {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
use crate::internal_paths;
|
||||
use clippy_utils::diagnostics::span_lint_and_sugg;
|
||||
use clippy_utils::source::snippet;
|
||||
use clippy_utils::ty::match_type;
|
||||
use clippy_utils::{match_def_path, paths};
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir as hir;
|
||||
use rustc_lint::{LateContext, LateLintPass, LintContext};
|
||||
|
|
@ -31,7 +30,7 @@ impl LateLintPass<'_> for MsrvAttrImpl {
|
|||
.tcx
|
||||
.impl_trait_ref(item.owner_id)
|
||||
.map(EarlyBinder::instantiate_identity)
|
||||
&& match_def_path(cx, trait_ref.def_id, &paths::EARLY_LINT_PASS)
|
||||
&& internal_paths::EARLY_LINT_PASS.matches(cx, trait_ref.def_id)
|
||||
&& let ty::Adt(self_ty_def, _) = trait_ref.self_ty().kind()
|
||||
&& self_ty_def.is_struct()
|
||||
&& self_ty_def.all_fields().any(|f| {
|
||||
|
|
@ -40,7 +39,7 @@ impl LateLintPass<'_> for MsrvAttrImpl {
|
|||
.instantiate_identity()
|
||||
.walk()
|
||||
.filter(|t| matches!(t.unpack(), GenericArgKind::Type(_)))
|
||||
.any(|t| match_type(cx, t.expect_ty(), &paths::MSRV_STACK))
|
||||
.any(|t| internal_paths::MSRV_STACK.matches_ty(cx, t.expect_ty()))
|
||||
})
|
||||
&& !items.iter().any(|item| item.ident.name.as_str() == "check_attributes")
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use crate::internal_paths;
|
||||
use clippy_utils::diagnostics::span_lint_and_sugg;
|
||||
use clippy_utils::ty::match_type;
|
||||
use clippy_utils::{is_lint_allowed, method_calls, paths};
|
||||
use clippy_utils::{is_lint_allowed, method_calls};
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir as hir;
|
||||
use rustc_lint::{LateContext, LateLintPass};
|
||||
|
|
@ -45,7 +45,7 @@ impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
|
|||
&& let (self_arg, args) = arg_lists[1]
|
||||
&& args.is_empty()
|
||||
&& let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs()
|
||||
&& match_type(cx, self_ty, &paths::SYNTAX_CONTEXT)
|
||||
&& internal_paths::SYNTAX_CONTEXT.matches_ty(cx, self_ty)
|
||||
{
|
||||
span_lint_and_sugg(
|
||||
cx,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
use crate::internal_paths;
|
||||
use clippy_utils::diagnostics::span_lint_and_then;
|
||||
use clippy_utils::ty::match_type;
|
||||
use clippy_utils::{def_path_def_ids, match_def_path, paths};
|
||||
use rustc_ast::LitKind;
|
||||
use rustc_data_structures::fx::FxHashMap;
|
||||
use rustc_errors::Applicability;
|
||||
|
|
@ -69,12 +68,12 @@ impl_lint_pass!(Symbols => [INTERNING_LITERALS, SYMBOL_AS_STR]);
|
|||
impl<'tcx> LateLintPass<'tcx> for Symbols {
|
||||
fn check_crate(&mut self, cx: &LateContext<'_>) {
|
||||
let modules = [
|
||||
("kw", &paths::KW_MODULE[..]),
|
||||
("sym", &paths::SYM_MODULE),
|
||||
("sym", &paths::CLIPPY_SYM_MODULE),
|
||||
("kw", &internal_paths::KW_MODULE),
|
||||
("sym", &internal_paths::SYM_MODULE),
|
||||
("sym", &internal_paths::CLIPPY_SYM_MODULE),
|
||||
];
|
||||
for (prefix, module) in modules {
|
||||
for def_id in def_path_def_ids(cx.tcx, module) {
|
||||
for def_id in module.get(cx) {
|
||||
// When linting `clippy_utils` itself we can't use `module_children` as it's a local def id. It will
|
||||
// still lint but the suggestion will say to add it to `sym.rs` even if it's already there
|
||||
if def_id.is_local() {
|
||||
|
|
@ -84,7 +83,7 @@ impl<'tcx> LateLintPass<'tcx> for Symbols {
|
|||
for item in cx.tcx.module_children(def_id) {
|
||||
if let Res::Def(DefKind::Const, item_def_id) = item.res
|
||||
&& let ty = cx.tcx.type_of(item_def_id).instantiate_identity()
|
||||
&& match_type(cx, ty, &paths::SYMBOL)
|
||||
&& internal_paths::SYMBOL.matches_ty(cx, ty)
|
||||
&& let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id)
|
||||
&& let Some(value) = value.to_u32().discard_err()
|
||||
{
|
||||
|
|
@ -160,7 +159,7 @@ fn suggestion(symbols: &mut FxHashMap<u32, (&'static str, Symbol)>, name: Symbol
|
|||
fn as_str_span(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Span> {
|
||||
if let ExprKind::MethodCall(_, recv, [], _) = expr.kind
|
||||
&& let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
|
||||
&& match_def_path(cx, method_def_id, &paths::SYMBOL_AS_STR)
|
||||
&& internal_paths::SYMBOL_AS_STR.matches(cx, method_def_id)
|
||||
{
|
||||
Some(recv.span.shrink_to_hi().to(expr.span.shrink_to_hi()))
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,23 +1,13 @@
|
|||
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_then};
|
||||
use clippy_utils::source::snippet_with_applicability;
|
||||
use clippy_utils::{def_path_def_ids, is_lint_allowed, match_any_def_paths, peel_hir_expr_refs};
|
||||
use rustc_ast::ast::LitKind;
|
||||
use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
|
||||
use rustc_errors::Applicability;
|
||||
use rustc_hir::def::{DefKind, Res};
|
||||
use crate::internal_paths;
|
||||
use clippy_utils::diagnostics::span_lint_and_then;
|
||||
use clippy_utils::{PathNS, lookup_path, path_def_id, peel_ref_operators};
|
||||
use rustc_hir::def_id::DefId;
|
||||
use rustc_hir::{Expr, ExprKind, LetStmt, Mutability, Node};
|
||||
use rustc_hir::{Expr, ExprKind};
|
||||
use rustc_lint::{LateContext, LateLintPass};
|
||||
use rustc_lint_defs::declare_tool_lint;
|
||||
use rustc_lint_defs::{declare_lint_pass, declare_tool_lint};
|
||||
use rustc_middle::mir::ConstValue;
|
||||
use rustc_middle::mir::interpret::{Allocation, GlobalAlloc};
|
||||
use rustc_middle::ty::{self, Ty};
|
||||
use rustc_session::impl_lint_pass;
|
||||
use rustc_span::Span;
|
||||
use rustc_span::symbol::Symbol;
|
||||
|
||||
use std::str;
|
||||
|
||||
declare_tool_lint! {
|
||||
/// ### What it does
|
||||
/// Checks for usage of def paths when a diagnostic item or a `LangItem` could be used.
|
||||
|
|
@ -28,12 +18,14 @@ declare_tool_lint! {
|
|||
///
|
||||
/// ### Example
|
||||
/// ```rust,ignore
|
||||
/// utils::match_type(cx, ty, &paths::VEC)
|
||||
/// pub static VEC: PathLookup = path!(alloc::vec::Vec);
|
||||
///
|
||||
/// VEC.contains_ty(cx, ty)
|
||||
/// ```
|
||||
///
|
||||
/// Use instead:
|
||||
/// ```rust,ignore
|
||||
/// utils::is_type_diagnostic_item(cx, ty, sym::Vec)
|
||||
/// is_type_diagnostic_item(cx, ty, sym::Vec)
|
||||
/// ```
|
||||
pub clippy::UNNECESSARY_DEF_PATH,
|
||||
Warn,
|
||||
|
|
@ -41,257 +33,65 @@ declare_tool_lint! {
|
|||
report_in_external_macro: true
|
||||
}
|
||||
|
||||
impl_lint_pass!(UnnecessaryDefPath => [UNNECESSARY_DEF_PATH]);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UnnecessaryDefPath {
|
||||
array_def_ids: FxIndexSet<(DefId, Span)>,
|
||||
linted_def_ids: FxHashSet<DefId>,
|
||||
}
|
||||
declare_lint_pass!(UnnecessaryDefPath => [UNNECESSARY_DEF_PATH]);
|
||||
|
||||
impl<'tcx> LateLintPass<'tcx> for UnnecessaryDefPath {
|
||||
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
|
||||
if is_lint_allowed(cx, UNNECESSARY_DEF_PATH, expr.hir_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
match expr.kind {
|
||||
ExprKind::Call(func, args) => self.check_call(cx, func, args, expr.span),
|
||||
ExprKind::Array(elements) => self.check_array(cx, elements, expr.span),
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
|
||||
fn check_crate_post(&mut self, cx: &LateContext<'tcx>) {
|
||||
for &(def_id, span) in &self.array_def_ids {
|
||||
if self.linted_def_ids.contains(&def_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (msg, sugg) = if let Some(sym) = cx.tcx.get_diagnostic_name(def_id) {
|
||||
("diagnostic item", format!("sym::{sym}"))
|
||||
} else if let Some(sym) = get_lang_item_name(cx, def_id) {
|
||||
("language item", format!("LangItem::{sym}"))
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
span_lint_and_help(
|
||||
cx,
|
||||
UNNECESSARY_DEF_PATH,
|
||||
span,
|
||||
format!("hardcoded path to a {msg}"),
|
||||
None,
|
||||
format!("convert all references to use `{sugg}`"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UnnecessaryDefPath {
|
||||
#[allow(clippy::too_many_lines)]
|
||||
fn check_call(&mut self, cx: &LateContext<'_>, func: &Expr<'_>, args: &[Expr<'_>], span: Span) {
|
||||
enum Item {
|
||||
LangItem(&'static str),
|
||||
DiagnosticItem(Symbol),
|
||||
}
|
||||
static PATHS: &[&[&str]] = &[
|
||||
&["clippy_utils", "match_def_path"],
|
||||
&["clippy_utils", "match_trait_method"],
|
||||
&["clippy_utils", "ty", "match_type"],
|
||||
&["clippy_utils", "is_expr_path_def_path"],
|
||||
];
|
||||
|
||||
if let [cx_arg, def_arg, args @ ..] = args
|
||||
&& let ExprKind::Path(path) = &func.kind
|
||||
&& let Some(id) = cx.qpath_res(path, func.hir_id).opt_def_id()
|
||||
&& let Some(which_path) = match_any_def_paths(cx, id, PATHS)
|
||||
&& let item_arg = if which_path == 4 { &args[1] } else { &args[0] }
|
||||
// Extract the path to the matched type
|
||||
&& let Some(segments) = path_to_matched_type(cx, item_arg)
|
||||
&& let segments = segments.iter().map(|sym| &**sym).collect::<Vec<_>>()
|
||||
&& let Some(def_id) = def_path_def_ids(cx.tcx, &segments[..]).next()
|
||||
if let ExprKind::Call(ctor, [_, path]) = expr.kind
|
||||
&& internal_paths::PATH_LOOKUP_NEW.matches_path(cx, ctor)
|
||||
&& let ExprKind::Array(segments) = peel_ref_operators(cx, path).kind
|
||||
&& let Some(macro_id) = expr.span.ctxt().outer_expn_data().macro_def_id
|
||||
{
|
||||
// Check if the target item is a diagnostic item or LangItem.
|
||||
#[rustfmt::skip]
|
||||
let (msg, item) = if let Some(item_name)
|
||||
= cx.tcx.diagnostic_items(def_id.krate).id_to_name.get(&def_id)
|
||||
{
|
||||
(
|
||||
"use of a def path to a diagnostic item",
|
||||
Item::DiagnosticItem(*item_name),
|
||||
)
|
||||
} else if let Some(item_name) = get_lang_item_name(cx, def_id) {
|
||||
(
|
||||
"use of a def path to a `LangItem`",
|
||||
Item::LangItem(item_name),
|
||||
)
|
||||
} else {
|
||||
return;
|
||||
let ns = match cx.tcx.item_name(macro_id).as_str() {
|
||||
"type_path" => PathNS::Type,
|
||||
"value_path" => PathNS::Value,
|
||||
"macro_path" => PathNS::Macro,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let has_ctor = match cx.tcx.def_kind(def_id) {
|
||||
DefKind::Struct => {
|
||||
let variant = cx.tcx.adt_def(def_id).non_enum_variant();
|
||||
variant.ctor.is_some() && variant.fields.iter().all(|f| f.vis.is_public())
|
||||
},
|
||||
DefKind::Variant => {
|
||||
let variant = cx.tcx.adt_def(cx.tcx.parent(def_id)).variant_with_id(def_id);
|
||||
variant.ctor.is_some() && variant.fields.iter().all(|f| f.vis.is_public())
|
||||
},
|
||||
_ => false,
|
||||
};
|
||||
let path: Vec<Symbol> = segments
|
||||
.iter()
|
||||
.map(|segment| {
|
||||
if let Some(const_def_id) = path_def_id(cx, segment)
|
||||
&& let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(const_def_id)
|
||||
&& let Some(value) = value.to_u32().discard_err()
|
||||
{
|
||||
Symbol::new(value)
|
||||
} else {
|
||||
panic!("failed to resolve path {:?}", expr.span);
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut app = Applicability::MachineApplicable;
|
||||
let cx_snip = snippet_with_applicability(cx, cx_arg.span, "..", &mut app);
|
||||
let def_snip = snippet_with_applicability(cx, def_arg.span, "..", &mut app);
|
||||
let (sugg, with_note) = match (which_path, item) {
|
||||
// match_def_path
|
||||
(0, Item::DiagnosticItem(item)) => (
|
||||
format!("{cx_snip}.tcx.is_diagnostic_item(sym::{item}, {def_snip})"),
|
||||
has_ctor,
|
||||
),
|
||||
(0, Item::LangItem(item)) => (
|
||||
format!("{cx_snip}.tcx.lang_items().get(LangItem::{item}) == Some({def_snip})"),
|
||||
has_ctor,
|
||||
),
|
||||
// match_trait_method
|
||||
(1, Item::DiagnosticItem(item)) => {
|
||||
(format!("is_trait_method({cx_snip}, {def_snip}, sym::{item})"), false)
|
||||
},
|
||||
// match_type
|
||||
(2, Item::DiagnosticItem(item)) => (
|
||||
format!("is_type_diagnostic_item({cx_snip}, {def_snip}, sym::{item})"),
|
||||
false,
|
||||
),
|
||||
(2, Item::LangItem(item)) => (
|
||||
format!("is_type_lang_item({cx_snip}, {def_snip}, LangItem::{item})"),
|
||||
false,
|
||||
),
|
||||
// is_expr_path_def_path
|
||||
(3, Item::DiagnosticItem(item)) if has_ctor => (
|
||||
format!("is_res_diag_ctor({cx_snip}, path_res({cx_snip}, {def_snip}), sym::{item})",),
|
||||
false,
|
||||
),
|
||||
(3, Item::LangItem(item)) if has_ctor => (
|
||||
format!("is_res_lang_ctor({cx_snip}, path_res({cx_snip}, {def_snip}), LangItem::{item})",),
|
||||
false,
|
||||
),
|
||||
(3, Item::DiagnosticItem(item)) => (
|
||||
format!("is_path_diagnostic_item({cx_snip}, {def_snip}, sym::{item})"),
|
||||
false,
|
||||
),
|
||||
(3, Item::LangItem(item)) => (
|
||||
format!(
|
||||
"path_res({cx_snip}, {def_snip}).opt_def_id()\
|
||||
.map_or(false, |id| {cx_snip}.tcx.lang_items().get(LangItem::{item}) == Some(id))",
|
||||
),
|
||||
false,
|
||||
),
|
||||
_ => return,
|
||||
};
|
||||
|
||||
span_lint_and_then(cx, UNNECESSARY_DEF_PATH, span, msg, |diag| {
|
||||
diag.span_suggestion(span, "try", sugg, app);
|
||||
if with_note {
|
||||
diag.help(
|
||||
"if this `DefId` came from a constructor expression or pattern then the \
|
||||
parent `DefId` should be used instead",
|
||||
for def_id in lookup_path(cx.tcx, ns, &path) {
|
||||
if let Some(name) = cx.tcx.get_diagnostic_name(def_id) {
|
||||
span_lint_and_then(
|
||||
cx,
|
||||
UNNECESSARY_DEF_PATH,
|
||||
expr.span.source_callsite(),
|
||||
format!("a diagnostic name exists for this path: sym::{name}"),
|
||||
|diag| {
|
||||
diag.help(
|
||||
"remove the `PathLookup` and use utilities such as `cx.tcx.is_diagnostic_item` instead",
|
||||
);
|
||||
diag.help("see also https://doc.rust-lang.org/nightly/nightly-rustc/?search=diag&filter-crate=clippy_utils");
|
||||
},
|
||||
);
|
||||
} else if let Some(item_name) = get_lang_item_name(cx, def_id) {
|
||||
span_lint_and_then(
|
||||
cx,
|
||||
UNNECESSARY_DEF_PATH,
|
||||
expr.span.source_callsite(),
|
||||
format!("a language item exists for this path: LangItem::{item_name}"),
|
||||
|diag| {
|
||||
diag.help("remove the `PathLookup` and use utilities such as `cx.tcx.lang_items` instead");
|
||||
diag.help("see also https://doc.rust-lang.org/nightly/nightly-rustc/?search=lang&filter-crate=clippy_utils");
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
self.linted_def_ids.insert(def_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn check_array(&mut self, cx: &LateContext<'_>, elements: &[Expr<'_>], span: Span) {
|
||||
let Some(path) = path_from_array(elements) else { return };
|
||||
|
||||
for def_id in def_path_def_ids(cx.tcx, &path.iter().map(AsRef::as_ref).collect::<Vec<_>>()) {
|
||||
self.array_def_ids.insert((def_id, span));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn path_to_matched_type(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Vec<String>> {
|
||||
match peel_hir_expr_refs(expr).0.kind {
|
||||
ExprKind::Path(ref qpath) => match cx.qpath_res(qpath, expr.hir_id) {
|
||||
Res::Local(hir_id) => {
|
||||
if let Node::LetStmt(LetStmt { init: Some(init), .. }) = cx.tcx.parent_hir_node(hir_id) {
|
||||
path_to_matched_type(cx, init)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
},
|
||||
Res::Def(DefKind::Static { .. }, def_id) => read_mir_alloc_def_path(
|
||||
cx,
|
||||
cx.tcx.eval_static_initializer(def_id).ok()?.inner(),
|
||||
cx.tcx.type_of(def_id).instantiate_identity(),
|
||||
),
|
||||
Res::Def(DefKind::Const, def_id) => match cx.tcx.const_eval_poly(def_id).ok()? {
|
||||
ConstValue::Indirect { alloc_id, offset } if offset.bytes() == 0 => {
|
||||
let alloc = cx.tcx.global_alloc(alloc_id).unwrap_memory();
|
||||
read_mir_alloc_def_path(cx, alloc.inner(), cx.tcx.type_of(def_id).instantiate_identity())
|
||||
},
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
},
|
||||
ExprKind::Array(exprs) => path_from_array(exprs),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_mir_alloc_def_path<'tcx>(cx: &LateContext<'tcx>, alloc: &'tcx Allocation, ty: Ty<'_>) -> Option<Vec<String>> {
|
||||
let (alloc, ty) = if let ty::Ref(_, ty, Mutability::Not) = *ty.kind() {
|
||||
let &alloc = alloc.provenance().ptrs().values().next()?;
|
||||
if let GlobalAlloc::Memory(alloc) = cx.tcx.global_alloc(alloc.alloc_id()) {
|
||||
(alloc.inner(), ty)
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
(alloc, ty)
|
||||
};
|
||||
|
||||
if let ty::Array(ty, _) | ty::Slice(ty) = *ty.kind()
|
||||
&& let ty::Ref(_, ty, Mutability::Not) = *ty.kind()
|
||||
&& ty.is_str()
|
||||
{
|
||||
alloc
|
||||
.provenance()
|
||||
.ptrs()
|
||||
.values()
|
||||
.map(|&alloc| {
|
||||
if let GlobalAlloc::Memory(alloc) = cx.tcx.global_alloc(alloc.alloc_id()) {
|
||||
let alloc = alloc.inner();
|
||||
str::from_utf8(alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()))
|
||||
.ok()
|
||||
.map(ToOwned::to_owned)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn path_from_array(exprs: &[Expr<'_>]) -> Option<Vec<String>> {
|
||||
exprs
|
||||
.iter()
|
||||
.map(|expr| {
|
||||
if let ExprKind::Lit(lit) = &expr.kind
|
||||
&& let LitKind::Str(sym, _) = lit.node
|
||||
{
|
||||
return Some((*sym.as_str()).to_owned());
|
||||
}
|
||||
|
||||
None
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_lang_item_name(cx: &LateContext<'_>, def_id: DefId) -> Option<&'static str> {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue