2 match_def_path, match_type, method_calls, paths, span_help_and_lint, span_lint, span_lint_and_sugg, walk_ptrs_ty,
4 use if_chain::if_chain;
6 use rustc::hir::def::{DefKind, Res};
7 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
9 use rustc::lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_errors::Applicability;
13 use syntax::ast::{Crate as AstCrate, ItemKind, Name};
14 use syntax::source_map::Span;
15 use syntax_pos::symbol::LocalInternedString;
17 declare_clippy_lint! {
18 /// **What it does:** Checks for various things we like to keep tidy in clippy.
20 /// **Why is this bad?** We like to pretend we're an example of tidy code.
22 /// **Known problems:** None.
24 /// **Example:** Wrong ordering of the util::paths constants.
25 pub CLIPPY_LINTS_INTERNAL,
27 "various things that will negatively affect your clippy experience"
30 declare_clippy_lint! {
31 /// **What it does:** Ensures every lint is associated to a `LintPass`.
33 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
34 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
35 /// know the name of the lint.
37 /// **Known problems:** Only checks for lints associated using the
38 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
42 /// declare_lint! { pub LINT_1, ... }
43 /// declare_lint! { pub LINT_2, ... }
44 /// declare_lint! { pub FORGOTTEN_LINT, ... }
46 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
47 /// // missing FORGOTTEN_LINT
49 pub LINT_WITHOUT_LINT_PASS,
51 "declaring a lint without associating it in a LintPass"
54 declare_clippy_lint! {
55 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
56 /// variant of the function.
58 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
59 /// warning/error messages.
61 /// **Known problems:** None.
66 /// cx.span_lint(LINT_NAME, "message");
71 /// utils::span_lint(cx, LINT_NAME, "message");
73 pub COMPILER_LINT_FUNCTIONS,
75 "usage of the lint functions of the compiler instead of the utils::* variant"
78 declare_clippy_lint! {
79 /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
80 /// the `cx.outer_expn_data()`
82 /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
84 /// **Known problems:** None.
89 /// expr.span.ctxt().outer().expn_data()
94 /// expr.span.ctxt().outer_expn_data()
96 pub OUTER_EXPN_EXPN_DATA,
98 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
101 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
103 impl EarlyLintPass for ClippyLintsInternal {
104 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
105 if let Some(utils) = krate
109 .find(|item| item.ident.name.as_str() == "utils")
111 if let ItemKind::Mod(ref utils_mod) = utils.node {
112 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
113 if let ItemKind::Mod(ref paths_mod) = paths.node {
114 let mut last_name: Option<LocalInternedString> = None;
115 for item in &*paths_mod.items {
116 let name = item.ident.as_str();
117 if let Some(ref last_name) = last_name {
118 if **last_name > *name {
121 CLIPPY_LINTS_INTERNAL,
123 "this constant should be before the previous constant due to lexical \
128 last_name = Some(name);
137 #[derive(Clone, Debug, Default)]
138 pub struct LintWithoutLintPass {
139 declared_lints: FxHashMap<Name, Span>,
140 registered_lints: FxHashSet<Name>,
143 impl_lint_pass!(LintWithoutLintPass => [LINT_WITHOUT_LINT_PASS]);
145 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
146 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
147 if let hir::ItemKind::Static(ref ty, MutImmutable, _) = item.node {
148 if is_lint_ref_type(cx, ty) {
149 self.declared_lints.insert(item.ident.name, item.span);
151 } else if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
153 if let hir::TraitRef{path, ..} = trait_ref;
154 if let Res::Def(DefKind::Trait, def_id) = path.res;
155 if match_def_path(cx, def_id, &paths::LINT_PASS);
157 let mut collector = LintCollector {
158 output: &mut self.registered_lints,
161 let body_id = cx.tcx.hir().body_owned_by(
164 .find(|iiref| iiref.ident.as_str() == "get_lints")
165 .expect("LintPass needs to implement get_lints")
168 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
174 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
175 for (lint_name, &lint_span) in &self.declared_lints {
176 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
177 // file points to "<rustc macros>".
178 // `compiletest-rs` thinks that's an error in a different file and
179 // just ignores it. This causes the test in compile-fail/lint_pass
180 // not able to capture the error.
181 // Therefore, we need to climb the macro expansion tree and find the
182 // actual span that invoked `declare_tool_lint!`:
183 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
185 if !self.registered_lints.contains(lint_name) {
188 LINT_WITHOUT_LINT_PASS,
190 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
197 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
206 if let TyKind::Path(ref path) = inner.node {
207 if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
208 return match_def_path(cx, def_id, &paths::LINT);
216 struct LintCollector<'a, 'tcx> {
217 output: &'a mut FxHashSet<Name>,
218 cx: &'a LateContext<'a, 'tcx>,
221 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
222 fn visit_expr(&mut self, expr: &'tcx Expr) {
223 walk_expr(self, expr);
226 fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
227 if path.segments.len() == 1 {
228 self.output.insert(path.segments[0].ident.name);
231 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
232 NestedVisitorMap::All(&self.cx.tcx.hir())
236 #[derive(Clone, Default)]
237 pub struct CompilerLintFunctions {
238 map: FxHashMap<&'static str, &'static str>,
241 impl CompilerLintFunctions {
242 pub fn new() -> Self {
243 let mut map = FxHashMap::default();
244 map.insert("span_lint", "utils::span_lint");
245 map.insert("struct_span_lint", "utils::span_lint");
246 map.insert("lint", "utils::span_lint");
247 map.insert("span_lint_note", "utils::span_note_and_lint");
248 map.insert("span_lint_help", "utils::span_help_and_lint");
253 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
255 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
256 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
258 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
259 let fn_name = path.ident;
260 if let Some(sugg) = self.map.get(&*fn_name.as_str());
261 let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
262 if match_type(cx, ty, &paths::EARLY_CONTEXT)
263 || match_type(cx, ty, &paths::LATE_CONTEXT);
267 COMPILER_LINT_FUNCTIONS,
269 "usage of a compiler lint function",
270 &format!("please use the Clippy variant of this function: `{}`", sugg),
277 pub struct OuterExpnDataPass;
279 impl_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
281 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OuterExpnDataPass {
282 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
283 let (method_names, arg_lists, spans) = method_calls(expr, 2);
284 let method_names: Vec<LocalInternedString> = method_names.iter().map(|s| s.as_str()).collect();
285 let method_names: Vec<&str> = method_names.iter().map(std::convert::AsRef::as_ref).collect();
287 if let ["expn_data", "outer_expn"] = method_names.as_slice();
288 let args = arg_lists[1];
290 let self_arg = &args[0];
291 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(self_arg));
292 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
296 OUTER_EXPN_EXPN_DATA,
297 spans[1].with_hi(expr.span.hi()),
298 "usage of `outer_expn().expn_data()`",
300 "outer_expn_data()".to_string(),
301 Applicability::MachineApplicable,