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