2 is_expn_of, match_def_path, match_type, method_calls, paths, span_help_and_lint, span_lint, span_lint_and_sugg,
5 use if_chain::if_chain;
7 use rustc::hir::def::{DefKind, Res};
8 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
10 use rustc::lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray, LintPass};
11 use rustc::{declare_lint_pass, impl_lint_pass};
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_errors::Applicability;
14 use rustc_session::declare_tool_lint;
16 use syntax::ast::{Crate as AstCrate, ItemKind, Name};
17 use syntax::source_map::Span;
18 use syntax::visit::FnKind;
19 use syntax_pos::symbol::SymbolStr;
21 declare_clippy_lint! {
22 /// **What it does:** Checks for various things we like to keep tidy in clippy.
24 /// **Why is this bad?** We like to pretend we're an example of tidy code.
26 /// **Known problems:** None.
28 /// **Example:** Wrong ordering of the util::paths constants.
29 pub CLIPPY_LINTS_INTERNAL,
31 "various things that will negatively affect your clippy experience"
34 declare_clippy_lint! {
35 /// **What it does:** Ensures every lint is associated to a `LintPass`.
37 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
38 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
39 /// know the name of the lint.
41 /// **Known problems:** Only checks for lints associated using the
42 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
46 /// declare_lint! { pub LINT_1, ... }
47 /// declare_lint! { pub LINT_2, ... }
48 /// declare_lint! { pub FORGOTTEN_LINT, ... }
50 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
51 /// // missing FORGOTTEN_LINT
53 pub LINT_WITHOUT_LINT_PASS,
55 "declaring a lint without associating it in a LintPass"
58 declare_clippy_lint! {
59 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
60 /// variant of the function.
62 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
63 /// warning/error messages.
65 /// **Known problems:** None.
70 /// cx.span_lint(LINT_NAME, "message");
75 /// utils::span_lint(cx, LINT_NAME, "message");
77 pub COMPILER_LINT_FUNCTIONS,
79 "usage of the lint functions of the compiler instead of the utils::* variant"
82 declare_clippy_lint! {
83 /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
84 /// the `cx.outer_expn_data()`
86 /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
88 /// **Known problems:** None.
93 /// expr.span.ctxt().outer().expn_data()
98 /// expr.span.ctxt().outer_expn_data()
100 pub OUTER_EXPN_EXPN_DATA,
102 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
105 declare_clippy_lint! {
106 /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
107 /// error message by calling `panic`.
109 /// **Why is this bad?** ICE in large quantities can damage your teeth
111 /// **Known problems:** None
120 "this message should not appear anywhere as we ICE before and don't emit the lint"
123 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
125 impl EarlyLintPass for ClippyLintsInternal {
126 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
127 if let Some(utils) = krate
131 .find(|item| item.ident.name.as_str() == "utils")
133 if let ItemKind::Mod(ref utils_mod) = utils.kind {
134 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
135 if let ItemKind::Mod(ref paths_mod) = paths.kind {
136 let mut last_name: Option<SymbolStr> = None;
137 for item in &*paths_mod.items {
138 let name = item.ident.as_str();
139 if let Some(ref last_name) = last_name {
140 if **last_name > *name {
143 CLIPPY_LINTS_INTERNAL,
145 "this constant should be before the previous constant due to lexical \
150 last_name = Some(name);
159 #[derive(Clone, Debug, Default)]
160 pub struct LintWithoutLintPass {
161 declared_lints: FxHashMap<Name, Span>,
162 registered_lints: FxHashSet<Name>,
165 impl_lint_pass!(LintWithoutLintPass => [LINT_WITHOUT_LINT_PASS]);
167 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
168 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
169 if let hir::ItemKind::Static(ref ty, Mutability::Not, _) = item.kind {
170 if is_lint_ref_type(cx, ty) {
171 self.declared_lints.insert(item.ident.name, item.span);
173 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
174 || is_expn_of(item.span, "declare_lint_pass").is_some()
176 if let hir::ItemKind::Impl(.., None, _, ref impl_item_refs) = item.kind {
177 let mut collector = LintCollector {
178 output: &mut self.registered_lints,
181 let body_id = cx.tcx.hir().body_owned_by(
184 .find(|iiref| iiref.ident.as_str() == "get_lints")
185 .expect("LintPass needs to implement get_lints")
189 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
194 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate<'_>) {
195 for (lint_name, &lint_span) in &self.declared_lints {
196 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
197 // file points to "<rustc macros>".
198 // `compiletest-rs` thinks that's an error in a different file and
199 // just ignores it. This causes the test in compile-fail/lint_pass
200 // not able to capture the error.
201 // Therefore, we need to climb the macro expansion tree and find the
202 // actual span that invoked `declare_tool_lint!`:
203 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
205 if !self.registered_lints.contains(lint_name) {
208 LINT_WITHOUT_LINT_PASS,
210 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
217 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
222 mutbl: Mutability::Not,
226 if let TyKind::Path(ref path) = inner.kind {
227 if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
228 return match_def_path(cx, def_id, &paths::LINT);
236 struct LintCollector<'a, 'tcx> {
237 output: &'a mut FxHashSet<Name>,
238 cx: &'a LateContext<'a, 'tcx>,
241 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
242 fn visit_expr(&mut self, expr: &'tcx Expr) {
243 walk_expr(self, expr);
246 fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
247 if path.segments.len() == 1 {
248 self.output.insert(path.segments[0].ident.name);
251 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
252 NestedVisitorMap::All(&self.cx.tcx.hir())
256 #[derive(Clone, Default)]
257 pub struct CompilerLintFunctions {
258 map: FxHashMap<&'static str, &'static str>,
261 impl CompilerLintFunctions {
263 pub fn new() -> Self {
264 let mut map = FxHashMap::default();
265 map.insert("span_lint", "utils::span_lint");
266 map.insert("struct_span_lint", "utils::span_lint");
267 map.insert("lint", "utils::span_lint");
268 map.insert("span_lint_note", "utils::span_note_and_lint");
269 map.insert("span_lint_help", "utils::span_help_and_lint");
274 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
276 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
277 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
279 if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind;
280 let fn_name = path.ident;
281 if let Some(sugg) = self.map.get(&*fn_name.as_str());
282 let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
283 if match_type(cx, ty, &paths::EARLY_CONTEXT)
284 || match_type(cx, ty, &paths::LATE_CONTEXT);
288 COMPILER_LINT_FUNCTIONS,
290 "usage of a compiler lint function",
291 &format!("please use the Clippy variant of this function: `{}`", sugg),
298 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
300 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OuterExpnDataPass {
301 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
302 let (method_names, arg_lists, spans) = method_calls(expr, 2);
303 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
304 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
306 if let ["expn_data", "outer_expn"] = method_names.as_slice();
307 let args = arg_lists[1];
309 let self_arg = &args[0];
310 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(self_arg));
311 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
315 OUTER_EXPN_EXPN_DATA,
316 spans[1].with_hi(expr.span.hi()),
317 "usage of `outer_expn().expn_data()`",
319 "outer_expn_data()".to_string(),
320 Applicability::MachineApplicable,
327 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
329 impl EarlyLintPass for ProduceIce {
330 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
331 if is_trigger_fn(fn_kind) {
332 panic!("Testing the ICE message");
337 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
339 FnKind::ItemFn(ident, ..) | FnKind::Method(ident, ..) => {
340 ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy"
342 FnKind::Closure(..) => false,