]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/mod.rs
Skip checking for unused mutable locals that have no name
[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 just before
20 //! translation to LLVM bytecode. 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 trans, 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::{self, FnKind};
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::maps::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     /// Deny lint after this edition
81     pub edition_deny: Option<Edition>,
82 }
83
84 impl Lint {
85     /// Get the lint's name, with ASCII letters converted to lowercase.
86     pub fn name_lower(&self) -> String {
87         self.name.to_ascii_lowercase()
88     }
89
90     pub fn default_level(&self, session: &Session) -> Level {
91         if let Some(edition_deny) = self.edition_deny {
92             if session.edition() >= edition_deny {
93                 return Level::Deny
94             }
95         }
96         self.default_level
97     }
98 }
99
100 /// Declare a static item of type `&'static Lint`.
101 #[macro_export]
102 macro_rules! declare_lint {
103     ($vis: vis $NAME: ident, $Level: ident, $desc: expr, $edition: expr) => (
104         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
105             name: stringify!($NAME),
106             default_level: $crate::lint::$Level,
107             desc: $desc,
108             edition_deny: Some($edition)
109         };
110     );
111     ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
112         $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
113             name: stringify!($NAME),
114             default_level: $crate::lint::$Level,
115             desc: $desc,
116             edition_deny: None,
117         };
118     );
119 }
120
121 /// Declare a static `LintArray` and return it as an expression.
122 #[macro_export]
123 macro_rules! lint_array {
124     ($( $lint:expr ),*,) => { lint_array!( $( $lint ),* ) };
125     ($( $lint:expr ),*) => {{
126          static ARRAY: LintArray = &[ $( &$lint ),* ];
127          ARRAY
128     }}
129 }
130
131 pub type LintArray = &'static [&'static &'static Lint];
132
133 pub trait LintPass {
134     /// Get descriptions of the lints this `LintPass` object can emit.
135     ///
136     /// NB: there is no enforcement that the object only emits lints it registered.
137     /// And some `rustc` internal `LintPass`es register lints to be emitted by other
138     /// parts of the compiler. If you want enforced access restrictions for your
139     /// `Lint`, make it a private `static` item in its own module.
140     fn get_lints(&self) -> LintArray;
141 }
142
143
144 /// Trait for types providing lint checks.
145 ///
146 /// Each `check` method checks a single syntax node, and should not
147 /// invoke methods recursively (unlike `Visitor`). By default they
148 /// do nothing.
149 //
150 // FIXME: eliminate the duplication with `Visitor`. But this also
151 // contains a few lint-specific methods with no equivalent in `Visitor`.
152 pub trait LateLintPass<'a, 'tcx>: LintPass {
153     fn check_body(&mut self, _: &LateContext, _: &'tcx hir::Body) { }
154     fn check_body_post(&mut self, _: &LateContext, _: &'tcx hir::Body) { }
155     fn check_name(&mut self, _: &LateContext, _: Span, _: ast::Name) { }
156     fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Crate) { }
157     fn check_crate_post(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Crate) { }
158     fn check_mod(&mut self,
159                  _: &LateContext<'a, 'tcx>,
160                  _: &'tcx hir::Mod,
161                  _: Span,
162                  _: ast::NodeId) { }
163     fn check_mod_post(&mut self,
164                       _: &LateContext<'a, 'tcx>,
165                       _: &'tcx hir::Mod,
166                       _: Span,
167                       _: ast::NodeId) { }
168     fn check_foreign_item(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::ForeignItem) { }
169     fn check_foreign_item_post(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::ForeignItem) { }
170     fn check_item(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Item) { }
171     fn check_item_post(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Item) { }
172     fn check_local(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Local) { }
173     fn check_block(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Block) { }
174     fn check_block_post(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Block) { }
175     fn check_stmt(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Stmt) { }
176     fn check_arm(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Arm) { }
177     fn check_pat(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Pat) { }
178     fn check_decl(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Decl) { }
179     fn check_expr(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Expr) { }
180     fn check_expr_post(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Expr) { }
181     fn check_ty(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Ty) { }
182     fn check_generic_param(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::GenericParam) { }
183     fn check_generics(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Generics) { }
184     fn check_where_predicate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::WherePredicate) { }
185     fn check_poly_trait_ref(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::PolyTraitRef,
186                             _: hir::TraitBoundModifier) { }
187     fn check_fn(&mut self,
188                 _: &LateContext<'a, 'tcx>,
189                 _: FnKind<'tcx>,
190                 _: &'tcx hir::FnDecl,
191                 _: &'tcx hir::Body,
192                 _: Span,
193                 _: ast::NodeId) { }
194     fn check_fn_post(&mut self,
195                      _: &LateContext<'a, 'tcx>,
196                      _: FnKind<'tcx>,
197                      _: &'tcx hir::FnDecl,
198                      _: &'tcx hir::Body,
199                      _: Span,
200                      _: ast::NodeId) { }
201     fn check_trait_item(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::TraitItem) { }
202     fn check_trait_item_post(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::TraitItem) { }
203     fn check_impl_item(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::ImplItem) { }
204     fn check_impl_item_post(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::ImplItem) { }
205     fn check_struct_def(&mut self,
206                         _: &LateContext<'a, 'tcx>,
207                         _: &'tcx hir::VariantData,
208                         _: ast::Name,
209                         _: &'tcx hir::Generics,
210                         _: ast::NodeId) { }
211     fn check_struct_def_post(&mut self,
212                              _: &LateContext<'a, 'tcx>,
213                              _: &'tcx hir::VariantData,
214                              _: ast::Name,
215                              _: &'tcx hir::Generics,
216                              _: ast::NodeId) { }
217     fn check_struct_field(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::StructField) { }
218     fn check_variant(&mut self,
219                      _: &LateContext<'a, 'tcx>,
220                      _: &'tcx hir::Variant,
221                      _: &'tcx hir::Generics) { }
222     fn check_variant_post(&mut self,
223                           _: &LateContext<'a, 'tcx>,
224                           _: &'tcx hir::Variant,
225                           _: &'tcx hir::Generics) { }
226     fn check_lifetime(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Lifetime) { }
227     fn check_path(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Path, _: ast::NodeId) { }
228     fn check_attribute(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx ast::Attribute) { }
229
230     /// Called when entering a syntax node that can have lint attributes such
231     /// as `#[allow(...)]`. Called with *all* the attributes of that node.
232     fn enter_lint_attrs(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx [ast::Attribute]) { }
233
234     /// Counterpart to `enter_lint_attrs`.
235     fn exit_lint_attrs(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx [ast::Attribute]) { }
236 }
237
238 pub trait EarlyLintPass: LintPass {
239     fn check_ident(&mut self, _: &EarlyContext, _: ast::Ident) { }
240     fn check_crate(&mut self, _: &EarlyContext, _: &ast::Crate) { }
241     fn check_crate_post(&mut self, _: &EarlyContext, _: &ast::Crate) { }
242     fn check_mod(&mut self, _: &EarlyContext, _: &ast::Mod, _: Span, _: ast::NodeId) { }
243     fn check_mod_post(&mut self, _: &EarlyContext, _: &ast::Mod, _: Span, _: ast::NodeId) { }
244     fn check_foreign_item(&mut self, _: &EarlyContext, _: &ast::ForeignItem) { }
245     fn check_foreign_item_post(&mut self, _: &EarlyContext, _: &ast::ForeignItem) { }
246     fn check_item(&mut self, _: &EarlyContext, _: &ast::Item) { }
247     fn check_item_post(&mut self, _: &EarlyContext, _: &ast::Item) { }
248     fn check_local(&mut self, _: &EarlyContext, _: &ast::Local) { }
249     fn check_block(&mut self, _: &EarlyContext, _: &ast::Block) { }
250     fn check_block_post(&mut self, _: &EarlyContext, _: &ast::Block) { }
251     fn check_stmt(&mut self, _: &EarlyContext, _: &ast::Stmt) { }
252     fn check_arm(&mut self, _: &EarlyContext, _: &ast::Arm) { }
253     fn check_pat(&mut self, _: &EarlyContext, _: &ast::Pat) { }
254     fn check_expr(&mut self, _: &EarlyContext, _: &ast::Expr) { }
255     fn check_expr_post(&mut self, _: &EarlyContext, _: &ast::Expr) { }
256     fn check_ty(&mut self, _: &EarlyContext, _: &ast::Ty) { }
257     fn check_generic_param(&mut self, _: &EarlyContext, _: &ast::GenericParam) { }
258     fn check_generics(&mut self, _: &EarlyContext, _: &ast::Generics) { }
259     fn check_where_predicate(&mut self, _: &EarlyContext, _: &ast::WherePredicate) { }
260     fn check_poly_trait_ref(&mut self, _: &EarlyContext, _: &ast::PolyTraitRef,
261                             _: &ast::TraitBoundModifier) { }
262     fn check_fn(&mut self, _: &EarlyContext,
263         _: ast_visit::FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) { }
264     fn check_fn_post(&mut self, _: &EarlyContext,
265         _: ast_visit::FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) { }
266     fn check_trait_item(&mut self, _: &EarlyContext, _: &ast::TraitItem) { }
267     fn check_trait_item_post(&mut self, _: &EarlyContext, _: &ast::TraitItem) { }
268     fn check_impl_item(&mut self, _: &EarlyContext, _: &ast::ImplItem) { }
269     fn check_impl_item_post(&mut self, _: &EarlyContext, _: &ast::ImplItem) { }
270     fn check_struct_def(&mut self, _: &EarlyContext,
271         _: &ast::VariantData, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
272     fn check_struct_def_post(&mut self, _: &EarlyContext,
273         _: &ast::VariantData, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
274     fn check_struct_field(&mut self, _: &EarlyContext, _: &ast::StructField) { }
275     fn check_variant(&mut self, _: &EarlyContext, _: &ast::Variant, _: &ast::Generics) { }
276     fn check_variant_post(&mut self, _: &EarlyContext, _: &ast::Variant, _: &ast::Generics) { }
277     fn check_lifetime(&mut self, _: &EarlyContext, _: &ast::Lifetime) { }
278     fn check_path(&mut self, _: &EarlyContext, _: &ast::Path, _: ast::NodeId) { }
279     fn check_attribute(&mut self, _: &EarlyContext, _: &ast::Attribute) { }
280
281     /// Called when entering a syntax node that can have lint attributes such
282     /// as `#[allow(...)]`. Called with *all* the attributes of that node.
283     fn enter_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
284
285     /// Counterpart to `enter_lint_attrs`.
286     fn exit_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
287 }
288
289 /// A lint pass boxed up as a trait object.
290 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
291 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
292                                                                            + sync::Sync + 'static>;
293
294 /// Identifies a lint known to the compiler.
295 #[derive(Clone, Copy, Debug)]
296 pub struct LintId {
297     // Identity is based on pointer equality of this field.
298     lint: &'static Lint,
299 }
300
301 impl PartialEq for LintId {
302     fn eq(&self, other: &LintId) -> bool {
303         (self.lint as *const Lint) == (other.lint as *const Lint)
304     }
305 }
306
307 impl Eq for LintId { }
308
309 impl hash::Hash for LintId {
310     fn hash<H: hash::Hasher>(&self, state: &mut H) {
311         let ptr = self.lint as *const Lint;
312         ptr.hash(state);
313     }
314 }
315
316 impl LintId {
317     /// Get the `LintId` for a `Lint`.
318     pub fn of(lint: &'static Lint) -> LintId {
319         LintId {
320             lint,
321         }
322     }
323
324     pub fn lint_name_raw(&self) -> &'static str {
325         self.lint.name
326     }
327
328     /// Get the name of the lint.
329     pub fn to_string(&self) -> String {
330         self.lint.name_lower()
331     }
332 }
333
334 /// Setting for how to handle a lint.
335 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
336 pub enum Level {
337     Allow, Warn, Deny, Forbid,
338 }
339
340 impl_stable_hash_for!(enum self::Level {
341     Allow,
342     Warn,
343     Deny,
344     Forbid
345 });
346
347 impl Level {
348     /// Convert a level to a lower-case string.
349     pub fn as_str(self) -> &'static str {
350         match self {
351             Allow => "allow",
352             Warn => "warn",
353             Deny => "deny",
354             Forbid => "forbid",
355         }
356     }
357
358     /// Convert a lower-case string to a level.
359     pub fn from_str(x: &str) -> Option<Level> {
360         match x {
361             "allow" => Some(Allow),
362             "warn" => Some(Warn),
363             "deny" => Some(Deny),
364             "forbid" => Some(Forbid),
365             _ => None,
366         }
367     }
368 }
369
370 /// How a lint level was set.
371 #[derive(Clone, Copy, PartialEq, Eq)]
372 pub enum LintSource {
373     /// Lint is at the default level as declared
374     /// in rustc or a plugin.
375     Default,
376
377     /// Lint level was set by an attribute.
378     Node(ast::Name, Span),
379
380     /// Lint level was set by a command-line flag.
381     CommandLine(Symbol),
382 }
383
384 impl_stable_hash_for!(enum self::LintSource {
385     Default,
386     Node(name, span),
387     CommandLine(text)
388 });
389
390 pub type LevelSource = (Level, LintSource);
391
392 pub mod builtin;
393 mod context;
394 mod levels;
395
396 pub use self::levels::{LintLevelSets, LintLevelMap};
397
398 pub struct LintBuffer {
399     map: NodeMap<Vec<BufferedEarlyLint>>,
400 }
401
402 impl LintBuffer {
403     pub fn new() -> LintBuffer {
404         LintBuffer { map: NodeMap() }
405     }
406
407     pub fn add_lint(&mut self,
408                     lint: &'static Lint,
409                     id: ast::NodeId,
410                     sp: MultiSpan,
411                     msg: &str,
412                     diagnostic: BuiltinLintDiagnostics) {
413         let early_lint = BufferedEarlyLint {
414             lint_id: LintId::of(lint),
415             ast_id: id,
416             span: sp,
417             msg: msg.to_string(),
418             diagnostic
419         };
420         let arr = self.map.entry(id).or_insert(Vec::new());
421         if !arr.contains(&early_lint) {
422             arr.push(early_lint);
423         }
424     }
425
426     pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
427         self.map.remove(&id).unwrap_or(Vec::new())
428     }
429
430     pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
431         let key = self.map.keys().next().map(|k| *k);
432         key.map(|k| &self.map[&k][..])
433     }
434 }
435
436 pub fn struct_lint_level<'a>(sess: &'a Session,
437                              lint: &'static Lint,
438                              level: Level,
439                              src: LintSource,
440                              span: Option<MultiSpan>,
441                              msg: &str)
442     -> DiagnosticBuilder<'a>
443 {
444     let mut err = match (level, span) {
445         (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
446         (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
447         (Level::Warn, None) => sess.struct_warn(msg),
448         (Level::Deny, Some(span)) |
449         (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
450         (Level::Deny, None) |
451         (Level::Forbid, None) => sess.struct_err(msg),
452     };
453
454     let name = lint.name_lower();
455     match src {
456         LintSource::Default => {
457             sess.diag_note_once(
458                 &mut err,
459                 DiagnosticMessageId::from(lint),
460                 &format!("#[{}({})] on by default", level.as_str(), name));
461         }
462         LintSource::CommandLine(lint_flag_val) => {
463             let flag = match level {
464                 Level::Warn => "-W",
465                 Level::Deny => "-D",
466                 Level::Forbid => "-F",
467                 Level::Allow => panic!(),
468             };
469             let hyphen_case_lint_name = name.replace("_", "-");
470             if lint_flag_val.as_str() == name {
471                 sess.diag_note_once(
472                     &mut err,
473                     DiagnosticMessageId::from(lint),
474                     &format!("requested on the command line with `{} {}`",
475                              flag, hyphen_case_lint_name));
476             } else {
477                 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
478                 sess.diag_note_once(
479                     &mut err,
480                     DiagnosticMessageId::from(lint),
481                     &format!("`{} {}` implied by `{} {}`",
482                              flag, hyphen_case_lint_name, flag,
483                              hyphen_case_flag_val));
484             }
485         }
486         LintSource::Node(lint_attr_name, src) => {
487             sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
488                                      src, "lint level defined here");
489             if lint_attr_name.as_str() != name {
490                 let level_str = level.as_str();
491                 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
492                                     &format!("#[{}({})] implied by #[{}({})]",
493                                              level_str, name, level_str, lint_attr_name));
494             }
495         }
496     }
497
498     err.code(DiagnosticId::Lint(name));
499
500     // Check for future incompatibility lints and issue a stronger warning.
501     let lints = sess.lint_store.borrow();
502     let lint_id = LintId::of(lint);
503     if let Some(future_incompatible) = lints.future_incompatible(lint_id) {
504         const STANDARD_MESSAGE: &str =
505             "this was previously accepted by the compiler but is being phased out; \
506              it will become a hard error";
507
508         let explanation = if lint_id == LintId::of(::lint::builtin::UNSTABLE_NAME_COLLISION) {
509             "once this method is added to the standard library, \
510              there will be ambiguity here, which will cause a hard error!"
511                 .to_owned()
512         } else if let Some(edition) = future_incompatible.edition {
513             format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
514         } else {
515             format!("{} in a future release!", STANDARD_MESSAGE)
516         };
517         let citation = format!("for more information, see {}",
518                                future_incompatible.reference);
519         err.warn(&explanation);
520         err.note(&citation);
521     }
522
523     return err
524 }
525
526 fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
527     -> Lrc<LintLevelMap>
528 {
529     assert_eq!(cnum, LOCAL_CRATE);
530     let mut builder = LintLevelMapBuilder {
531         levels: LintLevelSets::builder(tcx.sess),
532         tcx: tcx,
533     };
534     let krate = tcx.hir.krate();
535
536     builder.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |builder| {
537         intravisit::walk_crate(builder, krate);
538     });
539
540     Lrc::new(builder.levels.build_map())
541 }
542
543 struct LintLevelMapBuilder<'a, 'tcx: 'a> {
544     levels: levels::LintLevelsBuilder<'tcx>,
545     tcx: TyCtxt<'a, 'tcx, 'tcx>,
546 }
547
548 impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
549     fn with_lint_attrs<F>(&mut self,
550                           id: ast::NodeId,
551                           attrs: &[ast::Attribute],
552                           f: F)
553         where F: FnOnce(&mut Self)
554     {
555         let push = self.levels.push(attrs);
556         self.levels.register_id(self.tcx.hir.definitions().node_to_hir_id(id));
557         f(self);
558         self.levels.pop(push);
559     }
560 }
561
562 impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
563     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
564         intravisit::NestedVisitorMap::All(&self.tcx.hir)
565     }
566
567     fn visit_item(&mut self, it: &'tcx hir::Item) {
568         self.with_lint_attrs(it.id, &it.attrs, |builder| {
569             intravisit::walk_item(builder, it);
570         });
571     }
572
573     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
574         self.with_lint_attrs(it.id, &it.attrs, |builder| {
575             intravisit::walk_foreign_item(builder, it);
576         })
577     }
578
579     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
580         self.with_lint_attrs(e.id, &e.attrs, |builder| {
581             intravisit::walk_expr(builder, e);
582         })
583     }
584
585     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
586         self.with_lint_attrs(s.id, &s.attrs, |builder| {
587             intravisit::walk_struct_field(builder, s);
588         })
589     }
590
591     fn visit_variant(&mut self,
592                      v: &'tcx hir::Variant,
593                      g: &'tcx hir::Generics,
594                      item_id: ast::NodeId) {
595         self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |builder| {
596             intravisit::walk_variant(builder, v, g, item_id);
597         })
598     }
599
600     fn visit_local(&mut self, l: &'tcx hir::Local) {
601         self.with_lint_attrs(l.id, &l.attrs, |builder| {
602             intravisit::walk_local(builder, l);
603         })
604     }
605
606     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
607         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |builder| {
608             intravisit::walk_trait_item(builder, trait_item);
609         });
610     }
611
612     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
613         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |builder| {
614             intravisit::walk_impl_item(builder, impl_item);
615         });
616     }
617 }
618
619 pub fn provide(providers: &mut Providers) {
620     providers.lint_levels = lint_levels;
621 }