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