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