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