]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/mod.rs
Rollup merge of #55926 - cynecx:fix-rustdoc-mobile-css, r=GuillaumeGomez
[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 pub struct LintBuffer {
494     map: NodeMap<Vec<BufferedEarlyLint>>,
495 }
496
497 impl LintBuffer {
498     pub fn new() -> LintBuffer {
499         LintBuffer { map: NodeMap() }
500     }
501
502     pub fn add_lint(&mut self,
503                     lint: &'static Lint,
504                     id: ast::NodeId,
505                     sp: MultiSpan,
506                     msg: &str,
507                     diagnostic: BuiltinLintDiagnostics) {
508         let early_lint = BufferedEarlyLint {
509             lint_id: LintId::of(lint),
510             ast_id: id,
511             span: sp,
512             msg: msg.to_string(),
513             diagnostic
514         };
515         let arr = self.map.entry(id).or_default();
516         if !arr.contains(&early_lint) {
517             arr.push(early_lint);
518         }
519     }
520
521     pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
522         self.map.remove(&id).unwrap_or_default()
523     }
524
525     pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
526         let key = self.map.keys().next().map(|k| *k);
527         key.map(|k| &self.map[&k][..])
528     }
529 }
530
531 pub fn struct_lint_level<'a>(sess: &'a Session,
532                              lint: &'static Lint,
533                              level: Level,
534                              src: LintSource,
535                              span: Option<MultiSpan>,
536                              msg: &str)
537     -> DiagnosticBuilder<'a>
538 {
539     let mut err = match (level, span) {
540         (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
541         (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
542         (Level::Warn, None) => sess.struct_warn(msg),
543         (Level::Deny, Some(span)) |
544         (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
545         (Level::Deny, None) |
546         (Level::Forbid, None) => sess.struct_err(msg),
547     };
548
549     let name = lint.name_lower();
550     match src {
551         LintSource::Default => {
552             sess.diag_note_once(
553                 &mut err,
554                 DiagnosticMessageId::from(lint),
555                 &format!("#[{}({})] on by default", level.as_str(), name));
556         }
557         LintSource::CommandLine(lint_flag_val) => {
558             let flag = match level {
559                 Level::Warn => "-W",
560                 Level::Deny => "-D",
561                 Level::Forbid => "-F",
562                 Level::Allow => panic!(),
563             };
564             let hyphen_case_lint_name = name.replace("_", "-");
565             if lint_flag_val.as_str() == name {
566                 sess.diag_note_once(
567                     &mut err,
568                     DiagnosticMessageId::from(lint),
569                     &format!("requested on the command line with `{} {}`",
570                              flag, hyphen_case_lint_name));
571             } else {
572                 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
573                 sess.diag_note_once(
574                     &mut err,
575                     DiagnosticMessageId::from(lint),
576                     &format!("`{} {}` implied by `{} {}`",
577                              flag, hyphen_case_lint_name, flag,
578                              hyphen_case_flag_val));
579             }
580         }
581         LintSource::Node(lint_attr_name, src, reason) => {
582             if let Some(rationale) = reason {
583                 err.note(&rationale.as_str());
584             }
585             sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
586                                      src, "lint level defined here");
587             if lint_attr_name.as_str() != name {
588                 let level_str = level.as_str();
589                 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
590                                     &format!("#[{}({})] implied by #[{}({})]",
591                                              level_str, name, level_str, lint_attr_name));
592             }
593         }
594     }
595
596     err.code(DiagnosticId::Lint(name));
597
598     // Check for future incompatibility lints and issue a stronger warning.
599     let lints = sess.lint_store.borrow();
600     let lint_id = LintId::of(lint);
601     let future_incompatible = lints.future_incompatible(lint_id);
602     if let Some(future_incompatible) = future_incompatible {
603         const STANDARD_MESSAGE: &str =
604             "this was previously accepted by the compiler but is being phased out; \
605              it will become a hard error";
606
607         let explanation = if lint_id == LintId::of(::lint::builtin::UNSTABLE_NAME_COLLISIONS) {
608             "once this method is added to the standard library, \
609              the ambiguity may cause an error or change in behavior!"
610                 .to_owned()
611         } else if let Some(edition) = future_incompatible.edition {
612             format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
613         } else {
614             format!("{} in a future release!", STANDARD_MESSAGE)
615         };
616         let citation = format!("for more information, see {}",
617                                future_incompatible.reference);
618         err.warn(&explanation);
619         err.note(&citation);
620     }
621
622     // If this code originates in a foreign macro, aka something that this crate
623     // did not itself author, then it's likely that there's nothing this crate
624     // can do about it. We probably want to skip the lint entirely.
625     if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
626         // Any suggestions made here are likely to be incorrect, so anything we
627         // emit shouldn't be automatically fixed by rustfix.
628         err.allow_suggestions(false);
629
630         // If this is a future incompatible lint it'll become a hard error, so
631         // we have to emit *something*. Also allow lints to whitelist themselves
632         // on a case-by-case basis for emission in a foreign macro.
633         if future_incompatible.is_none() && !lint.report_in_external_macro {
634             err.cancel()
635         }
636     }
637
638     return err
639 }
640
641 fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
642     -> Lrc<LintLevelMap>
643 {
644     assert_eq!(cnum, LOCAL_CRATE);
645     let mut builder = LintLevelMapBuilder {
646         levels: LintLevelSets::builder(tcx.sess),
647         tcx: tcx,
648     };
649     let krate = tcx.hir.krate();
650
651     builder.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |builder| {
652         intravisit::walk_crate(builder, krate);
653     });
654
655     Lrc::new(builder.levels.build_map())
656 }
657
658 struct LintLevelMapBuilder<'a, 'tcx: 'a> {
659     levels: levels::LintLevelsBuilder<'tcx>,
660     tcx: TyCtxt<'a, 'tcx, 'tcx>,
661 }
662
663 impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
664     fn with_lint_attrs<F>(&mut self,
665                           id: ast::NodeId,
666                           attrs: &[ast::Attribute],
667                           f: F)
668         where F: FnOnce(&mut Self)
669     {
670         let push = self.levels.push(attrs);
671         self.levels.register_id(self.tcx.hir.definitions().node_to_hir_id(id));
672         f(self);
673         self.levels.pop(push);
674     }
675 }
676
677 impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
678     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
679         intravisit::NestedVisitorMap::All(&self.tcx.hir)
680     }
681
682     fn visit_item(&mut self, it: &'tcx hir::Item) {
683         self.with_lint_attrs(it.id, &it.attrs, |builder| {
684             intravisit::walk_item(builder, it);
685         });
686     }
687
688     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
689         self.with_lint_attrs(it.id, &it.attrs, |builder| {
690             intravisit::walk_foreign_item(builder, it);
691         })
692     }
693
694     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
695         self.with_lint_attrs(e.id, &e.attrs, |builder| {
696             intravisit::walk_expr(builder, e);
697         })
698     }
699
700     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
701         self.with_lint_attrs(s.id, &s.attrs, |builder| {
702             intravisit::walk_struct_field(builder, s);
703         })
704     }
705
706     fn visit_variant(&mut self,
707                      v: &'tcx hir::Variant,
708                      g: &'tcx hir::Generics,
709                      item_id: ast::NodeId) {
710         self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |builder| {
711             intravisit::walk_variant(builder, v, g, item_id);
712         })
713     }
714
715     fn visit_local(&mut self, l: &'tcx hir::Local) {
716         self.with_lint_attrs(l.id, &l.attrs, |builder| {
717             intravisit::walk_local(builder, l);
718         })
719     }
720
721     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
722         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |builder| {
723             intravisit::walk_trait_item(builder, trait_item);
724         });
725     }
726
727     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
728         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |builder| {
729             intravisit::walk_impl_item(builder, impl_item);
730         });
731     }
732 }
733
734 pub fn provide(providers: &mut Providers<'_>) {
735     providers.lint_levels = lint_levels;
736 }
737
738 /// Returns whether `span` originates in a foreign crate's external macro.
739 ///
740 /// This is used to test whether a lint should be entirely aborted above.
741 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
742     let info = match span.ctxt().outer().expn_info() {
743         Some(info) => info,
744         // no ExpnInfo means this span doesn't come from a macro
745         None => return false,
746     };
747
748     match info.format {
749         ExpnFormat::MacroAttribute(..) => return true, // definitely a plugin
750         ExpnFormat::CompilerDesugaring(_) => return true, // well, it's "external"
751         ExpnFormat::MacroBang(..) => {} // check below
752     }
753
754     let def_site = match info.def_site {
755         Some(span) => span,
756         // no span for the def_site means it's an external macro
757         None => return true,
758     };
759
760     match sess.source_map().span_to_snippet(def_site) {
761         Ok(code) => !code.starts_with("macro_rules"),
762         // no snippet = external macro or compiler-builtin expansion
763         Err(_) => true,
764     }
765 }