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