]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/mod.rs
Auto merge of #51678 - Zoxc:combine-lints, r=estebank
[rust.git] / src / librustc / lint / mod.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Lints, aka compiler warnings.
12 //!
13 //! A 'lint' check is a kind of miscellaneous constraint that a user _might_
14 //! want to enforce, but might reasonably want to permit as well, on a
15 //! module-by-module basis. They contrast with static constraints enforced by
16 //! other phases of the compiler, which are generally required to hold in order
17 //! to compile the program at all.
18 //!
19 //! Most lints can be written as `LintPass` instances. These run after
20 //! all other analyses. The `LintPass`es built into rustc are defined
21 //! within `builtin.rs`, which has further comments on how to add such a lint.
22 //! rustc can also load user-defined lint plugins via the plugin mechanism.
23 //!
24 //! Some of rustc's lints are defined elsewhere in the compiler and work by
25 //! calling `add_lint()` on the overall `Session` object. This works when
26 //! it happens before the main lint pass, which emits the lints stored by
27 //! `add_lint()`. To emit lints after the main lint pass (from codegen, for
28 //! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
29 //! in `context.rs`.
30
31 pub use self::Level::*;
32 pub use self::LintSource::*;
33
34 use rustc_data_structures::sync::{self, Lrc};
35
36 use errors::{DiagnosticBuilder, DiagnosticId};
37 use hir::def_id::{CrateNum, LOCAL_CRATE};
38 use hir::intravisit;
39 use hir;
40 use lint::builtin::BuiltinLintDiagnostics;
41 use session::{Session, DiagnosticMessageId};
42 use std::hash;
43 use syntax::ast;
44 use syntax::codemap::MultiSpan;
45 use syntax::edition::Edition;
46 use syntax::symbol::Symbol;
47 use syntax::visit as ast_visit;
48 use syntax_pos::Span;
49 use ty::TyCtxt;
50 use ty::query::Providers;
51 use util::nodemap::NodeMap;
52
53 pub use lint::context::{LateContext, EarlyContext, LintContext, LintStore,
54                         check_crate, check_ast_crate,
55                         FutureIncompatibleInfo, BufferedEarlyLint};
56
57 /// Specification of a single lint.
58 #[derive(Copy, Clone, Debug)]
59 pub struct Lint {
60     /// A string identifier for the lint.
61     ///
62     /// This identifies the lint in attributes and in command-line arguments.
63     /// In those contexts it is always lowercase, but this field is compared
64     /// in a way which is case-insensitive for ASCII characters. This allows
65     /// `declare_lint!()` invocations to follow the convention of upper-case
66     /// statics without repeating the name.
67     ///
68     /// The name is written with underscores, e.g. "unused_imports".
69     /// On the command line, underscores become dashes.
70     pub name: &'static str,
71
72     /// Default level for the lint.
73     pub default_level: Level,
74
75     /// Description of the lint or the issue it detects.
76     ///
77     /// e.g. "imports that are never used"
78     pub desc: &'static str,
79
80     /// Starting at the given edition, default to the given lint level. If this is `None`, then use
81     /// `default_level`.
82     pub edition_lint_opts: Option<(Edition, Level)>,
83 }
84
85 impl Lint {
86     /// Get the lint's name, with ASCII letters converted to lowercase.
87     pub fn name_lower(&self) -> String {
88         self.name.to_ascii_lowercase()
89     }
90
91     pub fn default_level(&self, session: &Session) -> Level {
92         self.edition_lint_opts
93             .filter(|(e, _)| *e <= session.edition())
94             .map(|(_, l)| l)
95             .unwrap_or(self.default_level)
96     }
97 }
98
99 /// Declare a static item of type `&'static Lint`.
100 #[macro_export]
101 macro_rules! declare_lint {
102     ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
103         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
104             name: stringify!($NAME),
105             default_level: $crate::lint::$Level,
106             desc: $desc,
107             edition_lint_opts: None,
108         };
109     );
110     ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
111      $lint_edition: expr => $edition_level: ident $(,)?
112     ) => (
113         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
114             name: stringify!($NAME),
115             default_level: $crate::lint::$Level,
116             desc: $desc,
117             edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
118         };
119     );
120 }
121
122 /// Declare a static `LintArray` and return it as an expression.
123 #[macro_export]
124 macro_rules! lint_array {
125     ($( $lint:expr ),* $(,)?) => {{
126         vec![$($lint),*]
127     }}
128 }
129
130 pub type LintArray = Vec<&'static Lint>;
131
132 pub trait LintPass {
133     /// Get descriptions of the lints this `LintPass` object can emit.
134     ///
135     /// NB: there is no enforcement that the object only emits lints it registered.
136     /// And some `rustc` internal `LintPass`es register lints to be emitted by other
137     /// parts of the compiler. If you want enforced access restrictions for your
138     /// `Lint`, make it a private `static` item in its own module.
139     fn get_lints(&self) -> LintArray;
140 }
141
142 #[macro_export]
143 macro_rules! late_lint_methods {
144     ($macro:path, $args:tt, [$hir:tt]) => (
145         $macro!($args, [$hir], [
146             fn check_body(a: &$hir hir::Body);
147             fn check_body_post(a: &$hir hir::Body);
148             fn check_name(a: Span, b: ast::Name);
149             fn check_crate(a: &$hir hir::Crate);
150             fn check_crate_post(a: &$hir hir::Crate);
151             fn check_mod(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
152             fn check_mod_post(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
153             fn check_foreign_item(a: &$hir hir::ForeignItem);
154             fn check_foreign_item_post(a: &$hir hir::ForeignItem);
155             fn check_item(a: &$hir hir::Item);
156             fn check_item_post(a: &$hir hir::Item);
157             fn check_local(a: &$hir hir::Local);
158             fn check_block(a: &$hir hir::Block);
159             fn check_block_post(a: &$hir hir::Block);
160             fn check_stmt(a: &$hir hir::Stmt);
161             fn check_arm(a: &$hir hir::Arm);
162             fn check_pat(a: &$hir hir::Pat);
163             fn check_decl(a: &$hir hir::Decl);
164             fn check_expr(a: &$hir hir::Expr);
165             fn check_expr_post(a: &$hir hir::Expr);
166             fn check_ty(a: &$hir hir::Ty);
167             fn check_generic_param(a: &$hir hir::GenericParam);
168             fn check_generics(a: &$hir hir::Generics);
169             fn check_where_predicate(a: &$hir hir::WherePredicate);
170             fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
171             fn check_fn(
172                 a: hir::intravisit::FnKind<$hir>,
173                 b: &$hir hir::FnDecl,
174                 c: &$hir hir::Body,
175                 d: Span,
176                 e: ast::NodeId);
177             fn check_fn_post(
178                 a: hir::intravisit::FnKind<$hir>,
179                 b: &$hir hir::FnDecl,
180                 c: &$hir hir::Body,
181                 d: Span,
182                 e: ast::NodeId
183             );
184             fn check_trait_item(a: &$hir hir::TraitItem);
185             fn check_trait_item_post(a: &$hir hir::TraitItem);
186             fn check_impl_item(a: &$hir hir::ImplItem);
187             fn check_impl_item_post(a: &$hir hir::ImplItem);
188             fn check_struct_def(
189                 a: &$hir hir::VariantData,
190                 b: ast::Name,
191                 c: &$hir hir::Generics,
192                 d: ast::NodeId
193             );
194             fn check_struct_def_post(
195                 a: &$hir hir::VariantData,
196                 b: ast::Name,
197                 c: &$hir hir::Generics,
198                 d: ast::NodeId
199             );
200             fn check_struct_field(a: &$hir hir::StructField);
201             fn check_variant(a: &$hir hir::Variant, b: &$hir hir::Generics);
202             fn check_variant_post(a: &$hir hir::Variant, b: &$hir hir::Generics);
203             fn check_lifetime(a: &$hir hir::Lifetime);
204             fn check_path(a: &$hir hir::Path, b: ast::NodeId);
205             fn check_attribute(a: &$hir ast::Attribute);
206
207             /// Called when entering a syntax node that can have lint attributes such
208             /// as `#[allow(...)]`. Called with *all* the attributes of that node.
209             fn enter_lint_attrs(a: &$hir [ast::Attribute]);
210
211             /// Counterpart to `enter_lint_attrs`.
212             fn exit_lint_attrs(a: &$hir [ast::Attribute]);
213         ]);
214     )
215 }
216
217 /// Trait for types providing lint checks.
218 ///
219 /// Each `check` method checks a single syntax node, and should not
220 /// invoke methods recursively (unlike `Visitor`). By default they
221 /// do nothing.
222 //
223 // FIXME: eliminate the duplication with `Visitor`. But this also
224 // contains a few lint-specific methods with no equivalent in `Visitor`.
225
226 macro_rules! expand_lint_pass_methods {
227     ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
228         $(#[inline(always)] fn $name(&mut self, $context, $(_: $arg),*) {})*
229     )
230 }
231
232 macro_rules! declare_late_lint_pass {
233     ([], [$hir:tt], [$($methods:tt)*]) => (
234         pub trait LateLintPass<'a, $hir>: LintPass {
235             expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
236         }
237     )
238 }
239
240 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
241
242 #[macro_export]
243 macro_rules! expand_combined_late_lint_pass_method {
244     ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
245         $($self.$passes.$name $params;)*
246     })
247 }
248
249 #[macro_export]
250 macro_rules! expand_combined_late_lint_pass_methods {
251     ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
252         $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
253             expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
254         })*
255     )
256 }
257
258 #[macro_export]
259 macro_rules! declare_combined_late_lint_pass {
260     ([$name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
261         #[allow(non_snake_case)]
262         struct $name {
263             $($passes: $passes,)*
264         }
265
266         impl $name {
267             fn new() -> Self {
268                 Self {
269                     $($passes: $constructor,)*
270                 }
271             }
272         }
273
274         impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
275             expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
276         }
277
278         impl LintPass for $name {
279             fn get_lints(&self) -> LintArray {
280                 let mut lints = Vec::new();
281                 $(lints.extend_from_slice(&self.$passes.get_lints());)*
282                 lints
283             }
284         }
285     )
286 }
287
288 pub trait EarlyLintPass: LintPass {
289     fn check_ident(&mut self, _: &EarlyContext, _: ast::Ident) { }
290     fn check_crate(&mut self, _: &EarlyContext, _: &ast::Crate) { }
291     fn check_crate_post(&mut self, _: &EarlyContext, _: &ast::Crate) { }
292     fn check_mod(&mut self, _: &EarlyContext, _: &ast::Mod, _: Span, _: ast::NodeId) { }
293     fn check_mod_post(&mut self, _: &EarlyContext, _: &ast::Mod, _: Span, _: ast::NodeId) { }
294     fn check_foreign_item(&mut self, _: &EarlyContext, _: &ast::ForeignItem) { }
295     fn check_foreign_item_post(&mut self, _: &EarlyContext, _: &ast::ForeignItem) { }
296     fn check_item(&mut self, _: &EarlyContext, _: &ast::Item) { }
297     fn check_item_post(&mut self, _: &EarlyContext, _: &ast::Item) { }
298     fn check_local(&mut self, _: &EarlyContext, _: &ast::Local) { }
299     fn check_block(&mut self, _: &EarlyContext, _: &ast::Block) { }
300     fn check_block_post(&mut self, _: &EarlyContext, _: &ast::Block) { }
301     fn check_stmt(&mut self, _: &EarlyContext, _: &ast::Stmt) { }
302     fn check_arm(&mut self, _: &EarlyContext, _: &ast::Arm) { }
303     fn check_pat(&mut self, _: &EarlyContext, _: &ast::Pat) { }
304     fn check_expr(&mut self, _: &EarlyContext, _: &ast::Expr) { }
305     fn check_expr_post(&mut self, _: &EarlyContext, _: &ast::Expr) { }
306     fn check_ty(&mut self, _: &EarlyContext, _: &ast::Ty) { }
307     fn check_generic_param(&mut self, _: &EarlyContext, _: &ast::GenericParam) { }
308     fn check_generics(&mut self, _: &EarlyContext, _: &ast::Generics) { }
309     fn check_where_predicate(&mut self, _: &EarlyContext, _: &ast::WherePredicate) { }
310     fn check_poly_trait_ref(&mut self, _: &EarlyContext, _: &ast::PolyTraitRef,
311                             _: &ast::TraitBoundModifier) { }
312     fn check_fn(&mut self, _: &EarlyContext,
313         _: ast_visit::FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) { }
314     fn check_fn_post(&mut self, _: &EarlyContext,
315         _: ast_visit::FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) { }
316     fn check_trait_item(&mut self, _: &EarlyContext, _: &ast::TraitItem) { }
317     fn check_trait_item_post(&mut self, _: &EarlyContext, _: &ast::TraitItem) { }
318     fn check_impl_item(&mut self, _: &EarlyContext, _: &ast::ImplItem) { }
319     fn check_impl_item_post(&mut self, _: &EarlyContext, _: &ast::ImplItem) { }
320     fn check_struct_def(&mut self, _: &EarlyContext,
321         _: &ast::VariantData, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
322     fn check_struct_def_post(&mut self, _: &EarlyContext,
323         _: &ast::VariantData, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
324     fn check_struct_field(&mut self, _: &EarlyContext, _: &ast::StructField) { }
325     fn check_variant(&mut self, _: &EarlyContext, _: &ast::Variant, _: &ast::Generics) { }
326     fn check_variant_post(&mut self, _: &EarlyContext, _: &ast::Variant, _: &ast::Generics) { }
327     fn check_lifetime(&mut self, _: &EarlyContext, _: &ast::Lifetime) { }
328     fn check_path(&mut self, _: &EarlyContext, _: &ast::Path, _: ast::NodeId) { }
329     fn check_attribute(&mut self, _: &EarlyContext, _: &ast::Attribute) { }
330
331     /// Called when entering a syntax node that can have lint attributes such
332     /// as `#[allow(...)]`. Called with *all* the attributes of that node.
333     fn enter_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
334
335     /// Counterpart to `enter_lint_attrs`.
336     fn exit_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
337 }
338
339 /// A lint pass boxed up as a trait object.
340 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
341 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
342                                                                            + sync::Sync + 'static>;
343
344 /// Identifies a lint known to the compiler.
345 #[derive(Clone, Copy, Debug)]
346 pub struct LintId {
347     // Identity is based on pointer equality of this field.
348     lint: &'static Lint,
349 }
350
351 impl PartialEq for LintId {
352     fn eq(&self, other: &LintId) -> bool {
353         (self.lint as *const Lint) == (other.lint as *const Lint)
354     }
355 }
356
357 impl Eq for LintId { }
358
359 impl hash::Hash for LintId {
360     fn hash<H: hash::Hasher>(&self, state: &mut H) {
361         let ptr = self.lint as *const Lint;
362         ptr.hash(state);
363     }
364 }
365
366 impl LintId {
367     /// Get the `LintId` for a `Lint`.
368     pub fn of(lint: &'static Lint) -> LintId {
369         LintId {
370             lint,
371         }
372     }
373
374     pub fn lint_name_raw(&self) -> &'static str {
375         self.lint.name
376     }
377
378     /// Get the name of the lint.
379     pub fn to_string(&self) -> String {
380         self.lint.name_lower()
381     }
382 }
383
384 /// Setting for how to handle a lint.
385 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
386 pub enum Level {
387     Allow, Warn, Deny, Forbid,
388 }
389
390 impl_stable_hash_for!(enum self::Level {
391     Allow,
392     Warn,
393     Deny,
394     Forbid
395 });
396
397 impl Level {
398     /// Convert a level to a lower-case string.
399     pub fn as_str(self) -> &'static str {
400         match self {
401             Allow => "allow",
402             Warn => "warn",
403             Deny => "deny",
404             Forbid => "forbid",
405         }
406     }
407
408     /// Convert a lower-case string to a level.
409     pub fn from_str(x: &str) -> Option<Level> {
410         match x {
411             "allow" => Some(Allow),
412             "warn" => Some(Warn),
413             "deny" => Some(Deny),
414             "forbid" => Some(Forbid),
415             _ => None,
416         }
417     }
418 }
419
420 /// How a lint level was set.
421 #[derive(Clone, Copy, PartialEq, Eq)]
422 pub enum LintSource {
423     /// Lint is at the default level as declared
424     /// in rustc or a plugin.
425     Default,
426
427     /// Lint level was set by an attribute.
428     Node(ast::Name, Span),
429
430     /// Lint level was set by a command-line flag.
431     CommandLine(Symbol),
432 }
433
434 impl_stable_hash_for!(enum self::LintSource {
435     Default,
436     Node(name, span),
437     CommandLine(text)
438 });
439
440 pub type LevelSource = (Level, LintSource);
441
442 pub mod builtin;
443 mod context;
444 mod levels;
445
446 pub use self::levels::{LintLevelSets, LintLevelMap};
447
448 pub struct LintBuffer {
449     map: NodeMap<Vec<BufferedEarlyLint>>,
450 }
451
452 impl LintBuffer {
453     pub fn new() -> LintBuffer {
454         LintBuffer { map: NodeMap() }
455     }
456
457     pub fn add_lint(&mut self,
458                     lint: &'static Lint,
459                     id: ast::NodeId,
460                     sp: MultiSpan,
461                     msg: &str,
462                     diagnostic: BuiltinLintDiagnostics) {
463         let early_lint = BufferedEarlyLint {
464             lint_id: LintId::of(lint),
465             ast_id: id,
466             span: sp,
467             msg: msg.to_string(),
468             diagnostic
469         };
470         let arr = self.map.entry(id).or_insert(Vec::new());
471         if !arr.contains(&early_lint) {
472             arr.push(early_lint);
473         }
474     }
475
476     pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
477         self.map.remove(&id).unwrap_or(Vec::new())
478     }
479
480     pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
481         let key = self.map.keys().next().map(|k| *k);
482         key.map(|k| &self.map[&k][..])
483     }
484 }
485
486 pub fn struct_lint_level<'a>(sess: &'a Session,
487                              lint: &'static Lint,
488                              level: Level,
489                              src: LintSource,
490                              span: Option<MultiSpan>,
491                              msg: &str)
492     -> DiagnosticBuilder<'a>
493 {
494     let mut err = match (level, span) {
495         (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
496         (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
497         (Level::Warn, None) => sess.struct_warn(msg),
498         (Level::Deny, Some(span)) |
499         (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
500         (Level::Deny, None) |
501         (Level::Forbid, None) => sess.struct_err(msg),
502     };
503
504     let name = lint.name_lower();
505     match src {
506         LintSource::Default => {
507             sess.diag_note_once(
508                 &mut err,
509                 DiagnosticMessageId::from(lint),
510                 &format!("#[{}({})] on by default", level.as_str(), name));
511         }
512         LintSource::CommandLine(lint_flag_val) => {
513             let flag = match level {
514                 Level::Warn => "-W",
515                 Level::Deny => "-D",
516                 Level::Forbid => "-F",
517                 Level::Allow => panic!(),
518             };
519             let hyphen_case_lint_name = name.replace("_", "-");
520             if lint_flag_val.as_str() == name {
521                 sess.diag_note_once(
522                     &mut err,
523                     DiagnosticMessageId::from(lint),
524                     &format!("requested on the command line with `{} {}`",
525                              flag, hyphen_case_lint_name));
526             } else {
527                 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
528                 sess.diag_note_once(
529                     &mut err,
530                     DiagnosticMessageId::from(lint),
531                     &format!("`{} {}` implied by `{} {}`",
532                              flag, hyphen_case_lint_name, flag,
533                              hyphen_case_flag_val));
534             }
535         }
536         LintSource::Node(lint_attr_name, src) => {
537             sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
538                                      src, "lint level defined here");
539             if lint_attr_name.as_str() != name {
540                 let level_str = level.as_str();
541                 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
542                                     &format!("#[{}({})] implied by #[{}({})]",
543                                              level_str, name, level_str, lint_attr_name));
544             }
545         }
546     }
547
548     err.code(DiagnosticId::Lint(name));
549
550     // Check for future incompatibility lints and issue a stronger warning.
551     let lints = sess.lint_store.borrow();
552     let lint_id = LintId::of(lint);
553     if let Some(future_incompatible) = lints.future_incompatible(lint_id) {
554         const STANDARD_MESSAGE: &str =
555             "this was previously accepted by the compiler but is being phased out; \
556              it will become a hard error";
557
558         let explanation = if lint_id == LintId::of(::lint::builtin::UNSTABLE_NAME_COLLISIONS) {
559             "once this method is added to the standard library, \
560              the ambiguity may cause an error or change in behavior!"
561                 .to_owned()
562         } else if let Some(edition) = future_incompatible.edition {
563             format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
564         } else {
565             format!("{} in a future release!", STANDARD_MESSAGE)
566         };
567         let citation = format!("for more information, see {}",
568                                future_incompatible.reference);
569         err.warn(&explanation);
570         err.note(&citation);
571     }
572
573     return err
574 }
575
576 fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
577     -> Lrc<LintLevelMap>
578 {
579     assert_eq!(cnum, LOCAL_CRATE);
580     let mut builder = LintLevelMapBuilder {
581         levels: LintLevelSets::builder(tcx.sess),
582         tcx: tcx,
583     };
584     let krate = tcx.hir.krate();
585
586     builder.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |builder| {
587         intravisit::walk_crate(builder, krate);
588     });
589
590     Lrc::new(builder.levels.build_map())
591 }
592
593 struct LintLevelMapBuilder<'a, 'tcx: 'a> {
594     levels: levels::LintLevelsBuilder<'tcx>,
595     tcx: TyCtxt<'a, 'tcx, 'tcx>,
596 }
597
598 impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
599     fn with_lint_attrs<F>(&mut self,
600                           id: ast::NodeId,
601                           attrs: &[ast::Attribute],
602                           f: F)
603         where F: FnOnce(&mut Self)
604     {
605         let push = self.levels.push(attrs);
606         self.levels.register_id(self.tcx.hir.definitions().node_to_hir_id(id));
607         f(self);
608         self.levels.pop(push);
609     }
610 }
611
612 impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
613     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
614         intravisit::NestedVisitorMap::All(&self.tcx.hir)
615     }
616
617     fn visit_item(&mut self, it: &'tcx hir::Item) {
618         self.with_lint_attrs(it.id, &it.attrs, |builder| {
619             intravisit::walk_item(builder, it);
620         });
621     }
622
623     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
624         self.with_lint_attrs(it.id, &it.attrs, |builder| {
625             intravisit::walk_foreign_item(builder, it);
626         })
627     }
628
629     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
630         self.with_lint_attrs(e.id, &e.attrs, |builder| {
631             intravisit::walk_expr(builder, e);
632         })
633     }
634
635     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
636         self.with_lint_attrs(s.id, &s.attrs, |builder| {
637             intravisit::walk_struct_field(builder, s);
638         })
639     }
640
641     fn visit_variant(&mut self,
642                      v: &'tcx hir::Variant,
643                      g: &'tcx hir::Generics,
644                      item_id: ast::NodeId) {
645         self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |builder| {
646             intravisit::walk_variant(builder, v, g, item_id);
647         })
648     }
649
650     fn visit_local(&mut self, l: &'tcx hir::Local) {
651         self.with_lint_attrs(l.id, &l.attrs, |builder| {
652             intravisit::walk_local(builder, l);
653         })
654     }
655
656     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
657         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |builder| {
658             intravisit::walk_trait_item(builder, trait_item);
659         });
660     }
661
662     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
663         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |builder| {
664             intravisit::walk_impl_item(builder, impl_item);
665         });
666     }
667 }
668
669 pub fn provide(providers: &mut Providers) {
670     providers.lint_levels = lint_levels;
671 }