Skip to content
Open
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
8 changes: 5 additions & 3 deletions clippy_lints/src/booleans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then};
use clippy_utils::higher::has_let_expr;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::res::MaybeDef as _;
use clippy_utils::source::{SpanExt as _, snippet_with_context};
use clippy_utils::source::{SpanExt as _, snippet_with_context, with_tracked_source};
use clippy_utils::sugg::Sugg;
use clippy_utils::ty::implements_trait;
use clippy_utils::{eq_expr_value, sym};
Expand Down Expand Up @@ -106,7 +106,7 @@ impl<'tcx> LateLintPass<'tcx> for NonminimalBool {
_: Span,
_: LocalDefId,
) {
NonminimalBoolVisitor { cx, msrv: self.msrv }.visit_body(body);
with_tracked_source(cx, || NonminimalBoolVisitor { cx, msrv: self.msrv }.visit_body(body));
}

fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
Expand All @@ -118,7 +118,9 @@ impl<'tcx> LateLintPass<'tcx> for NonminimalBool {
// !a == false;
// ```
ExprKind::Binary(op, left, right) if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) => {
check_inverted_bool_in_condition(cx, expr.span, op.node, left, right);
with_tracked_source(cx, || {
check_inverted_bool_in_condition(cx, expr.span, op.node, left, right);
});
},
_ => {},
}
Expand Down
7 changes: 6 additions & 1 deletion clippy_lints/src/comparison_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,15 @@ declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]);

impl<'tcx> LateLintPass<'tcx> for ComparisonChain {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if expr.span.from_expansion() {
if !matches!(expr.kind, ExprKind::If(..)) || expr.span.from_expansion() {
return;
}
clippy_utils::source::with_tracked_source(cx, || Self::check_chain(cx, expr));
}
}

