1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_hir_and_then};
2 use clippy_utils::source::{snippet, snippet_opt};
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir::intravisit::FnKind;
7 self as hir, def, BinOpKind, BindingAnnotation, Body, ByRef, Expr, ExprKind, FnDecl, HirId, Mutability, PatKind,
8 Stmt, StmtKind, TyKind,
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::hygiene::DesugaringKind;
14 use rustc_span::source_map::{ExpnKind, Span};
16 use clippy_utils::sugg::Sugg;
17 use clippy_utils::{get_parent_expr, in_constant, is_integer_literal, iter_input_pats, last_path_segment, SpanlessEq};
19 declare_clippy_lint! {
21 /// Checks for function arguments and let bindings denoted as
24 /// ### Why is this bad?
25 /// The `ref` declaration makes the function take an owned
26 /// value, but turns the argument into a reference (which means that the value
27 /// is destroyed when exiting the function). This adds not much value: either
28 /// take a reference type, or take an owned value and create references in the
31 /// For let bindings, `let x = &foo;` is preferred over `let ref x = foo`. The
32 /// type of `x` is more obvious with the former.
34 /// ### Known problems
35 /// If the argument is dereferenced within the function,
36 /// removing the `ref` will lead to errors. This can be fixed by removing the
37 /// dereferences, e.g., changing `*x` to `x` within the function.
41 /// fn foo(ref _x: u8) {}
46 /// fn foo(_x: &u8) {}
48 #[clippy::version = "pre 1.29.0"]
51 "an entire binding declared as `ref`, in a function argument or a `let` statement"
53 declare_clippy_lint! {
55 /// Checks for the use of bindings with a single leading
58 /// ### Why is this bad?
59 /// A single leading underscore is usually used to indicate
60 /// that a binding will not be used. Using such a binding breaks this
63 /// ### Known problems
64 /// The lint does not work properly with desugaring and
65 /// macro, it has been allowed in the mean time.
70 /// let y = _x + 1; // Here we are using `_x`, even though it has a leading
71 /// // underscore. We should rename `_x` to `x`
73 #[clippy::version = "pre 1.29.0"]
74 pub USED_UNDERSCORE_BINDING,
76 "using a binding which is prefixed with an underscore"
79 declare_clippy_lint! {
81 /// Checks for the use of short circuit boolean conditions as
85 /// ### Why is this bad?
86 /// Using a short circuit boolean condition as a statement
87 /// may hide the fact that the second part is executed or not depending on the
88 /// outcome of the first part.
92 /// f() && g(); // We should write `if f() { g(); }`.
94 #[clippy::version = "pre 1.29.0"]
95 pub SHORT_CIRCUIT_STATEMENT,
97 "using a short circuit boolean condition as a statement"
100 declare_clippy_lint! {
102 /// Catch casts from `0` to some pointer type
104 /// ### Why is this bad?
105 /// This generally means `null` and is better expressed as
106 /// {`std`, `core`}`::ptr::`{`null`, `null_mut`}.
110 /// let a = 0 as *const u32;
115 /// let a = std::ptr::null::<u32>();
117 #[clippy::version = "pre 1.29.0"]
120 "using `0 as *{const, mut} T`"
123 declare_lint_pass!(MiscLints => [
125 USED_UNDERSCORE_BINDING,
126 SHORT_CIRCUIT_STATEMENT,
130 impl<'tcx> LateLintPass<'tcx> for MiscLints {
133 cx: &LateContext<'tcx>,
135 decl: &'tcx FnDecl<'_>,
136 body: &'tcx Body<'_>,
140 if let FnKind::Closure = k {
141 // Does not apply to closures
144 if in_external_macro(cx.tcx.sess, span) {
147 for arg in iter_input_pats(decl, body) {
148 if let PatKind::Binding(BindingAnnotation(ByRef::Yes, _), ..) = arg.pat.kind {
153 "`ref` directly on a function argument is ignored. \
154 Consider using a reference type instead",
160 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
162 if !in_external_macro(cx.tcx.sess, stmt.span);
163 if let StmtKind::Local(local) = stmt.kind;
164 if let PatKind::Binding(BindingAnnotation(ByRef::Yes, mutabl), .., name, None) = local.pat.kind;
165 if let Some(init) = local.init;
167 // use the macro callsite when the init span (but not the whole local span)
168 // comes from an expansion like `vec![1, 2, 3]` in `let ref _ = vec![1, 2, 3];`
169 let sugg_init = if init.span.from_expansion() && !local.span.from_expansion() {
170 Sugg::hir_with_macro_callsite(cx, init, "..")
172 Sugg::hir(cx, init, "..")
174 let (mutopt, initref) = if mutabl == Mutability::Mut {
175 ("mut ", sugg_init.mut_addr())
177 ("", sugg_init.addr())
179 let tyopt = if let Some(ty) = local.ty {
180 format!(": &{mutopt}{ty}", ty=snippet(cx, ty.span, ".."))
184 span_lint_hir_and_then(
189 "`ref` on an entire `let` pattern is discouraged, take a reference with `&` instead",
191 diag.span_suggestion(
195 "let {name}{tyopt} = {initref};",
196 name=snippet(cx, name.span, ".."),
198 Applicability::MachineApplicable,
205 if let StmtKind::Semi(expr) = stmt.kind;
206 if let ExprKind::Binary(ref binop, a, b) = expr.kind;
207 if binop.node == BinOpKind::And || binop.node == BinOpKind::Or;
208 if let Some(sugg) = Sugg::hir_opt(cx, a);
210 span_lint_hir_and_then(
212 SHORT_CIRCUIT_STATEMENT,
215 "boolean short circuit operator in statement may be clearer using an explicit test",
217 let sugg = if binop.node == BinOpKind::Or { !sugg } else { sugg };
218 diag.span_suggestion(
222 "if {sugg} {{ {}; }}",
223 &snippet(cx, b.span, ".."),
225 Applicability::MachineApplicable, // snippet
232 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
233 if let ExprKind::Cast(e, ty) = expr.kind {
234 check_cast(cx, expr.span, e, ty);
237 if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) {
238 // Don't lint things expanded by #[derive(...)], etc or `await` desugaring
242 let binding = match expr.kind {
243 ExprKind::Path(ref qpath) if !matches!(qpath, hir::QPath::LangItem(..)) => {
244 let binding = last_path_segment(qpath).ident.as_str();
245 if binding.starts_with('_') &&
246 !binding.starts_with("__") &&
247 binding != "_result" && // FIXME: #944
249 // don't lint if the declaration is in a macro
250 non_macro_local(cx, cx.qpath_res(qpath, expr.hir_id))
257 ExprKind::Field(_, ident) => {
259 let name = sym.as_str();
260 if name.starts_with('_') && !name.starts_with("__") {
268 if let Some(binding) = binding {
271 USED_UNDERSCORE_BINDING,
274 "used binding `{binding}` which is prefixed with an underscore. A leading \
275 underscore signals that a binding will not be used"
282 /// Heuristic to see if an expression is used. Should be compatible with
283 /// `unused_variables`'s idea
284 /// of what it means for an expression to be "used".
285 fn is_used(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
286 get_parent_expr(cx, expr).map_or(true, |parent| match parent.kind {
287 ExprKind::Assign(_, rhs, _) | ExprKind::AssignOp(_, _, rhs) => SpanlessEq::new(cx).eq_expr(rhs, expr),
288 _ => is_used(cx, parent),
292 /// Tests whether an expression is in a macro expansion (e.g., something
293 /// generated by `#[derive(...)]` or the like).
294 fn in_attributes_expansion(expr: &Expr<'_>) -> bool {
295 use rustc_span::hygiene::MacroKind;
296 if expr.span.from_expansion() {
297 let data = expr.span.ctxt().outer_expn_data();
298 matches!(data.kind, ExpnKind::Macro(MacroKind::Attr | MacroKind::Derive, _))
304 /// Tests whether `res` is a variable defined outside a macro.
305 fn non_macro_local(cx: &LateContext<'_>, res: def::Res) -> bool {
306 if let def::Res::Local(id) = res {
307 !cx.tcx.hir().span(id).from_expansion()
313 fn check_cast(cx: &LateContext<'_>, span: Span, e: &Expr<'_>, ty: &hir::Ty<'_>) {
315 if let TyKind::Ptr(ref mut_ty) = ty.kind;
316 if is_integer_literal(e, 0);
317 if !in_constant(cx, e.hir_id);
319 let (msg, sugg_fn) = match mut_ty.mutbl {
320 Mutability::Mut => ("`0 as *mut _` detected", "std::ptr::null_mut"),
321 Mutability::Not => ("`0 as *const _` detected", "std::ptr::null"),
324 let (sugg, appl) = if let TyKind::Infer = mut_ty.ty.kind {
325 (format!("{sugg_fn}()"), Applicability::MachineApplicable)
326 } else if let Some(mut_ty_snip) = snippet_opt(cx, mut_ty.ty.span) {
327 (format!("{sugg_fn}::<{mut_ty_snip}>()"), Applicability::MachineApplicable)
329 // `MaybeIncorrect` as type inference may not work with the suggested code
330 (format!("{sugg_fn}()"), Applicability::MaybeIncorrect)
332 span_lint_and_sugg(cx, ZERO_PTR, span, msg, "try", sugg, appl);