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