]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/mod.rs
Revert some use of `PtrKey` to fix parallel_queries build
[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, ptr};
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     fn check_mac_def(&mut self, _: &EarlyContext, _: &ast::MacroDef, _id: ast::NodeId) { }
331     fn check_mac(&mut self, _: &EarlyContext, _: &ast::Mac) { }
332
333     /// Called when entering a syntax node that can have lint attributes such
334     /// as `#[allow(...)]`. Called with *all* the attributes of that node.
335     fn enter_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
336
337     /// Counterpart to `enter_lint_attrs`.
338     fn exit_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
339 }
340
341 /// A lint pass boxed up as a trait object.
342 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
343 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
344                                                                            + sync::Sync + 'static>;
345
346
347
348 /// Identifies a lint known to the compiler.
349 #[derive(Clone, Copy, Debug)]
350 pub struct LintId {
351     // Identity is based on pointer equality of this field.
352     lint: &'static Lint,
353 }
354
355 impl PartialEq for LintId {
356     fn eq(&self, other: &LintId) -> bool {
357         ptr::eq(self.lint, other.lint)
358     }
359 }
360
361 impl Eq for LintId { }
362
363 impl hash::Hash for LintId {
364     fn hash<H: hash::Hasher>(&self, state: &mut H) {
365         let ptr = self.lint as *const Lint;
366         ptr.hash(state);
367     }
368 }
369
370 impl LintId {
371     /// Get the `LintId` for a `Lint`.
372     pub fn of(lint: &'static Lint) -> LintId {
373         LintId {
374             lint,
375         }
376     }
377
378     pub fn lint_name_raw(&self) -> &'static str {
379         self.lint.name
380     }
381
382     /// Get the name of the lint.
383     pub fn to_string(&self) -> String {
384         self.lint.name_lower()
385     }
386 }
387
388 /// Setting for how to handle a lint.
389 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
390 pub enum Level {
391     Allow, Warn, Deny, Forbid,
392 }
393
394 impl_stable_hash_for!(enum self::Level {
395     Allow,
396     Warn,
397     Deny,
398     Forbid
399 });
400
401 impl Level {
402     /// Convert a level to a lower-case string.
403     pub fn as_str(self) -> &'static str {
404         match self {
405             Allow => "allow",
406             Warn => "warn",
407             Deny => "deny",
408             Forbid => "forbid",
409         }
410     }
411
412     /// Convert a lower-case string to a level.
413     pub fn from_str(x: &str) -> Option<Level> {
414         match x {
415             "allow" => Some(Allow),
416             "warn" => Some(Warn),
417             "deny" => Some(Deny),
418             "forbid" => Some(Forbid),
419             _ => None,
420         }
421     }
422 }
423
424 /// How a lint level was set.
425 #[derive(Clone, Copy, PartialEq, Eq)]
426 pub enum LintSource {
427     /// Lint is at the default level as declared
428     /// in rustc or a plugin.
429     Default,
430
431     /// Lint level was set by an attribute.
432     Node(ast::Name, Span),
433
434     /// Lint level was set by a command-line flag.
435     CommandLine(Symbol),
436 }
437
438 impl_stable_hash_for!(enum self::LintSource {
439     Default,
440     Node(name, span),
441     CommandLine(text)
442 });
443
444 pub type LevelSource = (Level, LintSource);
445
446 pub mod builtin;
447 mod context;
448 mod levels;
449
450 pub use self::levels::{LintLevelSets, LintLevelMap};
451
452 pub struct LintBuffer {
453     map: NodeMap<Vec<BufferedEarlyLint>>,
454 }
455
456 impl LintBuffer {
457     pub fn new() -> LintBuffer {
458         LintBuffer { map: NodeMap() }
459     }
460
461     pub fn add_lint(&mut self,
462                     lint: &'static Lint,
463                     id: ast::NodeId,
464                     sp: MultiSpan,
465                     msg: &str,
466                     diagnostic: BuiltinLintDiagnostics) {
467         let early_lint = BufferedEarlyLint {
468             lint_id: LintId::of(lint),
469             ast_id: id,
470             span: sp,
471             msg: msg.to_string(),
472             diagnostic
473         };
474         let arr = self.map.entry(id).or_insert(Vec::new());
475         if !arr.contains(&early_lint) {
476             arr.push(early_lint);
477         }
478     }
479
480     pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
481         self.map.remove(&id).unwrap_or(Vec::new())
482     }
483
484     pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
485         let key = self.map.keys().next().map(|k| *k);
486         key.map(|k| &self.map[&k][..])
487     }
488 }
489
490 pub fn struct_lint_level<'a>(sess: &'a Session,
491                              lint: &'static Lint,
492                              level: Level,
493                              src: LintSource,
494                              span: Option<MultiSpan>,
495                              msg: &str)
496     -> DiagnosticBuilder<'a>
497 {
498     let mut err = match (level, span) {
499         (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
500         (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
501         (Level::Warn, None) => sess.struct_warn(msg),
502         (Level::Deny, Some(span)) |
503         (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
504         (Level::Deny, None) |
505         (Level::Forbid, None) => sess.struct_err(msg),
506     };
507
508     let name = lint.name_lower();
509     match src {
510         LintSource::Default => {
511             sess.diag_note_once(
512                 &mut err,
513                 DiagnosticMessageId::from(lint),
514                 &format!("#[{}({})] on by default", level.as_str(), name));
515         }
516         LintSource::CommandLine(lint_flag_val) => {
517             let flag = match level {
518                 Level::Warn => "-W",
519                 Level::Deny => "-D",
520                 Level::Forbid => "-F",
521                 Level::Allow => panic!(),
522             };
523             let hyphen_case_lint_name = name.replace("_", "-");
524             if lint_flag_val.as_str() == name {
525                 sess.diag_note_once(
526                     &mut err,
527                     DiagnosticMessageId::from(lint),
528                     &format!("requested on the command line with `{} {}`",
529                              flag, hyphen_case_lint_name));
530             } else {
531                 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
532                 sess.diag_note_once(
533                     &mut err,
534                     DiagnosticMessageId::from(lint),
535                     &format!("`{} {}` implied by `{} {}`",
536                              flag, hyphen_case_lint_name, flag,
537                              hyphen_case_flag_val));
538             }
539         }
540         LintSource::Node(lint_attr_name, src) => {
541             sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
542                                      src, "lint level defined here");
543             if lint_attr_name.as_str() != name {
544                 let level_str = level.as_str();
545                 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
546                                     &format!("#[{}({})] implied by #[{}({})]",
547                                              level_str, name, level_str, lint_attr_name));
548             }
549         }
550     }
551
552     err.code(DiagnosticId::Lint(name));
553
554     // Check for future incompatibility lints and issue a stronger warning.
555     let lints = sess.lint_store.borrow();
556     let lint_id = LintId::of(lint);
557     if let Some(future_incompatible) = lints.future_incompatible(lint_id) {
558         const STANDARD_MESSAGE: &str =
559             "this was previously accepted by the compiler but is being phased out; \
560              it will become a hard error";
561
562         let explanation = if lint_id == LintId::of(::lint::builtin::UNSTABLE_NAME_COLLISIONS) {
563             "once this method is added to the standard library, \
564              the ambiguity may cause an error or change in behavior!"
565                 .to_owned()
566         } else if let Some(edition) = future_incompatible.edition {
567             format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
568         } else {
569             format!("{} in a future release!", STANDARD_MESSAGE)
570         };
571         let citation = format!("for more information, see {}",
572                                future_incompatible.reference);
573         err.warn(&explanation);
574         err.note(&citation);
575     }
576
577     return err
578 }
579
580 fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
581     -> Lrc<LintLevelMap>
582 {
583     assert_eq!(cnum, LOCAL_CRATE);
584     let mut builder = LintLevelMapBuilder {
585         levels: LintLevelSets::builder(tcx.sess),
586         tcx: tcx,
587     };
588     let krate = tcx.hir.krate();
589
590     builder.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |builder| {
591         intravisit::walk_crate(builder, krate);
592     });
593
594     Lrc::new(builder.levels.build_map())
595 }
596
597 struct LintLevelMapBuilder<'a, 'tcx: 'a> {
598     levels: levels::LintLevelsBuilder<'tcx>,
599     tcx: TyCtxt<'a, 'tcx, 'tcx>,
600 }
601
602 impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
603     fn with_lint_attrs<F>(&mut self,
604                           id: ast::NodeId,
605                           attrs: &[ast::Attribute],
606                           f: F)
607         where F: FnOnce(&mut Self)
608     {
609         let push = self.levels.push(attrs);
610         self.levels.register_id(self.tcx.hir.definitions().node_to_hir_id(id));
611         f(self);
612         self.levels.pop(push);
613     }
614 }
615
616 impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
617     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
618         intravisit::NestedVisitorMap::All(&self.tcx.hir)
619     }
620
621     fn visit_item(&mut self, it: &'tcx hir::Item) {
622         self.with_lint_attrs(it.id, &it.attrs, |builder| {
623             intravisit::walk_item(builder, it);
624         });
625     }
626
627     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
628         self.with_lint_attrs(it.id, &it.attrs, |builder| {
629             intravisit::walk_foreign_item(builder, it);
630         })
631     }
632
633     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
634         self.with_lint_attrs(e.id, &e.attrs, |builder| {
635             intravisit::walk_expr(builder, e);
636         })
637     }
638
639     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
640         self.with_lint_attrs(s.id, &s.attrs, |builder| {
641             intravisit::walk_struct_field(builder, s);
642         })
643     }
644
645     fn visit_variant(&mut self,
646                      v: &'tcx hir::Variant,
647                      g: &'tcx hir::Generics,
648                      item_id: ast::NodeId) {
649         self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |builder| {
650             intravisit::walk_variant(builder, v, g, item_id);
651         })
652     }
653
654     fn visit_local(&mut self, l: &'tcx hir::Local) {
655         self.with_lint_attrs(l.id, &l.attrs, |builder| {
656             intravisit::walk_local(builder, l);
657         })
658     }
659
660     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
661         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |builder| {
662             intravisit::walk_trait_item(builder, trait_item);
663         });
664     }
665
666     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
667         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |builder| {
668             intravisit::walk_impl_item(builder, impl_item);
669         });
670     }
671 }
672
673 pub fn provide(providers: &mut Providers) {
674     providers.lint_levels = lint_levels;
675 }