impl ComparisonChain {
fn check_chain(cx: &LateContext<'_>, expr: &Expr<'_>) {
// We only care about the top-most `if` in the chain
if is_else_clause(cx.tcx, expr) {
return;
Expand Down
16 changes: 14 additions & 2 deletions clippy_lints/src/doc/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use clippy_config::Conf;
use clippy_utils::attrs::is_doc_hidden;
use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_then};
use clippy_utils::source::{track_span_source, with_tracked_source};
use clippy_utils::{is_entrypoint_fn, is_trait_impl_item};
use rustc_attr_ir::Attribute;
use rustc_data_structures::fx::FxHashSet;
Expand Down Expand Up @@ -707,7 +708,6 @@ declare_clippy_lint! {
impl_lint_pass!(Documentation => [
DOC_BROKEN_LINK,
DOC_COMMENT_DOUBLE_SPACE_LINEBREAKS,
DOC_INCLUDE_WITHOUT_CFG,
DOC_LAZY_CONTINUATION,
DOC_LINK_CODE,
DOC_LINK_WITH_QUOTES,
Expand All @@ -727,6 +727,8 @@ impl_lint_pass!(Documentation => [
UNNECESSARY_SAFETY_DOC,
]);

impl_lint_pass!(EarlyDocumentation => [DOC_INCLUDE_WITHOUT_CFG]);

pub struct Documentation {
valid_idents: &'static FxHashSet<String>,
check_private_items: bool,
Expand All @@ -741,14 +743,22 @@ impl Documentation {
}
}

impl EarlyLintPass for Documentation {
pub struct EarlyDocumentation;

impl EarlyLintPass for EarlyDocumentation {
fn check_attributes(&mut self, cx: &EarlyContext<'_>, attrs: &[rustc_ast::Attribute]) {
include_in_doc_without_cfg::check(cx, attrs);
}
}

impl<'tcx> LateLintPass<'tcx> for Documentation {
fn check_attributes(&mut self, cx: &LateContext<'tcx>, attrs: &'tcx [Attribute]) {
with_tracked_source(cx, || self.check_late_attributes(cx, attrs));
}
}

impl Documentation {
fn check_late_attributes<'tcx>(&self, cx: &LateContext<'tcx>, attrs: &'tcx [Attribute]) {
let Some(headers) = check_attrs(cx, self.valid_idents, attrs) else {
return;
};
Expand Down Expand Up @@ -890,6 +900,8 @@ fn check_attrs(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &[
let mut doc = String::with_capacity(fragments.iter().map(|frag| frag.doc.as_str().len() + 1).sum());

for fragment in &fragments {
// Rustdoc also maps Markdown byte ranges back to raw source spans.
track_span_source(cx, fragment.span);
add_doc_fragment(&mut doc, fragment);
}
doc.pop();
Expand Down
21 changes: 19 additions & 2 deletions clippy_lints/src/incremental_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ macro_rules! audited_passes {

#[rustfmt::skip]
audited_passes!((conf: &'static Conf), [
Documentation: crate::doc::Documentation = crate::doc::Documentation::new(conf),
UnitExpressions: crate::unit_types::UnitExpressions = crate::unit_types::UnitExpressions,
NonminimalBool: crate::booleans::NonminimalBool = crate::booleans::NonminimalBool::new(conf),
ComparisonChain: crate::comparison_chain::ComparisonChain = crate::comparison_chain::ComparisonChain,
UnnecessaryWraps: crate::unnecessary_wraps::UnnecessaryWraps = crate::unnecessary_wraps::UnnecessaryWraps::new(conf),
NeedlessBorrowsForGenericArgs: crate::needless_borrows_for_generic_args::NeedlessBorrowsForGenericArgs<'tcx> = crate::needless_borrows_for_generic_args::NeedlessBorrowsForGenericArgs::new(conf),
NeedlessPassByValue: crate::needless_pass_by_value::NeedlessPassByValue = crate::needless_pass_by_value::NeedlessPassByValue,
Expand Down Expand Up @@ -113,8 +117,21 @@ fn inputs_available(lints: &LintVec) -> bool {
clippy_utils::source::SOURCE_FILE_INPUT.get().is_some() || !lints.iter().any(|lint| requires_source_input(lint))
}

fn requires_source_input(lint: &rustc_lint::Lint) -> bool {
std::ptr::eq(lint, crate::needless_pass_by_value::NEEDLESS_PASS_BY_VALUE)
fn requires_source_input(lint: &'static rustc_lint::Lint) -> bool {
static DOC_LINTS: OnceLock<FxHashSet<LintId>> = OnceLock::new();
let doc_lints = DOC_LINTS.get_or_init(|| {
crate::doc::Documentation::lint_vec()
.into_iter()
.map(LintId::of)
.collect()
});
if doc_lints.contains(&LintId::of(lint)) || std::ptr::eq(lint, crate::unit_types::UNIT_ARG) {
return true;
}
std::ptr::eq(lint, crate::booleans::NONMINIMAL_BOOL)
|| std::ptr::eq(lint, crate::booleans::OVERLY_COMPLEX_BOOL_EXPR)
|| std::ptr::eq(lint, crate::comparison_chain::COMPARISON_CHAIN)
|| std::ptr::eq(lint, crate::needless_pass_by_value::NEEDLESS_PASS_BY_VALUE)
|| std::ptr::eq(lint, crate::redundant_clone::REDUNDANT_CLONE)
|| std::ptr::eq(lint, crate::unnecessary_wraps::UNNECESSARY_WRAPS)
|| std::ptr::eq(
Expand Down
3 changes: 2 additions & 1 deletion clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ rustc_lint::early_lint_methods!(
RedundantFieldNames: redundant_field_names::RedundantFieldNames = redundant_field_names::RedundantFieldNames::new(conf),
UnnestedOrPatterns: unnested_or_patterns::UnnestedOrPatterns = unnested_or_patterns::UnnestedOrPatterns::new(conf),
EarlyFunctions: functions::EarlyFunctions = functions::EarlyFunctions,
Documentation: doc::Documentation = doc::Documentation::new(conf),
Documentation: doc::EarlyDocumentation = doc::EarlyDocumentation,
SuspiciousOperationGroupings: suspicious_operation_groupings::SuspiciousOperationGroupings = <suspicious_operation_groupings::SuspiciousOperationGroupings>::default(),
DoubleParens: double_parens::DoubleParens = double_parens::DoubleParens,
UnsafeNameRemoval: unsafe_removed_from_name::UnsafeNameRemoval = unsafe_removed_from_name::UnsafeNameRemoval,
Expand Down Expand Up @@ -613,6 +613,7 @@ rustc_lint::late_lint_methods!(
InconsistentStructConstructor: inconsistent_struct_constructor::InconsistentStructConstructor = inconsistent_struct_constructor::InconsistentStructConstructor::new( conf, ),
Methods: methods::Methods = methods::Methods::new(conf, format_args.clone()),
UnitTypes: unit_types::UnitTypes = unit_types::UnitTypes::new(format_args.clone()),
UnitExpressions: unit_types::UnitExpressions = unit_types::UnitExpressions,
Loops: loops::Loops = loops::Loops::new(conf),
MainRecursion: main_recursion::MainRecursion = <main_recursion::MainRecursion>::default(),
Lifetimes: lifetimes::Lifetimes = lifetimes::Lifetimes::new(conf),
Expand Down
98 changes: 43 additions & 55 deletions clippy_lints/src/macro_use.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use rustc_errors::Applicability;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::{self as hir, AmbigArg, UseTree};
use rustc_lint::{LateContext, LateLintPass, LintContext as _, impl_lint_pass};
use rustc_span::Span;
use rustc_span::edition::Edition;
use rustc_span::{Span, SyntaxContext};
use std::collections::BTreeMap;

declare_clippy_lint! {
Expand Down Expand Up @@ -45,51 +45,43 @@ declare_clippy_lint! {

impl_lint_pass!(MacroUseImports => [MACRO_USE_IMPORTS]);

/// `MacroRefData` includes the name of the macro.
#[derive(Debug, Clone)]
pub struct MacroRefData {
name: String,
}

impl MacroRefData {
pub fn new(name: String) -> Self {
Self { name }
}
}

#[derive(Default)]
pub struct MacroUseImports {
/// the actual import path used and the span of the attribute above it. The value is
/// the location, where the lint should be emitted.
imports: Vec<(String, Span, hir::HirId)>,
/// the span of the macro reference, kept to ensure only one reference is used per macro call.
collected: FxHashSet<Span>,
mac_refs: Vec<MacroRefData>,
expansions: FxHashSet<SyntaxContext>,
/// The first visit selects how the lint spells each macro reference.
references: Vec<(Span, bool)>,
}

impl MacroUseImports {
fn push_unique_macro(&mut self, cx: &LateContext<'_>, span: Span) {
let call_site = span.source_callsite();
let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
if span.source_callee().is_some() && !self.collected.contains(&call_site) {
let name = if name.contains("::") {
name.split("::").last().unwrap().to_string()
} else {
name.to_string()
};

self.mac_refs.push(MacroRefData::new(name));
self.collected.insert(call_site);
fn record_reference(&mut self, span: Span, strip_path: bool) {
let context = span.ctxt();
// For a non-root context the call site comes entirely from the
// expansion chain. Preserve its first visit and the original spelling.
if !context.is_root() && self.expansions.insert(context) {
self.references.push((span, strip_path));
}
}

fn push_unique_macro_pat_ty(&mut self, cx: &LateContext<'_>, span: Span) {
let call_site = span.source_callsite();
let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
if span.source_callee().is_some() && !self.collected.contains(&call_site) {
self.mac_refs.push(MacroRefData::new(name.to_string()));
self.collected.insert(call_site);
fn macro_names(&self, cx: &LateContext<'_>) -> Vec<String> {
// Different inner expansions can still have the same outer call site.
let mut call_sites = FxHashSet::default();
let mut names = Vec::new();
for &(span, strip_path) in &self.references {
let call_site = span.source_callsite();
if call_sites.insert(call_site) {
let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
let name = if strip_path {
name.rsplit("::").next().unwrap()
} else {
&name
};
names.push(name.to_owned());
}
}
names
}
}

Expand All @@ -109,38 +101,34 @@ impl LateLintPass<'_> for MacroUseImports {
self.imports.push((def_path, mac_attr_span, hir_id));
}
}
} else if item.span.from_expansion() {
self.push_unique_macro_pat_ty(cx, item.span);
} else {
self.record_reference(item.span, false);
}
}
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
if expr.span.from_expansion() {
self.push_unique_macro(cx, expr.span);
}
fn check_expr(&mut self, _: &LateContext<'_>, expr: &hir::Expr<'_>) {
self.record_reference(expr.span, true);
}
fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
if stmt.span.from_expansion() {
self.push_unique_macro(cx, stmt.span);
}
fn check_stmt(&mut self, _: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
self.record_reference(stmt.span, true);
}
fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
if pat.span.from_expansion() {
self.push_unique_macro_pat_ty(cx, pat.span);
}
fn check_pat(&mut self, _: &LateContext<'_>, pat: &hir::Pat<'_>) {
self.record_reference(pat.span, false);
}
fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_, AmbigArg>) {
if ty.span.from_expansion() {
self.push_unique_macro_pat_ty(cx, ty.span);
}
fn check_ty(&mut self, _: &LateContext<'_>, ty: &hir::Ty<'_, AmbigArg>) {
self.record_reference(ty.span, false);
}
fn check_crate_post(&mut self, cx: &LateContext<'_>) {
if self.imports.is_empty() {
return;
}
let mut mac_refs = self.macro_names(cx);
let mut used = BTreeMap::new();
let mut check_dup = vec![];
for (import, span, hir_id) in &self.imports {
let found_idx = self.mac_refs.iter().position(|mac| import.ends_with(&mac.name));
let found_idx = mac_refs.iter().position(|name| import.ends_with(name.as_str()));

if let Some(idx) = found_idx {
self.mac_refs.remove(idx);
mac_refs.remove(idx);
let seg = import.split("::").collect::<Vec<_>>();

match seg.as_slice() {
Expand Down Expand Up @@ -203,7 +191,7 @@ impl LateLintPass<'_> for MacroUseImports {

// If mac_refs is not empty we have encountered an import we could not handle
// such as `std::prelude::v1::foo` or some other macro that expands to an import.
if self.mac_refs.is_empty() {
if mac_refs.is_empty() {
for ((root, span, ..), (path, hir_id)) in used {
let import = if let [single] = &path[..] {
format!("{root}::{single}")
Expand Down
10 changes: 8 additions & 2 deletions clippy_lints/src/unit_types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,11 @@ declare_clippy_lint! {
"comparing unit values"
}

impl_lint_pass!(UnitTypes => [LET_UNIT_VALUE, UNIT_ARG, UNIT_CMP]);
impl_lint_pass!(UnitExpressions => [UNIT_ARG, UNIT_CMP]);

impl_lint_pass!(UnitTypes => [LET_UNIT_VALUE]);

pub struct UnitExpressions;

pub struct UnitTypes {
format_args: FormatArgsStorage,
Expand All @@ -112,9 +116,11 @@ impl<'tcx> LateLintPass<'tcx> for UnitTypes {
fn check_local(&mut self, cx: &LateContext<'tcx>, local: &'tcx LetStmt<'tcx>) {
let_unit_value::check(cx, &self.format_args, local);
}
}

impl<'tcx> LateLintPass<'tcx> for UnitExpressions {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
unit_cmp::check(cx, expr);
unit_arg::check(cx, expr);
clippy_utils::source::with_tracked_source(cx, || unit_arg::check(cx, expr));
}
}
Loading
Loading