2 is_expn_of, match_def_path, match_type, method_calls, paths, span_lint, span_lint_and_help, span_lint_and_sugg,
5 use if_chain::if_chain;
6 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, Name, NodeId};
7 use rustc_ast::visit::FnKind;
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_errors::Applicability;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
13 use rustc_hir::{Crate, Expr, ExprKind, HirId, Item, MutTy, Mutability, Path, Ty, TyKind};
14 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
15 use rustc_middle::hir::map::Map;
16 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
17 use rustc_span::source_map::{Span, Spanned};
18 use rustc_span::symbol::SymbolStr;
20 declare_clippy_lint! {
21 /// **What it does:** Checks for various things we like to keep tidy in clippy.
23 /// **Why is this bad?** We like to pretend we're an example of tidy code.
25 /// **Known problems:** None.
27 /// **Example:** Wrong ordering of the util::paths constants.
28 pub CLIPPY_LINTS_INTERNAL,
30 "various things that will negatively affect your clippy experience"
33 declare_clippy_lint! {
34 /// **What it does:** Ensures every lint is associated to a `LintPass`.
36 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
37 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
38 /// know the name of the lint.
40 /// **Known problems:** Only checks for lints associated using the
41 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
45 /// declare_lint! { pub LINT_1, ... }
46 /// declare_lint! { pub LINT_2, ... }
47 /// declare_lint! { pub FORGOTTEN_LINT, ... }
49 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
50 /// // missing FORGOTTEN_LINT
52 pub LINT_WITHOUT_LINT_PASS,
54 "declaring a lint without associating it in a LintPass"
57 declare_clippy_lint! {
58 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
59 /// variant of the function.
61 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
62 /// warning/error messages.
64 /// **Known problems:** None.
69 /// cx.span_lint(LINT_NAME, "message");
74 /// utils::span_lint(cx, LINT_NAME, "message");
76 pub COMPILER_LINT_FUNCTIONS,
78 "usage of the lint functions of the compiler instead of the utils::* variant"
81 declare_clippy_lint! {
82 /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
83 /// the `cx.outer_expn_data()`
85 /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
87 /// **Known problems:** None.
92 /// expr.span.ctxt().outer().expn_data()
97 /// expr.span.ctxt().outer_expn_data()
99 pub OUTER_EXPN_EXPN_DATA,
101 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
104 declare_clippy_lint! {
105 /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
106 /// error message by calling `panic`.
108 /// **Why is this bad?** ICE in large quantities can damage your teeth
110 /// **Known problems:** None
119 "this message should not appear anywhere as we ICE before and don't emit the lint"
122 declare_clippy_lint! {
123 /// **What it does:** Checks for cases of an auto-generated lint without an updated description,
124 /// i.e. `default lint description`.
126 /// **Why is this bad?** Indicates that the lint is not finished.
128 /// **Known problems:** None
133 /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
138 /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
142 "found 'default lint description' in a lint declaration"
145 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
147 impl EarlyLintPass for ClippyLintsInternal {
148 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
149 if let Some(utils) = krate
153 .find(|item| item.ident.name.as_str() == "utils")
155 if let ItemKind::Mod(ref utils_mod) = utils.kind {
156 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
157 if let ItemKind::Mod(ref paths_mod) = paths.kind {
158 let mut last_name: Option<SymbolStr> = None;
159 for item in &*paths_mod.items {
160 let name = item.ident.as_str();
161 if let Some(ref last_name) = last_name {
162 if **last_name > *name {
165 CLIPPY_LINTS_INTERNAL,
167 "this constant should be before the previous constant due to lexical \
172 last_name = Some(name);
181 #[derive(Clone, Debug, Default)]
182 pub struct LintWithoutLintPass {
183 declared_lints: FxHashMap<Name, Span>,
184 registered_lints: FxHashSet<Name>,
187 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
189 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
190 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
191 if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
192 if is_lint_ref_type(cx, ty) {
193 let expr = &cx.tcx.hir().body(body_id).value;
195 if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
196 if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
197 let field = fields.iter()
198 .find(|f| f.ident.as_str() == "desc")
199 .expect("lints must have a description field");
200 if let ExprKind::Lit(Spanned {
201 node: LitKind::Str(ref sym, _),
203 }) = field.expr.kind;
204 if sym.as_str() == "default lint description";
211 &format!("the lint `{}` has the default lint description", item.ident.name),
215 self.declared_lints.insert(item.ident.name, item.span);
217 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
218 || is_expn_of(item.span, "declare_lint_pass").is_some()
220 if let hir::ItemKind::Impl {
222 items: ref impl_item_refs,
226 let mut collector = LintCollector {
227 output: &mut self.registered_lints,
230 let body_id = cx.tcx.hir().body_owned_by(
233 .find(|iiref| iiref.ident.as_str() == "get_lints")
234 .expect("LintPass needs to implement get_lints")
238 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
243 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate<'_>) {
244 for (lint_name, &lint_span) in &self.declared_lints {
245 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
246 // file points to "<rustc macros>".
247 // `compiletest-rs` thinks that's an error in a different file and
248 // just ignores it. This causes the test in compile-fail/lint_pass
249 // not able to capture the error.
250 // Therefore, we need to climb the macro expansion tree and find the
251 // actual span that invoked `declare_tool_lint!`:
252 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
254 if !self.registered_lints.contains(lint_name) {
257 LINT_WITHOUT_LINT_PASS,
259 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
266 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty<'_>) -> bool {
271 mutbl: Mutability::Not,
275 if let TyKind::Path(ref path) = inner.kind {
276 if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
277 return match_def_path(cx, def_id, &paths::LINT);
285 struct LintCollector<'a, 'tcx> {
286 output: &'a mut FxHashSet<Name>,
287 cx: &'a LateContext<'a, 'tcx>,
290 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
291 type Map = Map<'tcx>;
293 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
294 walk_expr(self, expr);
297 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
298 if path.segments.len() == 1 {
299 self.output.insert(path.segments[0].ident.name);
302 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
303 NestedVisitorMap::All(self.cx.tcx.hir())
307 #[derive(Clone, Default)]
308 pub struct CompilerLintFunctions {
309 map: FxHashMap<&'static str, &'static str>,
312 impl CompilerLintFunctions {
314 pub fn new() -> Self {
315 let mut map = FxHashMap::default();
316 map.insert("span_lint", "utils::span_lint");
317 map.insert("struct_span_lint", "utils::span_lint");
318 map.insert("lint", "utils::span_lint");
319 map.insert("span_lint_note", "utils::span_lint_and_note");
320 map.insert("span_lint_help", "utils::span_lint_and_help");
325 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
327 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
328 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
330 if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind;
331 let fn_name = path.ident;
332 if let Some(sugg) = self.map.get(&*fn_name.as_str());
333 let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
334 if match_type(cx, ty, &paths::EARLY_CONTEXT)
335 || match_type(cx, ty, &paths::LATE_CONTEXT);
339 COMPILER_LINT_FUNCTIONS,
341 "usage of a compiler lint function",
342 &format!("please use the Clippy variant of this function: `{}`", sugg),
349 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
351 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OuterExpnDataPass {
352 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
353 let (method_names, arg_lists, spans) = method_calls(expr, 2);
354 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
355 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
357 if let ["expn_data", "outer_expn"] = method_names.as_slice();
358 let args = arg_lists[1];
360 let self_arg = &args[0];
361 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(self_arg));
362 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
366 OUTER_EXPN_EXPN_DATA,
367 spans[1].with_hi(expr.span.hi()),
368 "usage of `outer_expn().expn_data()`",
370 "outer_expn_data()".to_string(),
371 Applicability::MachineApplicable,
378 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
380 impl EarlyLintPass for ProduceIce {
381 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
382 if is_trigger_fn(fn_kind) {
383 panic!("Would you like some help with that?");
388 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
390 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
391 FnKind::Closure(..) => false,