]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/mod.rs
Auto merge of #66547 - leo60228:procfs-fallback, r=dtolnay
[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::symbol::{Symbol, sym};
43 use syntax_pos::hygiene::MacroKind;
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, HashStable)]
547 pub enum Level {
548     Allow, Warn, Deny, Forbid,
549 }
550
551 impl Level {
552     /// Converts a level to a lower-case string.
553     pub fn as_str(self) -> &'static str {
554         match self {
555             Allow => "allow",
556             Warn => "warn",
557             Deny => "deny",
558             Forbid => "forbid",
559         }
560     }
561
562     /// Converts a lower-case string to a level.
563     pub fn from_str(x: &str) -> Option<Level> {
564         match x {
565             "allow" => Some(Allow),
566             "warn" => Some(Warn),
567             "deny" => Some(Deny),
568             "forbid" => Some(Forbid),
569             _ => None,
570         }
571     }
572
573     /// Converts a symbol to a level.
574     pub fn from_symbol(x: Symbol) -> Option<Level> {
575         match x {
576             sym::allow => Some(Allow),
577             sym::warn => Some(Warn),
578             sym::deny => Some(Deny),
579             sym::forbid => Some(Forbid),
580             _ => None,
581         }
582     }
583 }
584
585 /// How a lint level was set.
586 #[derive(Clone, Copy, PartialEq, Eq, HashStable)]
587 pub enum LintSource {
588     /// Lint is at the default level as declared
589     /// in rustc or a plugin.
590     Default,
591
592     /// Lint level was set by an attribute.
593     Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
594
595     /// Lint level was set by a command-line flag.
596     CommandLine(Symbol),
597 }
598
599 pub type LevelSource = (Level, LintSource);
600
601 pub mod builtin;
602 pub mod internal;
603 mod context;
604 mod levels;
605
606 pub use self::levels::{LintLevelSets, LintLevelMap};
607
608 #[derive(Default)]
609 pub struct LintBuffer {
610     map: NodeMap<Vec<BufferedEarlyLint>>,
611 }
612
613 impl LintBuffer {
614     pub fn add_lint(&mut self,
615                     lint: &'static Lint,
616                     id: ast::NodeId,
617                     sp: MultiSpan,
618                     msg: &str,
619                     diagnostic: BuiltinLintDiagnostics) {
620         let early_lint = BufferedEarlyLint {
621             lint_id: LintId::of(lint),
622             ast_id: id,
623             span: sp,
624             msg: msg.to_string(),
625             diagnostic
626         };
627         let arr = self.map.entry(id).or_default();
628         if !arr.contains(&early_lint) {
629             arr.push(early_lint);
630         }
631     }
632
633     fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
634         self.map.remove(&id).unwrap_or_default()
635     }
636
637     pub fn buffer_lint<S: Into<MultiSpan>>(
638         &mut self,
639         lint: &'static Lint,
640         id: ast::NodeId,
641         sp: S,
642         msg: &str,
643     ) {
644         self.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
645     }
646
647     pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(
648         &mut self,
649         lint: &'static Lint,
650         id: ast::NodeId,
651         sp: S,
652         msg: &str,
653         diagnostic: BuiltinLintDiagnostics,
654     ) {
655         self.add_lint(lint, id, sp.into(), msg, diagnostic)
656     }
657 }
658
659 pub fn struct_lint_level<'a>(sess: &'a Session,
660                              lint: &'static Lint,
661                              level: Level,
662                              src: LintSource,
663                              span: Option<MultiSpan>,
664                              msg: &str)
665     -> DiagnosticBuilder<'a>
666 {
667     let mut err = match (level, span) {
668         (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
669         (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
670         (Level::Warn, None) => sess.struct_warn(msg),
671         (Level::Deny, Some(span)) |
672         (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
673         (Level::Deny, None) |
674         (Level::Forbid, None) => sess.struct_err(msg),
675     };
676
677     // Check for future incompatibility lints and issue a stronger warning.
678     let lint_id = LintId::of(lint);
679     let future_incompatible = lint.future_incompatible;
680
681     // If this code originates in a foreign macro, aka something that this crate
682     // did not itself author, then it's likely that there's nothing this crate
683     // can do about it. We probably want to skip the lint entirely.
684     if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
685         // Any suggestions made here are likely to be incorrect, so anything we
686         // emit shouldn't be automatically fixed by rustfix.
687         err.allow_suggestions(false);
688
689         // If this is a future incompatible lint it'll become a hard error, so
690         // we have to emit *something*. Also allow lints to whitelist themselves
691         // on a case-by-case basis for emission in a foreign macro.
692         if future_incompatible.is_none() && !lint.report_in_external_macro {
693             err.cancel();
694             // Don't continue further, since we don't want to have
695             // `diag_span_note_once` called for a diagnostic that isn't emitted.
696             return err;
697         }
698     }
699
700     let name = lint.name_lower();
701     match src {
702         LintSource::Default => {
703             sess.diag_note_once(
704                 &mut err,
705                 DiagnosticMessageId::from(lint),
706                 &format!("`#[{}({})]` on by default", level.as_str(), name));
707         }
708         LintSource::CommandLine(lint_flag_val) => {
709             let flag = match level {
710                 Level::Warn => "-W",
711                 Level::Deny => "-D",
712                 Level::Forbid => "-F",
713                 Level::Allow => panic!(),
714             };
715             let hyphen_case_lint_name = name.replace("_", "-");
716             if lint_flag_val.as_str() == name {
717                 sess.diag_note_once(
718                     &mut err,
719                     DiagnosticMessageId::from(lint),
720                     &format!("requested on the command line with `{} {}`",
721                              flag, hyphen_case_lint_name));
722             } else {
723                 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
724                 sess.diag_note_once(
725                     &mut err,
726                     DiagnosticMessageId::from(lint),
727                     &format!("`{} {}` implied by `{} {}`",
728                              flag, hyphen_case_lint_name, flag,
729                              hyphen_case_flag_val));
730             }
731         }
732         LintSource::Node(lint_attr_name, src, reason) => {
733             if let Some(rationale) = reason {
734                 err.note(&rationale.as_str());
735             }
736             sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
737                                      src, "lint level defined here");
738             if lint_attr_name.as_str() != name {
739                 let level_str = level.as_str();
740                 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
741                                     &format!("`#[{}({})]` implied by `#[{}({})]`",
742                                              level_str, name, level_str, lint_attr_name));
743             }
744         }
745     }
746
747     err.code(DiagnosticId::Lint(name));
748
749     if let Some(future_incompatible) = future_incompatible {
750         const STANDARD_MESSAGE: &str =
751             "this was previously accepted by the compiler but is being phased out; \
752              it will become a hard error";
753
754         let explanation = if lint_id == LintId::of(builtin::UNSTABLE_NAME_COLLISIONS) {
755             "once this method is added to the standard library, \
756              the ambiguity may cause an error or change in behavior!"
757                 .to_owned()
758         } else if lint_id == LintId::of(builtin::MUTABLE_BORROW_RESERVATION_CONFLICT) {
759             "this borrowing pattern was not meant to be accepted, \
760              and may become a hard error in the future"
761                 .to_owned()
762         } else if let Some(edition) = future_incompatible.edition {
763             format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
764         } else {
765             format!("{} in a future release!", STANDARD_MESSAGE)
766         };
767         let citation = format!("for more information, see {}",
768                                future_incompatible.reference);
769         err.warn(&explanation);
770         err.note(&citation);
771     }
772
773     return err
774 }
775
776 pub fn maybe_lint_level_root(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
777     let attrs = tcx.hir().attrs(id);
778     attrs.iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some())
779 }
780
781 fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> &LintLevelMap {
782     assert_eq!(cnum, LOCAL_CRATE);
783     let store = &tcx.lint_store;
784     let mut builder = LintLevelMapBuilder {
785         levels: LintLevelSets::builder(tcx.sess, false, &store),
786         tcx: tcx,
787         store: store,
788     };
789     let krate = tcx.hir().krate();
790
791     let push = builder.levels.push(&krate.attrs, &store);
792     builder.levels.register_id(hir::CRATE_HIR_ID);
793     for macro_def in &krate.exported_macros {
794        builder.levels.register_id(macro_def.hir_id);
795     }
796     intravisit::walk_crate(&mut builder, krate);
797     builder.levels.pop(push);
798
799     tcx.arena.alloc(builder.levels.build_map())
800 }
801
802 struct LintLevelMapBuilder<'a, 'tcx> {
803     levels: levels::LintLevelsBuilder<'tcx>,
804     tcx: TyCtxt<'tcx>,
805     store: &'a LintStore,
806 }
807
808 impl LintLevelMapBuilder<'_, '_> {
809     fn with_lint_attrs<F>(&mut self,
810                           id: hir::HirId,
811                           attrs: &[ast::Attribute],
812                           f: F)
813         where F: FnOnce(&mut Self)
814     {
815         let push = self.levels.push(attrs, self.store);
816         if push.changed {
817             self.levels.register_id(id);
818         }
819         f(self);
820         self.levels.pop(push);
821     }
822 }
823
824 impl intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> {
825     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
826         intravisit::NestedVisitorMap::All(&self.tcx.hir())
827     }
828
829     fn visit_param(&mut self, param: &'tcx hir::Param) {
830         self.with_lint_attrs(param.hir_id, &param.attrs, |builder| {
831             intravisit::walk_param(builder, param);
832         });
833     }
834
835     fn visit_item(&mut self, it: &'tcx hir::Item) {
836         self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
837             intravisit::walk_item(builder, it);
838         });
839     }
840
841     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
842         self.with_lint_attrs(it.hir_id, &it.attrs, |builder| {
843             intravisit::walk_foreign_item(builder, it);
844         })
845     }
846
847     fn visit_expr(&mut self, e: &'tcx hir::Expr) {
848         self.with_lint_attrs(e.hir_id, &e.attrs, |builder| {
849             intravisit::walk_expr(builder, e);
850         })
851     }
852
853     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
854         self.with_lint_attrs(s.hir_id, &s.attrs, |builder| {
855             intravisit::walk_struct_field(builder, s);
856         })
857     }
858
859     fn visit_variant(&mut self,
860                      v: &'tcx hir::Variant,
861                      g: &'tcx hir::Generics,
862                      item_id: hir::HirId) {
863         self.with_lint_attrs(v.id, &v.attrs, |builder| {
864             intravisit::walk_variant(builder, v, g, item_id);
865         })
866     }
867
868     fn visit_local(&mut self, l: &'tcx hir::Local) {
869         self.with_lint_attrs(l.hir_id, &l.attrs, |builder| {
870             intravisit::walk_local(builder, l);
871         })
872     }
873
874     fn visit_arm(&mut self, a: &'tcx hir::Arm) {
875         self.with_lint_attrs(a.hir_id, &a.attrs, |builder| {
876             intravisit::walk_arm(builder, a);
877         })
878     }
879
880     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
881         self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |builder| {
882             intravisit::walk_trait_item(builder, trait_item);
883         });
884     }
885
886     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
887         self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |builder| {
888             intravisit::walk_impl_item(builder, impl_item);
889         });
890     }
891 }
892
893 pub fn provide(providers: &mut Providers<'_>) {
894     providers.lint_levels = lint_levels;
895 }
896
897 /// Returns whether `span` originates in a foreign crate's external macro.
898 ///
899 /// This is used to test whether a lint should not even begin to figure out whether it should
900 /// be reported on the current node.
901 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
902     let expn_data = span.ctxt().outer_expn_data();
903     match expn_data.kind {
904         ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false,
905         ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
906         ExpnKind::Macro(MacroKind::Bang, _) => {
907             if expn_data.def_site.is_dummy() {
908                 // Dummy span for the `def_site` means it's an external macro.
909                 return true;
910             }
911             match sess.source_map().span_to_snippet(expn_data.def_site) {
912                 Ok(code) => !code.starts_with("macro_rules"),
913                 // No snippet means external macro or compiler-builtin expansion.
914                 Err(_) => true,
915             }
916         }
917         ExpnKind::Macro(..) => true, // definitely a plugin
918     }
919 }
920
921 /// Returns `true` if `span` originates in a derive-macro's expansion.
922 pub fn in_derive_expansion(span: Span) -> bool {
923     if let ExpnKind::Macro(MacroKind::Derive, _) = span.ctxt().outer_expn_data().kind {
924         return true;
925     }
926     false
927 }