]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/utils/internal_lints.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / utils / internal_lints.rs
1 use clippy_utils::consts::{constant_simple, Constant};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
3 use clippy_utils::source::snippet;
4 use clippy_utils::ty::match_type;
5 use clippy_utils::{
6 is_else_clause, is_expn_of, is_expr_path_def_path, is_lint_allowed, match_def_path, method_calls, path_to_res,
7 paths, SpanlessEq,
8 };
9 use if_chain::if_chain;
10 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, ModKind, NodeId};
11 use rustc_ast::visit::FnKind;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_errors::Applicability;
14 use rustc_hir as hir;
15 use rustc_hir::def::{DefKind, Res};
16 use rustc_hir::def_id::DefId;
17 use rustc_hir::hir_id::CRATE_HIR_ID;
18 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
19 use rustc_hir::{
20 BinOpKind, Block, Crate, Expr, ExprKind, HirId, Item, Local, MatchSource, MutTy, Mutability, Node, Path, Stmt,
21 StmtKind, Ty, TyKind, UnOp,
22 };
23 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
24 use rustc_middle::hir::map::Map;
25 use rustc_middle::mir::interpret::ConstValue;
26 use rustc_middle::ty;
27 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
28 use rustc_span::source_map::Spanned;
29 use rustc_span::symbol::{Symbol, SymbolStr};
30 use rustc_span::{BytePos, Span};
31 use rustc_typeck::hir_ty_to_ty;
32
33 use std::borrow::{Borrow, Cow};
34
35 #[cfg(feature = "metadata-collector-lint")]
36 pub mod metadata_collector;
37
38 declare_clippy_lint! {
39 /// ### What it does
40 /// Checks for various things we like to keep tidy in clippy.
41 ///
42 /// ### Why is this bad?
43 /// We like to pretend we're an example of tidy code.
44 ///
45 /// ### Example
46 /// Wrong ordering of the util::paths constants.
47 pub CLIPPY_LINTS_INTERNAL,
48 internal,
49 "various things that will negatively affect your clippy experience"
50 }
51
52 declare_clippy_lint! {
53 /// ### What it does
54 /// Ensures every lint is associated to a `LintPass`.
55 ///
56 /// ### Why is this bad?
57 /// The compiler only knows lints via a `LintPass`. Without
58 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
59 /// know the name of the lint.
60 ///
61 /// ### Known problems
62 /// Only checks for lints associated using the
63 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
64 ///
65 /// ### Example
66 /// ```rust,ignore
67 /// declare_lint! { pub LINT_1, ... }
68 /// declare_lint! { pub LINT_2, ... }
69 /// declare_lint! { pub FORGOTTEN_LINT, ... }
70 /// // ...
71 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
72 /// // missing FORGOTTEN_LINT
73 /// ```
74 pub LINT_WITHOUT_LINT_PASS,
75 internal,
76 "declaring a lint without associating it in a LintPass"
77 }
78
79 declare_clippy_lint! {
80 /// ### What it does
81 /// Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
82 /// variant of the function.
83 ///
84 /// ### Why is this bad?
85 /// The `utils::*` variants also add a link to the Clippy documentation to the
86 /// warning/error messages.
87 ///
88 /// ### Example
89 /// Bad:
90 /// ```rust,ignore
91 /// cx.span_lint(LINT_NAME, "message");
92 /// ```
93 ///
94 /// Good:
95 /// ```rust,ignore
96 /// utils::span_lint(cx, LINT_NAME, "message");
97 /// ```
98 pub COMPILER_LINT_FUNCTIONS,
99 internal,
100 "usage of the lint functions of the compiler instead of the utils::* variant"
101 }
102
103 declare_clippy_lint! {
104 /// ### What it does
105 /// Checks for calls to `cx.outer().expn_data()` and suggests to use
106 /// the `cx.outer_expn_data()`
107 ///
108 /// ### Why is this bad?
109 /// `cx.outer_expn_data()` is faster and more concise.
110 ///
111 /// ### Example
112 /// Bad:
113 /// ```rust,ignore
114 /// expr.span.ctxt().outer().expn_data()
115 /// ```
116 ///
117 /// Good:
118 /// ```rust,ignore
119 /// expr.span.ctxt().outer_expn_data()
120 /// ```
121 pub OUTER_EXPN_EXPN_DATA,
122 internal,
123 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
124 }
125
126 declare_clippy_lint! {
127 /// ### What it does
128 /// Not an actual lint. This lint is only meant for testing our customized internal compiler
129 /// error message by calling `panic`.
130 ///
131 /// ### Why is this bad?
132 /// ICE in large quantities can damage your teeth
133 ///
134 /// ### Example
135 /// Bad:
136 /// ```rust,ignore
137 /// 🍦🍦🍦🍦🍦
138 /// ```
139 pub PRODUCE_ICE,
140 internal,
141 "this message should not appear anywhere as we ICE before and don't emit the lint"
142 }
143
144 declare_clippy_lint! {
145 /// ### What it does
146 /// Checks for cases of an auto-generated lint without an updated description,
147 /// i.e. `default lint description`.
148 ///
149 /// ### Why is this bad?
150 /// Indicates that the lint is not finished.
151 ///
152 /// ### Example
153 /// Bad:
154 /// ```rust,ignore
155 /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
156 /// ```
157 ///
158 /// Good:
159 /// ```rust,ignore
160 /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
161 /// ```
162 pub DEFAULT_LINT,
163 internal,
164 "found 'default lint description' in a lint declaration"
165 }
166
167 declare_clippy_lint! {
168 /// ### What it does
169 /// Lints `span_lint_and_then` function calls, where the
170 /// closure argument has only one statement and that statement is a method
171 /// call to `span_suggestion`, `span_help`, `span_note` (using the same
172 /// span), `help` or `note`.
173 ///
174 /// These usages of `span_lint_and_then` should be replaced with one of the
175 /// wrapper functions `span_lint_and_sugg`, span_lint_and_help`, or
176 /// `span_lint_and_note`.
177 ///
178 /// ### Why is this bad?
179 /// Using the wrapper `span_lint_and_*` functions, is more
180 /// convenient, readable and less error prone.
181 ///
182 /// ### Example
183 /// Bad:
184 /// ```rust,ignore
185 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
186 /// diag.span_suggestion(
187 /// expr.span,
188 /// help_msg,
189 /// sugg.to_string(),
190 /// Applicability::MachineApplicable,
191 /// );
192 /// });
193 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
194 /// diag.span_help(expr.span, help_msg);
195 /// });
196 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
197 /// diag.help(help_msg);
198 /// });
199 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
200 /// diag.span_note(expr.span, note_msg);
201 /// });
202 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
203 /// diag.note(note_msg);
204 /// });
205 /// ```
206 ///
207 /// Good:
208 /// ```rust,ignore
209 /// span_lint_and_sugg(
210 /// cx,
211 /// TEST_LINT,
212 /// expr.span,
213 /// lint_msg,
214 /// help_msg,
215 /// sugg.to_string(),
216 /// Applicability::MachineApplicable,
217 /// );
218 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
219 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
220 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), note_msg);
221 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, None, note_msg);
222 /// ```
223 pub COLLAPSIBLE_SPAN_LINT_CALLS,
224 internal,
225 "found collapsible `span_lint_and_then` calls"
226 }
227
228 declare_clippy_lint! {
229 /// ### What it does
230 /// Checks for calls to `utils::match_type()` on a type diagnostic item
231 /// and suggests to use `utils::is_type_diagnostic_item()` instead.
232 ///
233 /// ### Why is this bad?
234 /// `utils::is_type_diagnostic_item()` does not require hardcoded paths.
235 ///
236 /// ### Example
237 /// Bad:
238 /// ```rust,ignore
239 /// utils::match_type(cx, ty, &paths::VEC)
240 /// ```
241 ///
242 /// Good:
243 /// ```rust,ignore
244 /// utils::is_type_diagnostic_item(cx, ty, sym::vec_type)
245 /// ```
246 pub MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
247 internal,
248 "using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
249 }
250
251 declare_clippy_lint! {
252 /// ### What it does
253 /// Checks the paths module for invalid paths.
254 ///
255 /// ### Why is this bad?
256 /// It indicates a bug in the code.
257 ///
258 /// ### Example
259 /// None.
260 pub INVALID_PATHS,
261 internal,
262 "invalid path"
263 }
264
265 declare_clippy_lint! {
266 /// ### What it does
267 /// Checks for interning symbols that have already been pre-interned and defined as constants.
268 ///
269 /// ### Why is this bad?
270 /// It's faster and easier to use the symbol constant.
271 ///
272 /// ### Example
273 /// Bad:
274 /// ```rust,ignore
275 /// let _ = sym!(f32);
276 /// ```
277 ///
278 /// Good:
279 /// ```rust,ignore
280 /// let _ = sym::f32;
281 /// ```
282 pub INTERNING_DEFINED_SYMBOL,
283 internal,
284 "interning a symbol that is pre-interned and defined as a constant"
285 }
286
287 declare_clippy_lint! {
288 /// ### What it does
289 /// Checks for unnecessary conversion from Symbol to a string.
290 ///
291 /// ### Why is this bad?
292 /// It's faster use symbols directly intead of strings.
293 ///
294 /// ### Example
295 /// Bad:
296 /// ```rust,ignore
297 /// symbol.as_str() == "clippy";
298 /// ```
299 ///
300 /// Good:
301 /// ```rust,ignore
302 /// symbol == sym::clippy;
303 /// ```
304 pub UNNECESSARY_SYMBOL_STR,
305 internal,
306 "unnecessary conversion between Symbol and string"
307 }
308
309 declare_clippy_lint! {
310 /// Finds unidiomatic usage of `if_chain!`
311 pub IF_CHAIN_STYLE,
312 internal,
313 "non-idiomatic `if_chain!` usage"
314 }
315
316 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
317
318 impl EarlyLintPass for ClippyLintsInternal {
319 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
320 if let Some(utils) = krate.items.iter().find(|item| item.ident.name.as_str() == "utils") {
321 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = utils.kind {
322 if let Some(paths) = items.iter().find(|item| item.ident.name.as_str() == "paths") {
323 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = paths.kind {
324 let mut last_name: Option<SymbolStr> = None;
325 for item in items {
326 let name = item.ident.as_str();
327 if let Some(ref last_name) = last_name {
328 if **last_name > *name {
329 span_lint(
330 cx,
331 CLIPPY_LINTS_INTERNAL,
332 item.span,
333 "this constant should be before the previous constant due to lexical \
334 ordering",
335 );
336 }
337 }
338 last_name = Some(name);
339 }
340 }
341 }
342 }
343 }
344 }
345 }
346
347 #[derive(Clone, Debug, Default)]
348 pub struct LintWithoutLintPass {
349 declared_lints: FxHashMap<Symbol, Span>,
350 registered_lints: FxHashSet<Symbol>,
351 }
352
353 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
354
355 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
356 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
357 if is_lint_allowed(cx, DEFAULT_LINT, item.hir_id()) {
358 return;
359 }
360
361 if let hir::ItemKind::Static(ty, Mutability::Not, body_id) = item.kind {
362 if is_lint_ref_type(cx, ty) {
363 let expr = &cx.tcx.hir().body(body_id).value;
364 if_chain! {
365 if let ExprKind::AddrOf(_, _, inner_exp) = expr.kind;
366 if let ExprKind::Struct(_, fields, _) = inner_exp.kind;
367 let field = fields
368 .iter()
369 .find(|f| f.ident.as_str() == "desc")
370 .expect("lints must have a description field");
371 if let ExprKind::Lit(Spanned {
372 node: LitKind::Str(ref sym, _),
373 ..
374 }) = field.expr.kind;
375 if sym.as_str() == "default lint description";
376
377 then {
378 span_lint(
379 cx,
380 DEFAULT_LINT,
381 item.span,
382 &format!("the lint `{}` has the default lint description", item.ident.name),
383 );
384 }
385 }
386 self.declared_lints.insert(item.ident.name, item.span);
387 }
388 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
389 || is_expn_of(item.span, "declare_lint_pass").is_some()
390 {
391 if let hir::ItemKind::Impl(hir::Impl {
392 of_trait: None,
393 items: impl_item_refs,
394 ..
395 }) = item.kind
396 {
397 let mut collector = LintCollector {
398 output: &mut self.registered_lints,
399 cx,
400 };
401 let body_id = cx.tcx.hir().body_owned_by(
402 impl_item_refs
403 .iter()
404 .find(|iiref| iiref.ident.as_str() == "get_lints")
405 .expect("LintPass needs to implement get_lints")
406 .id
407 .hir_id(),
408 );
409 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
410 }
411 }
412 }
413
414 fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
415 if is_lint_allowed(cx, LINT_WITHOUT_LINT_PASS, CRATE_HIR_ID) {
416 return;
417 }
418
419 for (lint_name, &lint_span) in &self.declared_lints {
420 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
421 // file points to "<rustc macros>".
422 // `compiletest-rs` thinks that's an error in a different file and
423 // just ignores it. This causes the test in compile-fail/lint_pass
424 // not able to capture the error.
425 // Therefore, we need to climb the macro expansion tree and find the
426 // actual span that invoked `declare_tool_lint!`:
427 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
428
429 if !self.registered_lints.contains(lint_name) {
430 span_lint(
431 cx,
432 LINT_WITHOUT_LINT_PASS,
433 lint_span,
434 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
435 );
436 }
437 }
438 }
439 }
440
441 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
442 if let TyKind::Rptr(
443 _,
444 MutTy {
445 ty: inner,
446 mutbl: Mutability::Not,
447 },
448 ) = ty.kind
449 {
450 if let TyKind::Path(ref path) = inner.kind {
451 if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
452 return match_def_path(cx, def_id, &paths::LINT);
453 }
454 }
455 }
456
457 false
458 }
459
460 struct LintCollector<'a, 'tcx> {
461 output: &'a mut FxHashSet<Symbol>,
462 cx: &'a LateContext<'tcx>,
463 }
464
465 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
466 type Map = Map<'tcx>;
467
468 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
469 if path.segments.len() == 1 {
470 self.output.insert(path.segments[0].ident.name);
471 }
472 }
473
474 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
475 NestedVisitorMap::All(self.cx.tcx.hir())
476 }
477 }
478
479 #[derive(Clone, Default)]
480 pub struct CompilerLintFunctions {
481 map: FxHashMap<&'static str, &'static str>,
482 }
483
484 impl CompilerLintFunctions {
485 #[must_use]
486 pub fn new() -> Self {
487 let mut map = FxHashMap::default();
488 map.insert("span_lint", "utils::span_lint");
489 map.insert("struct_span_lint", "utils::span_lint");
490 map.insert("lint", "utils::span_lint");
491 map.insert("span_lint_note", "utils::span_lint_and_note");
492 map.insert("span_lint_help", "utils::span_lint_and_help");
493 Self { map }
494 }
495 }
496
497 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
498
499 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
500 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
501 if is_lint_allowed(cx, COMPILER_LINT_FUNCTIONS, expr.hir_id) {
502 return;
503 }
504
505 if_chain! {
506 if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
507 let fn_name = path.ident;
508 if let Some(sugg) = self.map.get(&*fn_name.as_str());
509 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
510 if match_type(cx, ty, &paths::EARLY_CONTEXT)
511 || match_type(cx, ty, &paths::LATE_CONTEXT);
512 then {
513 span_lint_and_help(
514 cx,
515 COMPILER_LINT_FUNCTIONS,
516 path.ident.span,
517 "usage of a compiler lint function",
518 None,
519 &format!("please use the Clippy variant of this function: `{}`", sugg),
520 );
521 }
522 }
523 }
524 }
525
526 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
527
528 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
529 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
530 if is_lint_allowed(cx, OUTER_EXPN_EXPN_DATA, expr.hir_id) {
531 return;
532 }
533
534 let (method_names, arg_lists, spans) = method_calls(expr, 2);
535 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
536 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
537 if_chain! {
538 if let ["expn_data", "outer_expn"] = method_names.as_slice();
539 let args = arg_lists[1];
540 if args.len() == 1;
541 let self_arg = &args[0];
542 let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
543 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
544 then {
545 span_lint_and_sugg(
546 cx,
547 OUTER_EXPN_EXPN_DATA,
548 spans[1].with_hi(expr.span.hi()),
549 "usage of `outer_expn().expn_data()`",
550 "try",
551 "outer_expn_data()".to_string(),
552 Applicability::MachineApplicable,
553 );
554 }
555 }
556 }
557 }
558
559 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
560
561 impl EarlyLintPass for ProduceIce {
562 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
563 if is_trigger_fn(fn_kind) {
564 panic!("Would you like some help with that?");
565 }
566 }
567 }
568
569 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
570 match fn_kind {
571 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
572 FnKind::Closure(..) => false,
573 }
574 }
575
576 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
577
578 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
579 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
580 if is_lint_allowed(cx, COLLAPSIBLE_SPAN_LINT_CALLS, expr.hir_id) {
581 return;
582 }
583
584 if_chain! {
585 if let ExprKind::Call(func, and_then_args) = expr.kind;
586 if is_expr_path_def_path(cx, func, &["clippy_utils", "diagnostics", "span_lint_and_then"]);
587 if and_then_args.len() == 5;
588 if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
589 let body = cx.tcx.hir().body(*body_id);
590 if let ExprKind::Block(block, _) = &body.value.kind;
591 let stmts = &block.stmts;
592 if stmts.len() == 1 && block.expr.is_none();
593 if let StmtKind::Semi(only_expr) = &stmts[0].kind;
594 if let ExprKind::MethodCall(ps, _, span_call_args, _) = &only_expr.kind;
595 then {
596 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
597 let mut sle = SpanlessEq::new(cx).deny_side_effects();
598 match &*ps.ident.as_str() {
599 "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
600 suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
601 },
602 "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
603 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
604 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
605 },
606 "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
607 let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
608 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
609 },
610 "help" => {
611 let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
612 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
613 }
614 "note" => {
615 let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
616 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
617 }
618 _ => (),
619 }
620 }
621 }
622 }
623 }
624
625 struct AndThenSnippets<'a> {
626 cx: Cow<'a, str>,
627 lint: Cow<'a, str>,
628 span: Cow<'a, str>,
629 msg: Cow<'a, str>,
630 }
631
632 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
633 let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
634 let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
635 let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
636 let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
637
638 AndThenSnippets {
639 cx: cx_snippet,
640 lint: lint_snippet,
641 span: span_snippet,
642 msg: msg_snippet,
643 }
644 }
645
646 struct SpanSuggestionSnippets<'a> {
647 help: Cow<'a, str>,
648 sugg: Cow<'a, str>,
649 applicability: Cow<'a, str>,
650 }
651
652 fn span_suggestion_snippets<'a, 'hir>(
653 cx: &LateContext<'_>,
654 span_call_args: &'hir [Expr<'hir>],
655 ) -> SpanSuggestionSnippets<'a> {
656 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
657 let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
658 let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
659
660 SpanSuggestionSnippets {
661 help: help_snippet,
662 sugg: sugg_snippet,
663 applicability: applicability_snippet,
664 }
665 }
666
667 fn suggest_suggestion(
668 cx: &LateContext<'_>,
669 expr: &Expr<'_>,
670 and_then_snippets: &AndThenSnippets<'_>,
671 span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
672 ) {
673 span_lint_and_sugg(
674 cx,
675 COLLAPSIBLE_SPAN_LINT_CALLS,
676 expr.span,
677 "this call is collapsible",
678 "collapse into",
679 format!(
680 "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
681 and_then_snippets.cx,
682 and_then_snippets.lint,
683 and_then_snippets.span,
684 and_then_snippets.msg,
685 span_suggestion_snippets.help,
686 span_suggestion_snippets.sugg,
687 span_suggestion_snippets.applicability
688 ),
689 Applicability::MachineApplicable,
690 );
691 }
692
693 fn suggest_help(
694 cx: &LateContext<'_>,
695 expr: &Expr<'_>,
696 and_then_snippets: &AndThenSnippets<'_>,
697 help: &str,
698 with_span: bool,
699 ) {
700 let option_span = if with_span {
701 format!("Some({})", and_then_snippets.span)
702 } else {
703 "None".to_string()
704 };
705
706 span_lint_and_sugg(
707 cx,
708 COLLAPSIBLE_SPAN_LINT_CALLS,
709 expr.span,
710 "this call is collapsible",
711 "collapse into",
712 format!(
713 "span_lint_and_help({}, {}, {}, {}, {}, {})",
714 and_then_snippets.cx,
715 and_then_snippets.lint,
716 and_then_snippets.span,
717 and_then_snippets.msg,
718 &option_span,
719 help
720 ),
721 Applicability::MachineApplicable,
722 );
723 }
724
725 fn suggest_note(
726 cx: &LateContext<'_>,
727 expr: &Expr<'_>,
728 and_then_snippets: &AndThenSnippets<'_>,
729 note: &str,
730 with_span: bool,
731 ) {
732 let note_span = if with_span {
733 format!("Some({})", and_then_snippets.span)
734 } else {
735 "None".to_string()
736 };
737
738 span_lint_and_sugg(
739 cx,
740 COLLAPSIBLE_SPAN_LINT_CALLS,
741 expr.span,
742 "this call is collspible",
743 "collapse into",
744 format!(
745 "span_lint_and_note({}, {}, {}, {}, {}, {})",
746 and_then_snippets.cx,
747 and_then_snippets.lint,
748 and_then_snippets.span,
749 and_then_snippets.msg,
750 note_span,
751 note
752 ),
753 Applicability::MachineApplicable,
754 );
755 }
756
757 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
758
759 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
760 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
761 if is_lint_allowed(cx, MATCH_TYPE_ON_DIAGNOSTIC_ITEM, expr.hir_id) {
762 return;
763 }
764
765 if_chain! {
766 // Check if this is a call to utils::match_type()
767 if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
768 if is_expr_path_def_path(cx, fn_path, &["clippy_utils", "ty", "match_type"]);
769 // Extract the path to the matched type
770 if let Some(segments) = path_to_matched_type(cx, ty_path);
771 let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
772 if let Some(ty_did) = path_to_res(cx, &segments[..]).opt_def_id();
773 // Check if the matched type is a diagnostic item
774 let diag_items = cx.tcx.diagnostic_items(ty_did.krate);
775 if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None });
776 then {
777 // TODO: check paths constants from external crates.
778 let cx_snippet = snippet(cx, context.span, "_");
779 let ty_snippet = snippet(cx, ty.span, "_");
780
781 span_lint_and_sugg(
782 cx,
783 MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
784 expr.span,
785 "usage of `clippy_utils::ty::match_type()` on a type diagnostic item",
786 "try",
787 format!("clippy_utils::ty::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name),
788 Applicability::MaybeIncorrect,
789 );
790 }
791 }
792 }
793 }
794
795 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
796 use rustc_hir::ItemKind;
797
798 match &expr.kind {
799 ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
800 ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) {
801 Res::Local(hir_id) => {
802 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
803 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
804 if let Some(init) = local.init {
805 return path_to_matched_type(cx, init);
806 }
807 }
808 },
809 Res::Def(DefKind::Const | DefKind::Static, def_id) => {
810 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
811 if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
812 let body = cx.tcx.hir().body(body_id);
813 return path_to_matched_type(cx, &body.value);
814 }
815 }
816 },
817 _ => {},
818 },
819 ExprKind::Array(exprs) => {
820 let segments: Vec<SymbolStr> = exprs
821 .iter()
822 .filter_map(|expr| {
823 if let ExprKind::Lit(lit) = &expr.kind {
824 if let LitKind::Str(sym, _) = lit.node {
825 return Some(sym.as_str());
826 }
827 }
828
829 None
830 })
831 .collect();
832
833 if segments.len() == exprs.len() {
834 return Some(segments);
835 }
836 },
837 _ => {},
838 }
839
840 None
841 }
842
843 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
844 // module. That's all it does and all it needs to do.
845 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
846 if path_to_res(cx, path) != Res::Err {
847 return true;
848 }
849
850 // Some implementations can't be found by `path_to_res`, particularly inherent
851 // implementations of native types. Check lang items.
852 let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
853 let lang_items = cx.tcx.lang_items();
854 for item_def_id in lang_items.items().iter().flatten() {
855 let lang_item_path = cx.get_def_path(*item_def_id);
856 if path_syms.starts_with(&lang_item_path) {
857 if let [item] = &path_syms[lang_item_path.len()..] {
858 for child in cx.tcx.item_children(*item_def_id) {
859 if child.ident.name == *item {
860 return true;
861 }
862 }
863 }
864 }
865 }
866
867 false
868 }
869
870 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
871
872 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
873 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
874 let local_def_id = &cx.tcx.parent_module(item.hir_id());
875 let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
876 if_chain! {
877 if mod_name.as_str() == "paths";
878 if let hir::ItemKind::Const(ty, body_id) = item.kind;
879 let ty = hir_ty_to_ty(cx.tcx, ty);
880 if let ty::Array(el_ty, _) = &ty.kind();
881 if let ty::Ref(_, el_ty, _) = &el_ty.kind();
882 if el_ty.is_str();
883 let body = cx.tcx.hir().body(body_id);
884 let typeck_results = cx.tcx.typeck_body(body_id);
885 if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
886 let path: Vec<&str> = path.iter().map(|x| {
887 if let Constant::Str(s) = x {
888 s.as_str()
889 } else {
890 // We checked the type of the constant above
891 unreachable!()
892 }
893 }).collect();
894 if !check_path(cx, &path[..]);
895 then {
896 span_lint(cx, CLIPPY_LINTS_INTERNAL, item.span, "invalid path");
897 }
898 }
899 }
900 }
901
902 #[derive(Default)]
903 pub struct InterningDefinedSymbol {
904 // Maps the symbol value to the constant DefId.
905 symbol_map: FxHashMap<u32, DefId>,
906 }
907
908 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
909
910 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
911 fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
912 if !self.symbol_map.is_empty() {
913 return;
914 }
915
916 for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
917 if let Some(def_id) = path_to_res(cx, module).opt_def_id() {
918 for item in cx.tcx.item_children(def_id).iter() {
919 if_chain! {
920 if let Res::Def(DefKind::Const, item_def_id) = item.res;
921 let ty = cx.tcx.type_of(item_def_id);
922 if match_type(cx, ty, &paths::SYMBOL);
923 if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
924 if let Ok(value) = value.to_u32();
925 then {
926 self.symbol_map.insert(value, item_def_id);
927 }
928 }
929 }
930 }
931 }
932 }
933
934 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
935 if_chain! {
936 if let ExprKind::Call(func, [arg]) = &expr.kind;
937 if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
938 if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
939 if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
940 let value = Symbol::intern(&arg).as_u32();
941 if let Some(&def_id) = self.symbol_map.get(&value);
942 then {
943 span_lint_and_sugg(
944 cx,
945 INTERNING_DEFINED_SYMBOL,
946 is_expn_of(expr.span, "sym").unwrap_or(expr.span),
947 "interning a defined symbol",
948 "try",
949 cx.tcx.def_path_str(def_id),
950 Applicability::MachineApplicable,
951 );
952 }
953 }
954 if let ExprKind::Binary(op, left, right) = expr.kind {
955 if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
956 let data = [
957 (left, self.symbol_str_expr(left, cx)),
958 (right, self.symbol_str_expr(right, cx)),
959 ];
960 match data {
961 // both operands are a symbol string
962 [(_, Some(left)), (_, Some(right))] => {
963 span_lint_and_sugg(
964 cx,
965 UNNECESSARY_SYMBOL_STR,
966 expr.span,
967 "unnecessary `Symbol` to string conversion",
968 "try",
969 format!(
970 "{} {} {}",
971 left.as_symbol_snippet(cx),
972 op.node.as_str(),
973 right.as_symbol_snippet(cx),
974 ),
975 Applicability::MachineApplicable,
976 );
977 },
978 // one of the operands is a symbol string
979 [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
980 // creating an owned string for comparison
981 if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
982 span_lint_and_sugg(
983 cx,
984 UNNECESSARY_SYMBOL_STR,
985 expr.span,
986 "unnecessary string allocation",
987 "try",
988 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
989 Applicability::MachineApplicable,
990 );
991 }
992 },
993 // nothing found
994 [(_, None), (_, None)] => {},
995 }
996 }
997 }
998 }
999 }
1000
1001 impl InterningDefinedSymbol {
1002 fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
1003 static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
1004 static SYMBOL_STR_PATHS: &[&[&str]] = &[
1005 &paths::SYMBOL_AS_STR,
1006 &paths::SYMBOL_TO_IDENT_STRING,
1007 &paths::TO_STRING_METHOD,
1008 ];
1009 // SymbolStr might be de-referenced: `&*symbol.as_str()`
1010 let call = if_chain! {
1011 if let ExprKind::AddrOf(_, _, e) = expr.kind;
1012 if let ExprKind::Unary(UnOp::Deref, e) = e.kind;
1013 then { e } else { expr }
1014 };
1015 if_chain! {
1016 // is a method call
1017 if let ExprKind::MethodCall(_, _, [item], _) = call.kind;
1018 if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1019 let ty = cx.typeck_results().expr_ty(item);
1020 // ...on either an Ident or a Symbol
1021 if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1022 Some(false)
1023 } else if match_type(cx, ty, &paths::IDENT) {
1024 Some(true)
1025 } else {
1026 None
1027 };
1028 // ...which converts it to a string
1029 let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1030 if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1031 then {
1032 let is_to_owned = path.last().unwrap().ends_with("string");
1033 return Some(SymbolStrExpr::Expr {
1034 item,
1035 is_ident,
1036 is_to_owned,
1037 });
1038 }
1039 }
1040 // is a string constant
1041 if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1042 let value = Symbol::intern(&s).as_u32();
1043 // ...which matches a symbol constant
1044 if let Some(&def_id) = self.symbol_map.get(&value) {
1045 return Some(SymbolStrExpr::Const(def_id));
1046 }
1047 }
1048 None
1049 }
1050 }
1051
1052 enum SymbolStrExpr<'tcx> {
1053 /// a string constant with a corresponding symbol constant
1054 Const(DefId),
1055 /// a "symbol to string" expression like `symbol.as_str()`
1056 Expr {
1057 /// part that evaluates to `Symbol` or `Ident`
1058 item: &'tcx Expr<'tcx>,
1059 is_ident: bool,
1060 /// whether an owned `String` is created like `to_ident_string()`
1061 is_to_owned: bool,
1062 },
1063 }
1064
1065 impl<'tcx> SymbolStrExpr<'tcx> {
1066 /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1067 fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1068 match *self {
1069 Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1070 Self::Expr { item, is_ident, .. } => {
1071 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1072 if is_ident {
1073 // get `Ident.name`
1074 snip.to_mut().push_str(".name");
1075 }
1076 snip
1077 },
1078 }
1079 }
1080 }
1081
1082 declare_lint_pass!(IfChainStyle => [IF_CHAIN_STYLE]);
1083
1084 impl<'tcx> LateLintPass<'tcx> for IfChainStyle {
1085 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
1086 let (local, after, if_chain_span) = if_chain! {
1087 if let [Stmt { kind: StmtKind::Local(local), .. }, after @ ..] = block.stmts;
1088 if let Some(if_chain_span) = is_expn_of(block.span, "if_chain");
1089 then { (local, after, if_chain_span) } else { return }
1090 };
1091 if is_first_if_chain_expr(cx, block.hir_id, if_chain_span) {
1092 span_lint(
1093 cx,
1094 IF_CHAIN_STYLE,
1095 if_chain_local_span(cx, local, if_chain_span),
1096 "`let` expression should be above the `if_chain!`",
1097 );
1098 } else if local.span.ctxt() == block.span.ctxt() && is_if_chain_then(after, block.expr, if_chain_span) {
1099 span_lint(
1100 cx,
1101 IF_CHAIN_STYLE,
1102 if_chain_local_span(cx, local, if_chain_span),
1103 "`let` expression should be inside `then { .. }`",
1104 );
1105 }
1106 }
1107
1108 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1109 let (cond, then, els) = match expr.kind {
1110 ExprKind::If(cond, then, els) => (Some(cond), then, els.is_some()),
1111 ExprKind::Match(
1112 _,
1113 [arm, ..],
1114 MatchSource::IfLetDesugar {
1115 contains_else_clause: els,
1116 },
1117 ) => (None, arm.body, els),
1118 _ => return,
1119 };
1120 let then_block = match then.kind {
1121 ExprKind::Block(block, _) => block,
1122 _ => return,
1123 };
1124 let if_chain_span = is_expn_of(expr.span, "if_chain");
1125 if !els {
1126 check_nested_if_chains(cx, expr, then_block, if_chain_span);
1127 }
1128 let if_chain_span = match if_chain_span {
1129 None => return,
1130 Some(span) => span,
1131 };
1132 // check for `if a && b;`
1133 if_chain! {
1134 if let Some(cond) = cond;
1135 if let ExprKind::Binary(op, _, _) = cond.kind;
1136 if op.node == BinOpKind::And;
1137 if cx.sess().source_map().is_multiline(cond.span);
1138 then {
1139 span_lint(cx, IF_CHAIN_STYLE, cond.span, "`if a && b;` should be `if a; if b;`");
1140 }
1141 }
1142 if is_first_if_chain_expr(cx, expr.hir_id, if_chain_span)
1143 && is_if_chain_then(then_block.stmts, then_block.expr, if_chain_span)
1144 {
1145 span_lint(cx, IF_CHAIN_STYLE, expr.span, "`if_chain!` only has one `if`");
1146 }
1147 }
1148 }
1149
1150 fn check_nested_if_chains(
1151 cx: &LateContext<'_>,
1152 if_expr: &Expr<'_>,
1153 then_block: &Block<'_>,
1154 if_chain_span: Option<Span>,
1155 ) {
1156 #[rustfmt::skip]
1157 let (head, tail) = match *then_block {
1158 Block { stmts, expr: Some(tail), .. } => (stmts, tail),
1159 Block {
1160 stmts: &[
1161 ref head @ ..,
1162 Stmt { kind: StmtKind::Expr(tail) | StmtKind::Semi(tail), .. }
1163 ],
1164 ..
1165 } => (head, tail),
1166 _ => return,
1167 };
1168 if_chain! {
1169 if matches!(tail.kind,
1170 ExprKind::If(_, _, None)
1171 | ExprKind::Match(.., MatchSource::IfLetDesugar { contains_else_clause: false }));
1172 let sm = cx.sess().source_map();
1173 if head
1174 .iter()
1175 .all(|stmt| matches!(stmt.kind, StmtKind::Local(..)) && !sm.is_multiline(stmt.span));
1176 if if_chain_span.is_some() || !is_else_clause(cx.tcx, if_expr);
1177 then {} else { return }
1178 }
1179 let (span, msg) = match (if_chain_span, is_expn_of(tail.span, "if_chain")) {
1180 (None, Some(_)) => (if_expr.span, "this `if` can be part of the inner `if_chain!`"),
1181 (Some(_), None) => (tail.span, "this `if` can be part of the outer `if_chain!`"),
1182 (Some(a), Some(b)) if a != b => (b, "this `if_chain!` can be merged with the outer `if_chain!`"),
1183 _ => return,
1184 };
1185 span_lint_and_then(cx, IF_CHAIN_STYLE, span, msg, |diag| {
1186 let (span, msg) = match head {
1187 [] => return,
1188 [stmt] => (stmt.span, "this `let` statement can also be in the `if_chain!`"),
1189 [a, .., b] => (
1190 a.span.to(b.span),
1191 "these `let` statements can also be in the `if_chain!`",
1192 ),
1193 };
1194 diag.span_help(span, msg);
1195 });
1196 }
1197
1198 fn is_first_if_chain_expr(cx: &LateContext<'_>, hir_id: HirId, if_chain_span: Span) -> bool {
1199 cx.tcx
1200 .hir()
1201 .parent_iter(hir_id)
1202 .find(|(_, node)| {
1203 #[rustfmt::skip]
1204 !matches!(node, Node::Expr(Expr { kind: ExprKind::Block(..), .. }) | Node::Stmt(_))
1205 })
1206 .map_or(false, |(id, _)| {
1207 is_expn_of(cx.tcx.hir().span(id), "if_chain") != Some(if_chain_span)
1208 })
1209 }
1210
1211 /// Checks a trailing slice of statements and expression of a `Block` to see if they are part
1212 /// of the `then {..}` portion of an `if_chain!`
1213 fn is_if_chain_then(stmts: &[Stmt<'_>], expr: Option<&Expr<'_>>, if_chain_span: Span) -> bool {
1214 let span = if let [stmt, ..] = stmts {
1215 stmt.span
1216 } else if let Some(expr) = expr {
1217 expr.span
1218 } else {
1219 // empty `then {}`
1220 return true;
1221 };
1222 is_expn_of(span, "if_chain").map_or(true, |span| span != if_chain_span)
1223 }
1224
1225 /// Creates a `Span` for `let x = ..;` in an `if_chain!` call.
1226 fn if_chain_local_span(cx: &LateContext<'_>, local: &Local<'_>, if_chain_span: Span) -> Span {
1227 let mut span = local.pat.span;
1228 if let Some(init) = local.init {
1229 span = span.to(init.span);
1230 }
1231 span.adjust(if_chain_span.ctxt().outer_expn());
1232 let sm = cx.sess().source_map();
1233 let span = sm.span_extend_to_prev_str(span, "let", false);
1234 let span = sm.span_extend_to_next_char(span, ';', false);
1235 Span::new(span.lo() - BytePos(3), span.hi() + BytePos(1), span.ctxt())
1236 }