1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Lints, aka compiler warnings.
13 //! A 'lint' check is a kind of miscellaneous constraint that a user _might_
14 //! want to enforce, but might reasonably want to permit as well, on a
15 //! module-by-module basis. They contrast with static constraints enforced by
16 //! other phases of the compiler, which are generally required to hold in order
17 //! to compile the program at all.
19 //! Most lints can be written as `LintPass` instances. These run after
20 //! all other analyses. The `LintPass`es built into rustc are defined
21 //! within `builtin.rs`, which has further comments on how to add such a lint.
22 //! rustc can also load user-defined lint plugins via the plugin mechanism.
24 //! Some of rustc's lints are defined elsewhere in the compiler and work by
25 //! calling `add_lint()` on the overall `Session` object. This works when
26 //! it happens before the main lint pass, which emits the lints stored by
27 //! `add_lint()`. To emit lints after the main lint pass (from codegen, for
28 //! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
31 pub use self::Level::*;
32 pub use self::LintSource::*;
34 use rustc_data_structures::sync::{self, Lrc};
36 use errors::{DiagnosticBuilder, DiagnosticId};
37 use hir::def_id::{CrateNum, LOCAL_CRATE};
40 use lint::builtin::BuiltinLintDiagnostics;
41 use lint::builtin::parser::QUESTION_MARK_MACRO_SEP;
42 use session::{Session, DiagnosticMessageId};
45 use syntax::source_map::{MultiSpan, ExpnFormat};
46 use syntax::early_buffered_lints::BufferedEarlyLintId;
47 use syntax::edition::Edition;
48 use syntax::symbol::Symbol;
49 use syntax::visit as ast_visit;
52 use ty::query::Providers;
53 use util::nodemap::NodeMap;
55 pub use lint::context::{LateContext, EarlyContext, LintContext, LintStore,
56 check_crate, check_ast_crate, CheckLintNameResult,
57 FutureIncompatibleInfo, BufferedEarlyLint};
59 /// Specification of a single lint.
60 #[derive(Copy, Clone, Debug)]
62 /// A string identifier for the lint.
64 /// This identifies the lint in attributes and in command-line arguments.
65 /// In those contexts it is always lowercase, but this field is compared
66 /// in a way which is case-insensitive for ASCII characters. This allows
67 /// `declare_lint!()` invocations to follow the convention of upper-case
68 /// statics without repeating the name.
70 /// The name is written with underscores, e.g. "unused_imports".
71 /// On the command line, underscores become dashes.
72 pub name: &'static str,
74 /// Default level for the lint.
75 pub default_level: Level,
77 /// Description of the lint or the issue it detects.
79 /// e.g. "imports that are never used"
80 pub desc: &'static str,
82 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
84 pub edition_lint_opts: Option<(Edition, Level)>,
86 /// Whether this lint is reported even inside expansions of external macros
87 pub report_in_external_macro: bool,
91 /// Returns the `rust::lint::Lint` for a `syntax::early_buffered_lints::BufferedEarlyLintId`.
92 pub fn from_parser_lint_id(lint_id: BufferedEarlyLintId) -> &'static Self {
94 BufferedEarlyLintId::QuestionMarkMacroSep => QUESTION_MARK_MACRO_SEP,
98 /// Get the lint's name, with ASCII letters converted to lowercase.
99 pub fn name_lower(&self) -> String {
100 self.name.to_ascii_lowercase()
103 pub fn default_level(&self, session: &Session) -> Level {
104 self.edition_lint_opts
105 .filter(|(e, _)| *e <= session.edition())
107 .unwrap_or(self.default_level)
111 /// Declare a static item of type `&'static Lint`.
113 macro_rules! declare_lint {
114 ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
115 declare_lint!{$vis $NAME, $Level, $desc, false}
117 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, report_in_external_macro: $rep: expr) => (
118 declare_lint!{$vis $NAME, $Level, $desc, $rep}
120 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, $external: expr) => (
121 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
122 name: stringify!($NAME),
123 default_level: $crate::lint::$Level,
125 edition_lint_opts: None,
126 report_in_external_macro: $external,
129 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
130 $lint_edition: expr => $edition_level: ident
132 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
133 name: stringify!($NAME),
134 default_level: $crate::lint::$Level,
136 edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
137 report_in_external_macro: false,
143 macro_rules! declare_tool_lint {
144 ($vis: vis $tool: ident ::$NAME: ident, $Level: ident, $desc: expr) => (
145 declare_tool_lint!{$vis $tool::$NAME, $Level, $desc, false}
147 ($vis: vis $tool: ident ::$NAME: ident, $Level: ident, $desc: expr,
148 report_in_external_macro: $rep: expr) => (
149 declare_tool_lint!{$vis $tool::$NAME, $Level, $desc, $rep}
151 ($vis: vis $tool: ident ::$NAME: ident, $Level: ident, $desc: expr, $external: expr) => (
152 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
153 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
154 default_level: $crate::lint::$Level,
156 edition_lint_opts: None,
157 report_in_external_macro: $external,
162 /// Declare a static `LintArray` and return it as an expression.
164 macro_rules! lint_array {
165 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
166 ($( $lint:expr ),*) => {{
171 pub type LintArray = Vec<&'static Lint>;
174 /// Get descriptions of the lints this `LintPass` object can emit.
176 /// NB: 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;
184 macro_rules! late_lint_methods {
185 ($macro:path, $args:tt, [$hir:tt]) => (
186 $macro!($args, [$hir], [
187 fn check_body(a: &$hir hir::Body);
188 fn check_body_post(a: &$hir hir::Body);
189 fn check_name(a: Span, b: ast::Name);
190 fn check_crate(a: &$hir hir::Crate);
191 fn check_crate_post(a: &$hir hir::Crate);
192 fn check_mod(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
193 fn check_mod_post(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
194 fn check_foreign_item(a: &$hir hir::ForeignItem);
195 fn check_foreign_item_post(a: &$hir hir::ForeignItem);
196 fn check_item(a: &$hir hir::Item);
197 fn check_item_post(a: &$hir hir::Item);
198 fn check_local(a: &$hir hir::Local);
199 fn check_block(a: &$hir hir::Block);
200 fn check_block_post(a: &$hir hir::Block);
201 fn check_stmt(a: &$hir hir::Stmt);
202 fn check_arm(a: &$hir hir::Arm);
203 fn check_pat(a: &$hir hir::Pat);
204 fn check_decl(a: &$hir hir::Decl);
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);
213 a: hir::intravisit::FnKind<$hir>,
214 b: &$hir hir::FnDecl,
219 a: hir::intravisit::FnKind<$hir>,
220 b: &$hir hir::FnDecl,
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);
230 a: &$hir hir::VariantData,
232 c: &$hir hir::Generics,
235 fn check_struct_def_post(
236 a: &$hir hir::VariantData,
238 c: &$hir hir::Generics,
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);
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]);
252 /// Counterpart to `enter_lint_attrs`.
253 fn exit_lint_attrs(a: &$hir [ast::Attribute]);
258 /// Trait for types providing lint checks.
260 /// Each `check` method checks a single syntax node, and should not
261 /// invoke methods recursively (unlike `Visitor`). By default they
264 // FIXME: eliminate the duplication with `Visitor`. But this also
265 // contains a few lint-specific methods with no equivalent in `Visitor`.
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),*) {})*
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)*]);
281 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
284 macro_rules! expand_combined_late_lint_pass_method {
285 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
286 $($self.$passes.$name $params;)*
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),*));
300 macro_rules! declare_combined_late_lint_pass {
301 ([$name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
302 #[allow(non_snake_case)]
304 $($passes: $passes,)*
310 $($passes: $constructor,)*
315 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
316 expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
319 impl LintPass for $name {
320 fn get_lints(&self) -> LintArray {
321 let mut lints = Vec::new();
322 $(lints.extend_from_slice(&self.$passes.get_lints());)*
329 pub trait EarlyLintPass: LintPass {
330 fn check_ident(&mut self, _: &EarlyContext<'_>, _: ast::Ident) { }
331 fn check_crate(&mut self, _: &EarlyContext<'_>, _: &ast::Crate) { }
332 fn check_crate_post(&mut self, _: &EarlyContext<'_>, _: &ast::Crate) { }
333 fn check_mod(&mut self, _: &EarlyContext<'_>, _: &ast::Mod, _: Span, _: ast::NodeId) { }
334 fn check_mod_post(&mut self, _: &EarlyContext<'_>, _: &ast::Mod, _: Span, _: ast::NodeId) { }
335 fn check_foreign_item(&mut self, _: &EarlyContext<'_>, _: &ast::ForeignItem) { }
336 fn check_foreign_item_post(&mut self, _: &EarlyContext<'_>, _: &ast::ForeignItem) { }
337 fn check_item(&mut self, _: &EarlyContext<'_>, _: &ast::Item) { }
338 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &ast::Item) { }
339 fn check_local(&mut self, _: &EarlyContext<'_>, _: &ast::Local) { }
340 fn check_block(&mut self, _: &EarlyContext<'_>, _: &ast::Block) { }
341 fn check_block_post(&mut self, _: &EarlyContext<'_>, _: &ast::Block) { }
342 fn check_stmt(&mut self, _: &EarlyContext<'_>, _: &ast::Stmt) { }
343 fn check_arm(&mut self, _: &EarlyContext<'_>, _: &ast::Arm) { }
344 fn check_pat(&mut self, _: &EarlyContext<'_>, _: &ast::Pat) { }
345 fn check_expr(&mut self, _: &EarlyContext<'_>, _: &ast::Expr) { }
346 fn check_expr_post(&mut self, _: &EarlyContext<'_>, _: &ast::Expr) { }
347 fn check_ty(&mut self, _: &EarlyContext<'_>, _: &ast::Ty) { }
348 fn check_generic_param(&mut self, _: &EarlyContext<'_>, _: &ast::GenericParam) { }
349 fn check_generics(&mut self, _: &EarlyContext<'_>, _: &ast::Generics) { }
350 fn check_where_predicate(&mut self, _: &EarlyContext<'_>, _: &ast::WherePredicate) { }
351 fn check_poly_trait_ref(&mut self, _: &EarlyContext<'_>, _: &ast::PolyTraitRef,
352 _: &ast::TraitBoundModifier) { }
353 fn check_fn(&mut self, _: &EarlyContext<'_>,
354 _: ast_visit::FnKind<'_>, _: &ast::FnDecl, _: Span, _: ast::NodeId) { }
355 fn check_fn_post(&mut self, _: &EarlyContext<'_>,
356 _: ast_visit::FnKind<'_>, _: &ast::FnDecl, _: Span, _: ast::NodeId) { }
357 fn check_trait_item(&mut self, _: &EarlyContext<'_>, _: &ast::TraitItem) { }
358 fn check_trait_item_post(&mut self, _: &EarlyContext<'_>, _: &ast::TraitItem) { }
359 fn check_impl_item(&mut self, _: &EarlyContext<'_>, _: &ast::ImplItem) { }
360 fn check_impl_item_post(&mut self, _: &EarlyContext<'_>, _: &ast::ImplItem) { }
361 fn check_struct_def(&mut self, _: &EarlyContext<'_>,
362 _: &ast::VariantData, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
363 fn check_struct_def_post(&mut self, _: &EarlyContext<'_>,
364 _: &ast::VariantData, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
365 fn check_struct_field(&mut self, _: &EarlyContext<'_>, _: &ast::StructField) { }
366 fn check_variant(&mut self, _: &EarlyContext<'_>, _: &ast::Variant, _: &ast::Generics) { }
367 fn check_variant_post(&mut self, _: &EarlyContext<'_>, _: &ast::Variant, _: &ast::Generics) { }
368 fn check_lifetime(&mut self, _: &EarlyContext<'_>, _: &ast::Lifetime) { }
369 fn check_path(&mut self, _: &EarlyContext<'_>, _: &ast::Path, _: ast::NodeId) { }
370 fn check_attribute(&mut self, _: &EarlyContext<'_>, _: &ast::Attribute) { }
371 fn check_mac_def(&mut self, _: &EarlyContext<'_>, _: &ast::MacroDef, _id: ast::NodeId) { }
372 fn check_mac(&mut self, _: &EarlyContext<'_>, _: &ast::Mac) { }
374 /// Called when entering a syntax node that can have lint attributes such
375 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
376 fn enter_lint_attrs(&mut self, _: &EarlyContext<'_>, _: &[ast::Attribute]) { }
378 /// Counterpart to `enter_lint_attrs`.
379 fn exit_lint_attrs(&mut self, _: &EarlyContext<'_>, _: &[ast::Attribute]) { }
382 /// A lint pass boxed up as a trait object.
383 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
384 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
385 + sync::Sync + 'static>;
389 /// Identifies a lint known to the compiler.
390 #[derive(Clone, Copy, Debug)]
392 // Identity is based on pointer equality of this field.
396 impl PartialEq for LintId {
397 fn eq(&self, other: &LintId) -> bool {
398 ptr::eq(self.lint, other.lint)
402 impl Eq for LintId { }
404 impl hash::Hash for LintId {
405 fn hash<H: hash::Hasher>(&self, state: &mut H) {
406 let ptr = self.lint as *const Lint;
412 /// Get the `LintId` for a `Lint`.
413 pub fn of(lint: &'static Lint) -> LintId {
419 pub fn lint_name_raw(&self) -> &'static str {
423 /// Get the name of the lint.
424 pub fn to_string(&self) -> String {
425 self.lint.name_lower()
429 /// Setting for how to handle a lint.
430 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
432 Allow, Warn, Deny, Forbid,
435 impl_stable_hash_for!(enum self::Level {
443 /// Convert a level to a lower-case string.
444 pub fn as_str(self) -> &'static str {
453 /// Convert a lower-case string to a level.
454 pub fn from_str(x: &str) -> Option<Level> {
456 "allow" => Some(Allow),
457 "warn" => Some(Warn),
458 "deny" => Some(Deny),
459 "forbid" => Some(Forbid),
465 /// How a lint level was set.
466 #[derive(Clone, Copy, PartialEq, Eq)]
467 pub enum LintSource {
468 /// Lint is at the default level as declared
469 /// in rustc or a plugin.
472 /// Lint level was set by an attribute.
473 Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
475 /// Lint level was set by a command-line flag.
479 impl_stable_hash_for!(enum self::LintSource {
481 Node(name, span, reason),
485 pub type LevelSource = (Level, LintSource);
491 pub use self::levels::{LintLevelSets, LintLevelMap};
493 pub struct LintBuffer {
494 map: NodeMap<Vec<BufferedEarlyLint>>,
498 pub fn new() -> LintBuffer {
499 LintBuffer { map: NodeMap() }
502 pub fn add_lint(&mut self,
507 diagnostic: BuiltinLintDiagnostics) {
508 let early_lint = BufferedEarlyLint {
509 lint_id: LintId::of(lint),
512 msg: msg.to_string(),
515 let arr = self.map.entry(id).or_default();
516 if !arr.contains(&early_lint) {
517 arr.push(early_lint);
521 pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
522 self.map.remove(&id).unwrap_or_default()
525 pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
526 let key = self.map.keys().next().map(|k| *k);
527 key.map(|k| &self.map[&k][..])
531 pub fn struct_lint_level<'a>(sess: &'a Session,
535 span: Option<MultiSpan>,
537 -> DiagnosticBuilder<'a>
539 let mut err = match (level, span) {
540 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
541 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
542 (Level::Warn, None) => sess.struct_warn(msg),
543 (Level::Deny, Some(span)) |
544 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
545 (Level::Deny, None) |
546 (Level::Forbid, None) => sess.struct_err(msg),
549 let name = lint.name_lower();
551 LintSource::Default => {
554 DiagnosticMessageId::from(lint),
555 &format!("#[{}({})] on by default", level.as_str(), name));
557 LintSource::CommandLine(lint_flag_val) => {
558 let flag = match level {
561 Level::Forbid => "-F",
562 Level::Allow => panic!(),
564 let hyphen_case_lint_name = name.replace("_", "-");
565 if lint_flag_val.as_str() == name {
568 DiagnosticMessageId::from(lint),
569 &format!("requested on the command line with `{} {}`",
570 flag, hyphen_case_lint_name));
572 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
575 DiagnosticMessageId::from(lint),
576 &format!("`{} {}` implied by `{} {}`",
577 flag, hyphen_case_lint_name, flag,
578 hyphen_case_flag_val));
581 LintSource::Node(lint_attr_name, src, reason) => {
582 if let Some(rationale) = reason {
583 err.note(&rationale.as_str());
585 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
586 src, "lint level defined here");
587 if lint_attr_name.as_str() != name {
588 let level_str = level.as_str();
589 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
590 &format!("#[{}({})] implied by #[{}({})]",
591 level_str, name, level_str, lint_attr_name));
596 err.code(DiagnosticId::Lint(name));
598 // Check for future incompatibility lints and issue a stronger warning.
599 let lints = sess.lint_store.borrow();
600 let lint_id = LintId::of(lint);
601 let future_incompatible = lints.future_incompatible(lint_id);
602 if let Some(future_incompatible) = future_incompatible {
603 const STANDARD_MESSAGE: &str =
604 "this was previously accepted by the compiler but is being phased out; \
605 it will become a hard error";
607 let explanation = if lint_id == LintId::of(::lint::builtin::UNSTABLE_NAME_COLLISIONS) {
608 "once this method is added to the standard library, \
609 the ambiguity may cause an error or change in behavior!"
611 } else if let Some(edition) = future_incompatible.edition {
612 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
614 format!("{} in a future release!", STANDARD_MESSAGE)
616 let citation = format!("for more information, see {}",
617 future_incompatible.reference);
618 err.warn(&explanation);
622 // If this code originates in a foreign macro, aka something that this crate
623 // did not itself author, then it's likely that there's nothing this crate
624 // can do about it. We probably want to skip the lint entirely.
625 if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
626 // Any suggestions made here are likely to be incorrect, so anything we
627 // emit shouldn't be automatically fixed by rustfix.
628 err.allow_suggestions(false);
630 // If this is a future incompatible lint it'll become a hard error, so
631 // we have to emit *something*. Also allow lints to whitelist themselves
632 // on a case-by-case basis for emission in a foreign macro.
633 if future_incompatible.is_none() && !lint.report_in_external_macro {
641 fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
644 assert_eq!(cnum, LOCAL_CRATE);
645 let mut builder = LintLevelMapBuilder {
646 levels: LintLevelSets::builder(tcx.sess),
649 let krate = tcx.hir.krate();
651 builder.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |builder| {
652 intravisit::walk_crate(builder, krate);
655 Lrc::new(builder.levels.build_map())
658 struct LintLevelMapBuilder<'a, 'tcx: 'a> {
659 levels: levels::LintLevelsBuilder<'tcx>,
660 tcx: TyCtxt<'a, 'tcx, 'tcx>,
663 impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
664 fn with_lint_attrs<F>(&mut self,
666 attrs: &[ast::Attribute],
668 where F: FnOnce(&mut Self)
670 let push = self.levels.push(attrs);
671 self.levels.register_id(self.tcx.hir.definitions().node_to_hir_id(id));
673 self.levels.pop(push);
677 impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
678 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
679 intravisit::NestedVisitorMap::All(&self.tcx.hir)
682 fn visit_item(&mut self, it: &'tcx hir::Item) {
683 self.with_lint_attrs(it.id, &it.attrs, |builder| {
684 intravisit::walk_item(builder, it);
688 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
689 self.with_lint_attrs(it.id, &it.attrs, |builder| {
690 intravisit::walk_foreign_item(builder, it);
694 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
695 self.with_lint_attrs(e.id, &e.attrs, |builder| {
696 intravisit::walk_expr(builder, e);
700 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
701 self.with_lint_attrs(s.id, &s.attrs, |builder| {
702 intravisit::walk_struct_field(builder, s);
706 fn visit_variant(&mut self,
707 v: &'tcx hir::Variant,
708 g: &'tcx hir::Generics,
709 item_id: ast::NodeId) {
710 self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |builder| {
711 intravisit::walk_variant(builder, v, g, item_id);
715 fn visit_local(&mut self, l: &'tcx hir::Local) {
716 self.with_lint_attrs(l.id, &l.attrs, |builder| {
717 intravisit::walk_local(builder, l);
721 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
722 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |builder| {
723 intravisit::walk_trait_item(builder, trait_item);
727 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
728 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |builder| {
729 intravisit::walk_impl_item(builder, impl_item);
734 pub fn provide(providers: &mut Providers<'_>) {
735 providers.lint_levels = lint_levels;
738 /// Returns whether `span` originates in a foreign crate's external macro.
740 /// This is used to test whether a lint should be entirely aborted above.
741 pub fn in_external_macro(sess: &Session, span: Span) -> bool {
742 let info = match span.ctxt().outer().expn_info() {
744 // no ExpnInfo means this span doesn't come from a macro
745 None => return false,
749 ExpnFormat::MacroAttribute(..) => return true, // definitely a plugin
750 ExpnFormat::CompilerDesugaring(_) => return true, // well, it's "external"
751 ExpnFormat::MacroBang(..) => {} // check below
754 let def_site = match info.def_site {
756 // no span for the def_site means it's an external macro
760 match sess.source_map().span_to_snippet(def_site) {
761 Ok(code) => !code.starts_with("macro_rules"),
762 // no snippet = external macro or compiler-builtin expansion