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