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::hir::map::Map;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_errors::Applicability;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
13 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
14 use rustc_session::declare_tool_lint;
15 use rustc_session::{declare_lint_pass, impl_lint_pass};
16 use rustc_span::source_map::{Span, Spanned};
17 use rustc_span::symbol::SymbolStr;
19 use syntax::ast::{Crate as AstCrate, ItemKind, LitKind, Name};
20 use syntax::visit::FnKind;
22 declare_clippy_lint! {
23 /// **What it does:** Checks for various things we like to keep tidy in clippy.
25 /// **Why is this bad?** We like to pretend we're an example of tidy code.
27 /// **Known problems:** None.
29 /// **Example:** Wrong ordering of the util::paths constants.
30 pub CLIPPY_LINTS_INTERNAL,
32 "various things that will negatively affect your clippy experience"
35 declare_clippy_lint! {
36 /// **What it does:** Ensures every lint is associated to a `LintPass`.
38 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
39 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
40 /// know the name of the lint.
42 /// **Known problems:** Only checks for lints associated using the
43 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
47 /// declare_lint! { pub LINT_1, ... }
48 /// declare_lint! { pub LINT_2, ... }
49 /// declare_lint! { pub FORGOTTEN_LINT, ... }
51 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
52 /// // missing FORGOTTEN_LINT
54 pub LINT_WITHOUT_LINT_PASS,
56 "declaring a lint without associating it in a LintPass"
59 declare_clippy_lint! {
60 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
61 /// variant of the function.
63 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
64 /// warning/error messages.
66 /// **Known problems:** None.
71 /// cx.span_lint(LINT_NAME, "message");
76 /// utils::span_lint(cx, LINT_NAME, "message");
78 pub COMPILER_LINT_FUNCTIONS,
80 "usage of the lint functions of the compiler instead of the utils::* variant"
83 declare_clippy_lint! {
84 /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
85 /// the `cx.outer_expn_data()`
87 /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
89 /// **Known problems:** None.
94 /// expr.span.ctxt().outer().expn_data()
99 /// expr.span.ctxt().outer_expn_data()
101 pub OUTER_EXPN_EXPN_DATA,
103 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
106 declare_clippy_lint! {
107 /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
108 /// error message by calling `panic`.
110 /// **Why is this bad?** ICE in large quantities can damage your teeth
112 /// **Known problems:** None
121 "this message should not appear anywhere as we ICE before and don't emit the lint"
124 declare_clippy_lint! {
125 /// **What it does:** Checks for cases of an auto-generated lint without an updated description,
126 /// i.e. `default lint description`.
128 /// **Why is this bad?** Indicates that the lint is not finished.
130 /// **Known problems:** None
135 /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
140 /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
144 "found 'default lint description' in a lint declaration"
147 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
149 impl EarlyLintPass for ClippyLintsInternal {
150 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
151 if let Some(utils) = krate
155 .find(|item| item.ident.name.as_str() == "utils")
157 if let ItemKind::Mod(ref utils_mod) = utils.kind {
158 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
159 if let ItemKind::Mod(ref paths_mod) = paths.kind {
160 let mut last_name: Option<SymbolStr> = None;
161 for item in &*paths_mod.items {
162 let name = item.ident.as_str();
163 if let Some(ref last_name) = last_name {
164 if **last_name > *name {
167 CLIPPY_LINTS_INTERNAL,
169 "this constant should be before the previous constant due to lexical \
174 last_name = Some(name);
183 #[derive(Clone, Debug, Default)]
184 pub struct LintWithoutLintPass {
185 declared_lints: FxHashMap<Name, Span>,
186 registered_lints: FxHashSet<Name>,
189 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
191 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
192 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
193 if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
194 if is_lint_ref_type(cx, ty) {
195 let expr = &cx.tcx.hir().body(body_id).value;
197 if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
198 if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
199 let field = fields.iter()
200 .find(|f| f.ident.as_str() == "desc")
201 .expect("lints must have a description field");
202 if let ExprKind::Lit(Spanned {
203 node: LitKind::Str(ref sym, _),
205 }) = field.expr.kind;
206 if sym.as_str() == "default lint description";
213 &format!("the lint `{}` has the default lint description", item.ident.name),
217 self.declared_lints.insert(item.ident.name, item.span);
219 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
220 || is_expn_of(item.span, "declare_lint_pass").is_some()
222 if let hir::ItemKind::Impl {
224 items: ref impl_item_refs,
228 let mut collector = LintCollector {
229 output: &mut self.registered_lints,
232 let body_id = cx.tcx.hir().body_owned_by(
235 .find(|iiref| iiref.ident.as_str() == "get_lints")
236 .expect("LintPass needs to implement get_lints")
240 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
245 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate<'_>) {
246 for (lint_name, &lint_span) in &self.declared_lints {
247 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
248 // file points to "<rustc macros>".
249 // `compiletest-rs` thinks that's an error in a different file and
250 // just ignores it. This causes the test in compile-fail/lint_pass
251 // not able to capture the error.
252 // Therefore, we need to climb the macro expansion tree and find the
253 // actual span that invoked `declare_tool_lint!`:
254 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
256 if !self.registered_lints.contains(lint_name) {
259 LINT_WITHOUT_LINT_PASS,
261 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
268 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty<'_>) -> bool {
273 mutbl: Mutability::Not,
277 if let TyKind::Path(ref path) = inner.kind {
278 if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
279 return match_def_path(cx, def_id, &paths::LINT);
287 struct LintCollector<'a, 'tcx> {
288 output: &'a mut FxHashSet<Name>,
289 cx: &'a LateContext<'a, 'tcx>,
292 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
293 type Map = Map<'tcx>;
295 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
296 walk_expr(self, expr);
299 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
300 if path.segments.len() == 1 {
301 self.output.insert(path.segments[0].ident.name);
304 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
305 NestedVisitorMap::All(&self.cx.tcx.hir())
309 #[derive(Clone, Default)]
310 pub struct CompilerLintFunctions {
311 map: FxHashMap<&'static str, &'static str>,
314 impl CompilerLintFunctions {
316 pub fn new() -> Self {
317 let mut map = FxHashMap::default();
318 map.insert("span_lint", "utils::span_lint");
319 map.insert("struct_span_lint", "utils::span_lint");
320 map.insert("lint", "utils::span_lint");
321 map.insert("span_lint_note", "utils::span_lint_and_note");
322 map.insert("span_lint_help", "utils::span_lint_and_help");
327 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
329 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
330 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
332 if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind;
333 let fn_name = path.ident;
334 if let Some(sugg) = self.map.get(&*fn_name.as_str());
335 let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
336 if match_type(cx, ty, &paths::EARLY_CONTEXT)
337 || match_type(cx, ty, &paths::LATE_CONTEXT);
341 COMPILER_LINT_FUNCTIONS,
343 "usage of a compiler lint function",
344 &format!("please use the Clippy variant of this function: `{}`", sugg),
351 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
353 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OuterExpnDataPass {
354 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
355 let (method_names, arg_lists, spans) = method_calls(expr, 2);
356 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
357 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
359 if let ["expn_data", "outer_expn"] = method_names.as_slice();
360 let args = arg_lists[1];
362 let self_arg = &args[0];
363 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(self_arg));
364 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
368 OUTER_EXPN_EXPN_DATA,
369 spans[1].with_hi(expr.span.hi()),
370 "usage of `outer_expn().expn_data()`",
372 "outer_expn_data()".to_string(),
373 Applicability::MachineApplicable,
380 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
382 impl EarlyLintPass for ProduceIce {
383 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
384 if is_trigger_fn(fn_kind) {
385 panic!("Testing the ICE message");
390 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
392 FnKind::ItemFn(ident, ..) | FnKind::Method(ident, ..) => {
393 ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy"
395 FnKind::Closure(..) => false,