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