]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/mod.rs
a5d6cf9dbb72eb23cc754cf1f3fb3e5eb1d688c3
[rust.git] / src / librustc / lint / mod.rs
1 //! Lints, aka compiler warnings.
2 //!
3 //! A 'lint' check is a kind of miscellaneous constraint that a user _might_
4 //! want to enforce, but might reasonably want to permit as well, on a
5 //! module-by-module basis. They contrast with static constraints enforced by
6 //! other phases of the compiler, which are generally required to hold in order
7 //! to compile the program at all.
8 //!
9 //! Most lints can be written as `LintPass` instances. These run after
10 //! all other analyses. The `LintPass`es built into rustc are defined
11 //! within `builtin.rs`, which has further comments on how to add such a lint.
12 //! rustc can also load user-defined lint plugins via the plugin mechanism.
13 //!
14 //! Some of rustc's lints are defined elsewhere in the compiler and work by
15 //! calling `add_lint()` on the overall `Session` object. This works when
16 //! it happens before the main lint pass, which emits the lints stored by
17 //! `add_lint()`. To emit lints after the main lint pass (from codegen, for
18 //! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
19 //! in `context.rs`.
20
21 pub use self::Level::*;
22 pub use self::LintSource::*;
23
24 use rustc_data_structures::sync;
25
26 use crate::hir::def_id::{CrateNum, LOCAL_CRATE};
27 use crate::hir::intravisit;
28 use crate::hir;
29 use crate::lint::builtin::BuiltinLintDiagnostics;
30 use crate::session::{Session, DiagnosticMessageId};
31 use crate::ty::TyCtxt;
32 use crate::ty::query::Providers;
33 use crate::util::nodemap::NodeMap;
34 use errors::{DiagnosticBuilder, DiagnosticId};
35 use syntax::ast;
36 use syntax::source_map::{MultiSpan, ExpnKind, DesugaringKind};
37 use syntax::symbol::Symbol;
38 use syntax_pos::hygiene::MacroKind;
39 use syntax_pos::Span;
40
41 pub use crate::lint::context::{LateContext, EarlyContext, LintContext, LintStore,
42                         check_crate, check_ast_crate, late_lint_mod, CheckLintNameResult,
43                         BufferedEarlyLint,};
44
45 pub use rustc_session::lint::{Lint, LintId, Level, FutureIncompatibleInfo};
46
47 /// Declares a static `LintArray` and return it as an expression.
48 #[macro_export]
49 macro_rules! lint_array {
50     ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
51     ($( $lint:expr ),*) => {{
52         vec![$($lint),*]
53     }}
54 }
55
56 pub type LintArray = Vec<&'static Lint>;
57
58 pub trait LintPass {
59     fn name(&self) -> &'static str;
60 }
61
62 /// Implements `LintPass for $name` with the given list of `Lint` statics.
63 #[macro_export]
64 macro_rules! impl_lint_pass {
65     ($name:ident => [$($lint:expr),* $(,)?]) => {
66         impl LintPass for $name {
67             fn name(&self) -> &'static str { stringify!($name) }
68         }
69         impl $name {
70             pub fn get_lints() -> LintArray { $crate::lint_array!($($lint),*) }
71         }
72     };
73 }
74
75 /// Declares a type named `$name` which implements `LintPass`.
76 /// To the right of `=>` a comma separated list of `Lint` statics is given.
77 #[macro_export]
78 macro_rules! declare_lint_pass {
79     ($(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?]) => {
80         $(#[$m])* #[derive(Copy, Clone)] pub struct $name;
81         $crate::impl_lint_pass!($name => [$($lint),*]);
82     };
83 }
84
85 #[macro_export]
86 macro_rules! late_lint_methods {
87     ($macro:path, $args:tt, [$hir:tt]) => (
88         $macro!($args, [$hir], [
89             fn check_param(a: &$hir hir::Param);
90             fn check_body(a: &$hir hir::Body);
91             fn check_body_post(a: &$hir hir::Body);
92             fn check_name(a: Span, b: ast::Name);
93             fn check_crate(a: &$hir hir::Crate<$hir>);
94             fn check_crate_post(a: &$hir hir::Crate<$hir>);
95             fn check_mod(a: &$hir hir::Mod<$hir>, b: Span, c: hir::HirId);
96             fn check_mod_post(a: &$hir hir::Mod<$hir>, b: Span, c: hir::HirId);
97             fn check_foreign_item(a: &$hir hir::ForeignItem<$hir>);
98             fn check_foreign_item_post(a: &$hir hir::ForeignItem<$hir>);
99             fn check_item(a: &$hir hir::Item<$hir>);
100             fn check_item_post(a: &$hir hir::Item<$hir>);
101             fn check_local(a: &$hir hir::Local);
102             fn check_block(a: &$hir hir::Block);
103             fn check_block_post(a: &$hir hir::Block);
104             fn check_stmt(a: &$hir hir::Stmt);
105             fn check_arm(a: &$hir hir::Arm);
106             fn check_pat(a: &$hir hir::Pat);
107             fn check_expr(a: &$hir hir::Expr);
108             fn check_expr_post(a: &$hir hir::Expr);
109             fn check_ty(a: &$hir hir::Ty);
110             fn check_generic_param(a: &$hir hir::GenericParam);
111             fn check_generics(a: &$hir hir::Generics);
112             fn check_where_predicate(a: &$hir hir::WherePredicate);
113             fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
114             fn check_fn(
115                 a: hir::intravisit::FnKind<$hir>,
116                 b: &$hir hir::FnDecl,
117                 c: &$hir hir::Body,
118                 d: Span,
119                 e: hir::HirId);
120             fn check_fn_post(
121                 a: hir::intravisit::FnKind<$hir>,
122                 b: &$hir hir::FnDecl,
123                 c: &$hir hir::Body,
124                 d: Span,
125                 e: hir::HirId
126             );
127             fn check_trait_item(a: &$hir hir::TraitItem<$hir>);
128             fn check_trait_item_post(a: &$hir hir::TraitItem<$hir>);
129             fn check_impl_item(a: &$hir hir::ImplItem<$hir>);
130             fn check_impl_item_post(a: &$hir hir::ImplItem<$hir>);
131             fn check_struct_def(a: &$hir hir::VariantData<$hir>);
132             fn check_struct_def_post(a: &$hir hir::VariantData<$hir>);
133             fn check_struct_field(a: &$hir hir::StructField<$hir>);
134             fn check_variant(a: &$hir hir::Variant<$hir>);
135             fn check_variant_post(a: &$hir hir::Variant<$hir>);
136             fn check_lifetime(a: &$hir hir::Lifetime);
137             fn check_path(a: &$hir hir::Path, b: hir::HirId);
138             fn check_attribute(a: &$hir ast::Attribute);
139
140             /// Called when entering a syntax node that can have lint attributes such
141             /// as `#[allow(...)]`. Called with *all* the attributes of that node.
142             fn enter_lint_attrs(a: &$hir [ast::Attribute]);
143
144             /// Counterpart to `enter_lint_attrs`.
145             fn exit_lint_attrs(a: &$hir [ast::Attribute]);
146         ]);
147     )
148 }
149
150 /// Trait for types providing lint checks.
151 ///
152 /// Each `check` method checks a single syntax node, and should not
153 /// invoke methods recursively (unlike `Visitor`). By default they
154 /// do nothing.
155 //
156 // FIXME: eliminate the duplication with `Visitor`. But this also
157 // contains a few lint-specific methods with no equivalent in `Visitor`.
158
159 macro_rules! expand_lint_pass_methods {
160     ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
161         $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
162     )
163 }
164
165 macro_rules! declare_late_lint_pass {
166     ([], [$hir:tt], [$($methods:tt)*]) => (
167         pub trait LateLintPass<'a, $hir>: LintPass {
168             expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
169         }
170     )
171 }
172
173 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
174
175 #[macro_export]
176 macro_rules! expand_combined_late_lint_pass_method {
177     ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
178         $($self.$passes.$name $params;)*
179     })
180 }
181
182 #[macro_export]
183 macro_rules! expand_combined_late_lint_pass_methods {
184     ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
185         $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
186             expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
187         })*
188     )
189 }
190
191 #[macro_export]
192 macro_rules! declare_combined_late_lint_pass {
193     ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
194         #[allow(non_snake_case)]
195         $v struct $name {
196             $($passes: $passes,)*
197         }
198
199         impl $name {
200             $v fn new() -> Self {
201                 Self {
202                     $($passes: $constructor,)*
203                 }
204             }
205
206             $v fn get_lints() -> LintArray {
207                 let mut lints = Vec::new();
208                 $(lints.extend_from_slice(&$passes::get_lints());)*
209                 lints
210             }
211         }
212
213         impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
214             expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
215         }
216
217         impl LintPass for $name {
218             fn name(&self) -> &'static str {
219                 panic!()
220             }
221         }
222     )
223 }
224
225 #[macro_export]
226 macro_rules! early_lint_methods {
227     ($macro:path, $args:tt) => (
228         $macro!($args, [
229             fn check_param(a: &ast::Param);
230             fn check_ident(a: ast::Ident);
231             fn check_crate(a: &ast::Crate);
232             fn check_crate_post(a: &ast::Crate);
233             fn check_mod(a: &ast::Mod, b: Span, c: ast::NodeId);
234             fn check_mod_post(a: &ast::Mod, b: Span, c: ast::NodeId);
235             fn check_foreign_item(a: &ast::ForeignItem);
236             fn check_foreign_item_post(a: &ast::ForeignItem);
237             fn check_item(a: &ast::Item);
238             fn check_item_post(a: &ast::Item);
239             fn check_local(a: &ast::Local);
240             fn check_block(a: &ast::Block);
241             fn check_block_post(a: &ast::Block);
242             fn check_stmt(a: &ast::Stmt);
243             fn check_arm(a: &ast::Arm);
244             fn check_pat(a: &ast::Pat);
245             fn check_pat_post(a: &ast::Pat);
246             fn check_expr(a: &ast::Expr);
247             fn check_expr_post(a: &ast::Expr);
248             fn check_ty(a: &ast::Ty);
249             fn check_generic_param(a: &ast::GenericParam);
250             fn check_generics(a: &ast::Generics);
251             fn check_where_predicate(a: &ast::WherePredicate);
252             fn check_poly_trait_ref(a: &ast::PolyTraitRef,
253                                     b: &ast::TraitBoundModifier);
254             fn check_fn(a: syntax::visit::FnKind<'_>, b: &ast::FnDecl, c: Span, d_: ast::NodeId);
255             fn check_fn_post(
256                 a: syntax::visit::FnKind<'_>,
257                 b: &ast::FnDecl,
258                 c: Span,
259                 d: ast::NodeId
260             );
261             fn check_trait_item(a: &ast::AssocItem);
262             fn check_trait_item_post(a: &ast::AssocItem);
263             fn check_impl_item(a: &ast::AssocItem);
264             fn check_impl_item_post(a: &ast::AssocItem);
265             fn check_struct_def(a: &ast::VariantData);
266             fn check_struct_def_post(a: &ast::VariantData);
267             fn check_struct_field(a: &ast::StructField);
268             fn check_variant(a: &ast::Variant);
269             fn check_variant_post(a: &ast::Variant);
270             fn check_lifetime(a: &ast::Lifetime);
271             fn check_path(a: &ast::Path, b: ast::NodeId);
272             fn check_attribute(a: &ast::Attribute);
273             fn check_mac_def(a: &ast::MacroDef, b: ast::NodeId);
274             fn check_mac(a: &ast::Mac);
275
276             /// Called when entering a syntax node that can have lint attributes such
277             /// as `#[allow(...)]`. Called with *all* the attributes of that node.
278             fn enter_lint_attrs(a: &[ast::Attribute]);
279
280             /// Counterpart to `enter_lint_attrs`.
281             fn exit_lint_attrs(a: &[ast::Attribute]);
282         ]);
283     )
284 }
285
286 macro_rules! expand_early_lint_pass_methods {
287     ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
288         $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
289     )
290 }
291
292 macro_rules! declare_early_lint_pass {
293     ([], [$($methods:tt)*]) => (
294         pub trait EarlyLintPass: LintPass {
295             expand_early_lint_pass_methods!(&EarlyContext<'_>, [$($methods)*]);
296         }
297     )
298 }
299
300 early_lint_methods!(declare_early_lint_pass, []);
301
302 #[macro_export]
303 macro_rules! expand_combined_early_lint_pass_method {
304     ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
305         $($self.$passes.$name $params;)*
306     })
307 }
308
309 #[macro_export]
310 macro_rules! expand_combined_early_lint_pass_methods {
311     ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
312         $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
313             expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*));
314         })*
315     )
316 }
317
318 #[macro_export]
319 macro_rules! declare_combined_early_lint_pass {
320     ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => (
321         #[allow(non_snake_case)]
322         $v struct $name {
323             $($passes: $passes,)*
324         }
325
326         impl $name {
327             $v fn new() -> Self {
328                 Self {
329                     $($passes: $constructor,)*
330                 }
331             }
332
333             $v fn get_lints() -> LintArray {
334                 let mut lints = Vec::new();
335                 $(lints.extend_from_slice(&$passes::get_lints());)*
336                 lints
337             }
338         }
339
340         impl EarlyLintPass for $name {
341             expand_combined_early_lint_pass_methods!([$($passes),*], $methods);
342         }
343
344         impl LintPass for $name {
345             fn name(&self) -> &'static str {
346                 panic!()
347             }
348         }
349     )
350 }
351
352 /// A lint pass boxed up as a trait object.
353 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
354 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
355                                                                            + sync::Sync + 'static>;
356
357 /// How a lint level was set.
358 #[derive(Clone, Copy, PartialEq, Eq, HashStable)]
359 pub enum LintSource {
360     /// Lint is at the default level as declared
361     /// in rustc or a plugin.
362     Default,
363
364     /// Lint level was set by an attribute.
365     Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
366
367     /// Lint level was set by a command-line flag.
368     CommandLine(Symbol),
369 }
370
371 pub type LevelSource = (Level, LintSource);
372
373 pub mod builtin;
374 pub mod internal;
375 mod context;
376 mod levels;
377
378 pub use self::levels::{LintLevelSets, LintLevelMap};
379
380 #[derive(Default)]
381 pub struct LintBuffer {
382     map: NodeMap<Vec<BufferedEarlyLint>>,
383 }
384
385 impl LintBuffer {
386     pub fn add_lint(&mut self,
387                     lint: &'static Lint,
388                     id: ast::NodeId,
389                     sp: MultiSpan,
390                     msg: &str,
391                     diagnostic: BuiltinLintDiagnostics) {
392         let early_lint = BufferedEarlyLint {
393             lint_id: LintId::of(lint),
394             ast_id: id,
395             span: sp,
396             msg: msg.to_string(),
397             diagnostic
398         };
399         let arr = self.map.entry(id).or_default();
400         if !arr.contains(&early_lint) {
401             arr.push(early_lint);
402         }
403     }
404
405     fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
406         self.map.remove(&id).unwrap_or_default()
407     }
408
409     pub fn buffer_lint<S: Into<MultiSpan>>(
410         &mut self,
411         lint: &'static Lint,
412         id: ast::NodeId,
413         sp: S,
414         msg: &str,
415     ) {
416         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
417     }
418
419     pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(
420         &mut self,
421         lint: &'static Lint,
422         id: ast::NodeId,
423         sp: S,
424         msg: &str,
425         diagnostic: BuiltinLintDiagnostics,
426     ) {
427         self.add_lint(lint, id, sp.into(), msg, diagnostic)
428     }
429 }
430
431 pub fn struct_lint_level<'a>(sess: &'a Session,
432                              lint: &'static Lint,
433                              level: Level,
434                              src: LintSource,
435                              span: Option<MultiSpan>,
436                              msg: &str)
437     -> DiagnosticBuilder<'a>
438 {
439     let mut err = match (level, span) {
440         (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
441         (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
442         (Level::Warn, None) => sess.struct_warn(msg),
443         (Level::Deny, Some(span)) |
444         (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
445         (Level::Deny, None) |
446         (Level::Forbid, None) => sess.struct_err(msg),
447     };
448
449     // Check for future incompatibility lints and issue a stronger warning.
450     let lint_id = LintId::of(lint);
451     let future_incompatible = lint.future_incompatible;
452
453     // If this code originates in a foreign macro, aka something that this crate
454     // did not itself author, then it's likely that there's nothing this crate
455     // can do about it. We probably want to skip the lint entirely.
456     if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
457         // Any suggestions made here are likely to be incorrect, so anything we
458         // emit shouldn't be automatically fixed by rustfix.
459         err.allow_suggestions(false);
460
461         // If this is a future incompatible lint it'll become a hard error, so
462         // we have to emit *something*. Also allow lints to whitelist themselves
463         // on a case-by-case basis for emission in a foreign macro.
464         if future_incompatible.is_none() && !lint.report_in_external_macro {
465             err.cancel();
466             // Don't continue further, since we don't want to have
467             // `diag_span_note_once` called for a diagnostic that isn't emitted.
468             return err;
469         }
470     }
471
472     let name = lint.name_lower();
473     match src {
474         LintSource::Default => {
475             sess.diag_note_once(
476                 &mut err,
477                 DiagnosticMessageId::from(lint),
478                 &format!("`#[{}({})]` on by default", level.as_str(), name));
479         }
480         LintSource::CommandLine(lint_flag_val) => {
481             let flag = match level {
482                 Level::Warn => "-W",
483                 Level::Deny => "-D",
484                 Level::Forbid => "-F",
485                 Level::Allow => panic!(),
486             };
487             let hyphen_case_lint_name = name.replace("_", "-");
488             if lint_flag_val.as_str() == name {
489                 sess.diag_note_once(
490                     &mut err,
491                     DiagnosticMessageId::from(lint),
492                     &format!("requested on the command line with `{} {}`",
493                              flag, hyphen_case_lint_name));
494             } else {
495                 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
496                 sess.diag_note_once(
497                     &mut err,
498                     DiagnosticMessageId::from(lint),
499                     &format!("`{} {}` implied by `{} {}`",
500                              flag, hyphen_case_lint_name, flag,
501                              hyphen_case_flag_val));
502             }
503         }
504         LintSource::Node(lint_attr_name, src, reason) => {
505             if let Some(rationale) = reason {
506                 err.note(&rationale.as_str());
507             }
508             sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
509                                      src, "lint level defined here");
510             if lint_attr_name.as_str() != name {
511                 let level_str = level.as_str();
512                 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
513                                     &format!("`#[{}({})]` implied by `#[{}({})]`",
514                                              level_str, name, level_str, lint_attr_name));
515             }
516         }
517     }
518
519     err.code(DiagnosticId::Lint(name));
520
521     if let Some(future_incompatible) = future_incompatible {
522         const STANDARD_MESSAGE: &str =
523             "this was previously accepted by the compiler but is being phased out; \
524              it will become a hard error";
525
526         let explanation = if lint_id == LintId::of(builtin::UNSTABLE_NAME_COLLISIONS) {
527             "once this method is added to the standard library, \
528              the ambiguity may cause an error or change in behavior!"
529                 .to_owned()
530         } else if lint_id == LintId::of(builtin::MUTABLE_BORROW_RESERVATION_CONFLICT) {
531             "this borrowing pattern was not meant to be accepted, \
532              and may become a hard error in the future"
533                 .to_owned()
534         } else if let Some(edition) = future_incompatible.edition {
535             format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
536         } else {
537             format!("{} in a future release!", STANDARD_MESSAGE)
538         };
539         let citation = format!("for more information, see {}",
540                                future_incompatible.reference);
541         err.warn(&explanation);
542         err.note(&citation);
543     }
544
545     return err
546 }
547
548 pub fn maybe_lint_level_root(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
549     let attrs = tcx.hir().attrs(id);
550     attrs.iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some())
551 }
552
553 fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> &LintLevelMap {
554     assert_eq!(cnum, LOCAL_CRATE);
555     let store = &tcx.lint_store;
556     let mut builder = LintLevelMapBuilder {
557         levels: LintLevelSets::builder(tcx.sess, false, &store),
558         tcx: tcx,
559         store: store,
560     };
561     let krate = tcx.hir().krate();
562
563     let push = builder.levels.push(&krate.attrs, &store);
564     builder.levels.register_id(hir::CRATE_HIR_ID);
565     for macro_def in krate.exported_macros {
566        builder.levels.register_id(macro_def.hir_id);
567     }
568     intravisit::walk_crate(&mut builder, krate);
569     builder.levels.pop(push);
570
571     tcx.arena.alloc(builder.levels.build_map())
572 }
573
574 struct LintLevelMapBuilder<'a, 'tcx> {
575     levels: levels::LintLevelsBuilder<'tcx>,
576     tcx: TyCtxt<'tcx>,
577     store: &'a LintStore,
578 }
579
580 impl LintLevelMapBuilder<'_, '_> {
581     fn with_lint_attrs<F>(&mut self,
582                           id: hir::HirId,
583                           attrs: &[ast::Attribute],
584                           f: F)
585         where F: FnOnce(&mut Self)
586     {
587         let push = self.levels.push(attrs, self.store);
588         if push.changed {
589             self.levels.register_id(id);
590         }
591         f(self);
592         self.levels.pop(push);
593     }
594 }
595
596 impl intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
597     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
598         intravisit::NestedVisitorMap::All(&self.tcx.hir())
599     }
600
601     fn visit_param(&mut self, param: &'tcx hir::Param) {
602         self.with_lint_attrs(param.hir_id, &param.attrs, |builder| {
603             intravisit::walk_param(builder, param);
604         });
605     }
606
607     fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
608         self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
609             intravisit::walk_item(builder, it);
610         });
611     }
612
613     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
614         self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
615             intravisit::walk_foreign_item(builder, it);
616         })
617     }
618
619     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
620         self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
621             intravisit::walk_expr(builder, e);
622         })
623     }
624
625     fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
626         self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
627             intravisit::walk_struct_field(builder, s);
628         })
629     }
630
631     fn visit_variant(&mut self,
632                      v: &'tcx hir::Variant<'tcx>,
633                      g: &'tcx hir::Generics,
634                      item_id: hir::HirId) {
635         self.with_lint_attrs(v.id, &v.attrs, |builder| {
636             intravisit::walk_variant(builder, v, g, item_id);
637         })
638     }
639
640     fn visit_local(&mut self, l: &'tcx hir::Local) {
641         self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
642             intravisit::walk_local(builder, l);
643         })
644     }
645
646     fn visit_arm(&mut self, a: &'tcx hir::Arm) {
647         self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
648             intravisit::walk_arm(builder, a);
649         })
650     }
651
652     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
653         self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
654             intravisit::walk_trait_item(builder, trait_item);
655         });
656     }
657
658     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
659         self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
660             intravisit::walk_impl_item(builder, impl_item);
661         });
662     }
663 }
664
665 pub fn provide(providers: &mut Providers<'_>) {
666     providers.lint_levels = lint_levels;
667 }
668
669 /// Returns whether `span` originates in a foreign crate's external macro.
670 ///
671 /// This is used to test whether a lint should not even begin to figure out whether it should
672 /// be reported on the current node.
673 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
674     let expn_data = span.ctxt().outer_expn_data();
675     match expn_data.kind {
676         ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false,
677         ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
678         ExpnKind::Macro(MacroKind::Bang, _) => {
679             if expn_data.def_site.is_dummy() {
680                 // Dummy span for the `def_site` means it's an external macro.
681                 return true;
682             }
683             match sess.source_map().span_to_snippet(expn_data.def_site) {
684                 Ok(code) => !code.starts_with("macro_rules"),
685                 // No snippet means external macro or compiler-builtin expansion.
686                 Err(_) => true,
687             }
688         }
689         ExpnKind::Macro(..) => true, // definitely a plugin
690     }
691 }
692
693 /// Returns `true` if `span` originates in a derive-macro's expansion.
694 pub fn in_derive_expansion(span: Span) -> bool {
695     if let ExpnKind::Macro(MacroKind::Derive, _) = span.ctxt().outer_expn_data().kind {
696         return true;
697     }
698     false
699 }