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