blob: 4e6bf753b01aa4af75889d07746be18842f2ab74 [file] [log] [blame]
Keegan McAllisterc7af6062014-06-06 22:49:481//! Lints, aka compiler warnings.
2//!
Alex Crichtonc0388cd2013-10-02 18:29:293//! 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//!
Irina Popab63d7e22018-05-08 13:10:169//! Most lints can be written as `LintPass` instances. These run after
10//! all other analyses. The `LintPass`es built into rustc are defined
Keegan McAllisterc7af6062014-06-06 22:49:4811//! within `builtin.rs`, which has further comments on how to add such a lint.
Keegan McAllister2f274d12014-06-19 00:26:1412//! rustc can also load user-defined lint plugins via the plugin mechanism.
Alex Crichtonc0388cd2013-10-02 18:29:2913//!
Keegan McAllisterc7af6062014-06-06 22:49:4814//! 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
Irina Popab63d7e22018-05-08 13:10:1617//! `add_lint()`. To emit lints after the main lint pass (from codegen, for
Keegan McAllisterc7af6062014-06-06 22:49:4818//! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
19//! in `context.rs`.
Patrick Waltonf3723cf2013-05-17 22:28:4420
Steven Fackler3dcd2152014-11-06 08:05:5321pub use self::Level::*;
22pub use self::LintSource::*;
23
John Kåre Alsakerdc0fb522018-03-03 05:18:0924use rustc_data_structures::sync::{self, Lrc};
Alex Crichton0374e6a2017-07-27 04:51:0925
Mark Mansie957ed92019-02-05 17:20:4526use crate::errors::{DiagnosticBuilder, DiagnosticId};
27use crate::hir::def_id::{CrateNum, LOCAL_CRATE};
28use crate::hir::intravisit;
29use crate::hir;
30use crate::lint::builtin::BuiltinLintDiagnostics;
31use crate::lint::builtin::parser::{QUESTION_MARK_MACRO_SEP, ILL_FORMED_ATTRIBUTE_INPUT};
32use crate::session::{Session, DiagnosticMessageId};
Vadim Petrochenkov2eb83ee2018-07-18 18:53:5433use std::{hash, ptr};
Keegan McAllisterc7af6062014-06-06 22:49:4834use syntax::ast;
Donato Sciarra82607d22018-08-18 10:14:0335use syntax::source_map::{MultiSpan, ExpnFormat};
mark2a7ae042018-07-12 01:54:1236use syntax::early_buffered_lints::BufferedEarlyLintId;
Kurtis Nusbaum3c8d5552018-03-15 03:30:0637use syntax::edition::Edition;
Zack M. Davis93014462017-01-06 02:55:4338use syntax::symbol::Symbol;
Alex Crichton0374e6a2017-07-27 04:51:0939use syntax_pos::Span;
Mark Mansie957ed92019-02-05 17:20:4540use crate::ty::TyCtxt;
41use crate::ty::query::Providers;
42use crate::util::nodemap::NodeMap;
Patrick Walton57c59992012-12-23 22:41:3743
Mark Mansie957ed92019-02-05 17:20:4544pub use crate::lint::context::{LateContext, EarlyContext, LintContext, LintStore,
flip1995c549e652018-09-10 15:13:3145 check_crate, check_ast_crate, CheckLintNameResult,
Alex Crichton0374e6a2017-07-27 04:51:0946 FutureIncompatibleInfo, BufferedEarlyLint};
Niko Matsakis65b93eb2017-01-28 12:01:4547
Keegan McAllisterc7af6062014-06-06 22:49:4848/// Specification of a single lint.
Niko Matsakisd9530c02015-03-30 13:38:4449#[derive(Copy, Clone, Debug)]
Keegan McAllisterc7af6062014-06-06 22:49:4850pub struct Lint {
51 /// A string identifier for the lint.
52 ///
Keegan McAllister21e7b932014-06-13 20:04:5253 /// 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 ///
Alexander Regueiroee89c082018-11-27 02:59:4959 /// The name is written with underscores, e.g., "unused_imports".
Keegan McAllister21e7b932014-06-13 20:04:5260 /// On the command line, underscores become dashes.
Keegan McAllisterc7af6062014-06-06 22:49:4861 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 ///
Alexander Regueiroee89c082018-11-27 02:59:4968 /// e.g., "imports that are never used"
Keegan McAllisterc7af6062014-06-06 22:49:4869 pub desc: &'static str,
Manish Goregaokarda9dc052018-02-23 00:51:4270
Mark Mansi0e53b782018-02-17 23:33:2771 /// 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)>,
Oliver Schneiderb6e05472018-07-20 20:45:5274
75 /// Whether this lint is reported even inside expansions of external macros
76 pub report_in_external_macro: bool,
Keegan McAllisterc7af6062014-06-06 22:49:4877}
78
Keegan McAllister21e7b932014-06-13 20:04:5279impl Lint {
mark2a7ae042018-07-12 01:54:1280 /// 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,
Vadim Petrochenkov41c65992019-01-01 23:21:0584 BufferedEarlyLintId::IllFormedAttributeInput => ILL_FORMED_ATTRIBUTE_INPUT,
mark2a7ae042018-07-12 01:54:1285 }
86 }
87
Keegan McAllister21e7b932014-06-13 20:04:5288 /// Get the lint's name, with ASCII letters converted to lowercase.
89 pub fn name_lower(&self) -> String {
Simon Sapin1e5811e2014-12-05 17:57:4290 self.name.to_ascii_lowercase()
Keegan McAllister21e7b932014-06-13 20:04:5291 }
Manish Goregaokarda9dc052018-02-23 00:51:4292
93 pub fn default_level(&self, session: &Session) -> Level {
Mark Mansi0e53b782018-02-17 23:33:2794 self.edition_lint_opts
95 .filter(|(e, _)| *e <= session.edition())
96 .map(|(_, l)| l)
97 .unwrap_or(self.default_level)
Manish Goregaokarda9dc052018-02-23 00:51:4298 }
Keegan McAllister21e7b932014-06-13 20:04:5299}
100
Keegan McAllisterc7af6062014-06-06 22:49:48101/// Declare a static item of type `&'static Lint`.
Keegan McAllister442fbc42014-06-04 21:35:58102#[macro_export]
Patrick Waltonddb24662014-11-14 17:18:10103macro_rules! declare_lint {
Vadim Petrochenkovbf0cdb52017-10-20 21:00:57104 ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
Oliver Schneiderb6e05472018-07-20 20:45:52105 declare_lint!{$vis $NAME, $Level, $desc, false}
106 );
Oliver Schneider2f7edcc2018-07-21 10:36:18107 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, report_in_external_macro: $rep: expr) => (
108 declare_lint!{$vis $NAME, $Level, $desc, $rep}
Oliver Schneiderb6e05472018-07-20 20:45:52109 );
110 ($vis: vis $NAME: ident, $Level: ident, $desc: expr, $external: expr) => (
Vadim Petrochenkovbf0cdb52017-10-20 21:00:57111 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
112 name: stringify!($NAME),
113 default_level: $crate::lint::$Level,
Manish Goregaokarda9dc052018-02-23 00:51:42114 desc: $desc,
Mark Mansi0e53b782018-02-17 23:33:27115 edition_lint_opts: None,
Oliver Schneiderb6e05472018-07-20 20:45:52116 report_in_external_macro: $external,
Mark Mansi0e53b782018-02-17 23:33:27117 };
118 );
119 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
mark8eb49412018-06-16 02:49:00120 $lint_edition: expr => $edition_level: ident
Mark Mansi0e53b782018-02-17 23:33:27121 ) => (
122 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
123 name: stringify!($NAME),
124 default_level: $crate::lint::$Level,
125 desc: $desc,
126 edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
Oliver Schneiderb6e05472018-07-20 20:45:52127 report_in_external_macro: false,
Vadim Petrochenkovbf0cdb52017-10-20 21:00:57128 };
Manish Goregaokarda9dc052018-02-23 00:51:42129 );
Patrick Waltonddb24662014-11-14 17:18:10130}
Keegan McAllister442fbc42014-06-04 21:35:58131
flip19954b466ee2018-07-30 09:20:11132#[macro_export]
133macro_rules! declare_tool_lint {
134 ($vis: vis $tool: ident ::$NAME: ident, $Level: ident, $desc: expr) => (
135 declare_tool_lint!{$vis $tool::$NAME, $Level, $desc, false}
136 );
137 ($vis: vis $tool: ident ::$NAME: ident, $Level: ident, $desc: expr,
138 report_in_external_macro: $rep: expr) => (
139 declare_tool_lint!{$vis $tool::$NAME, $Level, $desc, $rep}
140 );
141 ($vis: vis $tool: ident ::$NAME: ident, $Level: ident, $desc: expr, $external: expr) => (
142 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
143 name: &concat!(stringify!($tool), "::", stringify!($NAME)),
144 default_level: $crate::lint::$Level,
145 desc: $desc,
146 edition_lint_opts: None,
147 report_in_external_macro: $external,
148 };
149 );
150}
151
Keegan McAllisterc7af6062014-06-06 22:49:48152/// Declare a static `LintArray` and return it as an expression.
Keegan McAllister442fbc42014-06-04 21:35:58153#[macro_export]
Mark Mansif81c2de2018-01-15 16:29:30154macro_rules! lint_array {
mark8eb49412018-06-16 02:49:00155 ($( $lint:expr ),* ,) => { lint_array!( $($lint),* ) };
156 ($( $lint:expr ),*) => {{
John Kåre Alsakerc5ecc6f2018-06-21 07:04:50157 vec![$($lint),*]
Mark Mansif81c2de2018-01-15 16:29:30158 }}
159}
Keegan McAllister442fbc42014-06-04 21:35:58160
John Kåre Alsakerc5ecc6f2018-06-21 07:04:50161pub type LintArray = Vec<&'static Lint>;
Keegan McAllister442fbc42014-06-04 21:35:58162
Keegan McAllister819f76c2014-06-10 21:03:19163pub trait LintPass {
John Kåre Alsakerbeb0c742019-01-18 06:40:55164 fn name(&self) -> &'static str;
165
Keegan McAllister442fbc42014-06-04 21:35:58166 /// Get descriptions of the lints this `LintPass` object can emit.
167 ///
Alexander Regueiroee89c082018-11-27 02:59:49168 /// N.B., there is no enforcement that the object only emits lints it registered.
Keegan McAllister442fbc42014-06-04 21:35:58169 /// And some `rustc` internal `LintPass`es register lints to be emitted by other
170 /// parts of the compiler. If you want enforced access restrictions for your
171 /// `Lint`, make it a private `static` item in its own module.
172 fn get_lints(&self) -> LintArray;
Nick Camerona642d852015-09-14 23:35:25173}
Keegan McAllister442fbc42014-06-04 21:35:58174
John Kåre Alsakerc5ecc6f2018-06-21 07:04:50175#[macro_export]
176macro_rules! late_lint_methods {
177 ($macro:path, $args:tt, [$hir:tt]) => (
178 $macro!($args, [$hir], [
179 fn check_body(a: &$hir hir::Body);
180 fn check_body_post(a: &$hir hir::Body);
181 fn check_name(a: Span, b: ast::Name);
182 fn check_crate(a: &$hir hir::Crate);
183 fn check_crate_post(a: &$hir hir::Crate);
184 fn check_mod(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
185 fn check_mod_post(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
186 fn check_foreign_item(a: &$hir hir::ForeignItem);
187 fn check_foreign_item_post(a: &$hir hir::ForeignItem);
188 fn check_item(a: &$hir hir::Item);
189 fn check_item_post(a: &$hir hir::Item);
190 fn check_local(a: &$hir hir::Local);
191 fn check_block(a: &$hir hir::Block);
192 fn check_block_post(a: &$hir hir::Block);
193 fn check_stmt(a: &$hir hir::Stmt);
194 fn check_arm(a: &$hir hir::Arm);
195 fn check_pat(a: &$hir hir::Pat);
John Kåre Alsakerc5ecc6f2018-06-21 07:04:50196 fn check_expr(a: &$hir hir::Expr);
197 fn check_expr_post(a: &$hir hir::Expr);
198 fn check_ty(a: &$hir hir::Ty);
199 fn check_generic_param(a: &$hir hir::GenericParam);
200 fn check_generics(a: &$hir hir::Generics);
201 fn check_where_predicate(a: &$hir hir::WherePredicate);
202 fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
203 fn check_fn(
204 a: hir::intravisit::FnKind<$hir>,
205 b: &$hir hir::FnDecl,
206 c: &$hir hir::Body,
207 d: Span,
208 e: ast::NodeId);
209 fn check_fn_post(
210 a: hir::intravisit::FnKind<$hir>,
211 b: &$hir hir::FnDecl,
212 c: &$hir hir::Body,
213 d: Span,
214 e: ast::NodeId
215 );
216 fn check_trait_item(a: &$hir hir::TraitItem);
217 fn check_trait_item_post(a: &$hir hir::TraitItem);
218 fn check_impl_item(a: &$hir hir::ImplItem);
219 fn check_impl_item_post(a: &$hir hir::ImplItem);
220 fn check_struct_def(
221 a: &$hir hir::VariantData,
222 b: ast::Name,
223 c: &$hir hir::Generics,
224 d: ast::NodeId
225 );
226 fn check_struct_def_post(
227 a: &$hir hir::VariantData,
228 b: ast::Name,
229 c: &$hir hir::Generics,
230 d: ast::NodeId
231 );
232 fn check_struct_field(a: &$hir hir::StructField);
233 fn check_variant(a: &$hir hir::Variant, b: &$hir hir::Generics);
234 fn check_variant_post(a: &$hir hir::Variant, b: &$hir hir::Generics);
235 fn check_lifetime(a: &$hir hir::Lifetime);
Mark Rousskov3baec3c2018-07-31 16:43:51236 fn check_path(a: &$hir hir::Path, b: hir::HirId);
John Kåre Alsakerc5ecc6f2018-06-21 07:04:50237 fn check_attribute(a: &$hir ast::Attribute);
238
239 /// Called when entering a syntax node that can have lint attributes such
240 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
241 fn enter_lint_attrs(a: &$hir [ast::Attribute]);
242
243 /// Counterpart to `enter_lint_attrs`.
244 fn exit_lint_attrs(a: &$hir [ast::Attribute]);
245 ]);
246 )
247}
Nick Camerona642d852015-09-14 23:35:25248
249/// Trait for types providing lint checks.
250///
251/// Each `check` method checks a single syntax node, and should not
252/// invoke methods recursively (unlike `Visitor`). By default they
253/// do nothing.
254//
255// FIXME: eliminate the duplication with `Visitor`. But this also
256// contains a few lint-specific methods with no equivalent in `Visitor`.
Nick Cameron76856e12015-09-10 04:40:59257
John Kåre Alsakerc5ecc6f2018-06-21 07:04:50258macro_rules! expand_lint_pass_methods {
259 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
Mark Mansi3a9cf122018-08-11 17:28:35260 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
John Kåre Alsakerc5ecc6f2018-06-21 07:04:50261 )
262}
Keegan McAllister69b6bc52014-06-02 22:27:15263
John Kåre Alsakerc5ecc6f2018-06-21 07:04:50264macro_rules! declare_late_lint_pass {
265 ([], [$hir:tt], [$($methods:tt)*]) => (
266 pub trait LateLintPass<'a, $hir>: LintPass {
267 expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
268 }
269 )
270}
271
272late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
273
274#[macro_export]
275macro_rules! expand_combined_late_lint_pass_method {
276 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
277 $($self.$passes.$name $params;)*
278 })
279}
280
281#[macro_export]
282macro_rules! expand_combined_late_lint_pass_methods {
283 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
284 $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
285 expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
286 })*
287 )
288}
289
290#[macro_export]
291macro_rules! declare_combined_late_lint_pass {
292 ([$name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
293 #[allow(non_snake_case)]
294 struct $name {
295 $($passes: $passes,)*
296 }
297
298 impl $name {
299 fn new() -> Self {
300 Self {
301 $($passes: $constructor,)*
302 }
303 }
304 }
305
306 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
307 expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
308 }
309
310 impl LintPass for $name {
John Kåre Alsakerbeb0c742019-01-18 06:40:55311 fn name(&self) -> &'static str {
312 panic!()
313 }
314
John Kåre Alsakerc5ecc6f2018-06-21 07:04:50315 fn get_lints(&self) -> LintArray {
316 let mut lints = Vec::new();
317 $(lints.extend_from_slice(&self.$passes.get_lints());)*
318 lints
319 }
320 }
321 )
Nick Camerona642d852015-09-14 23:35:25322}
323
John Kåre Alsakerbeb0c742019-01-18 06:40:55324#[macro_export]
325macro_rules! early_lint_methods {
326 ($macro:path, $args:tt) => (
327 $macro!($args, [
328 fn check_ident(a: ast::Ident);
329 fn check_crate(a: &ast::Crate);
330 fn check_crate_post(a: &ast::Crate);
331 fn check_mod(a: &ast::Mod, b: Span, c: ast::NodeId);
332 fn check_mod_post(a: &ast::Mod, b: Span, c: ast::NodeId);
333 fn check_foreign_item(a: &ast::ForeignItem);
334 fn check_foreign_item_post(a: &ast::ForeignItem);
335 fn check_item(a: &ast::Item);
336 fn check_item_post(a: &ast::Item);
337 fn check_local(a: &ast::Local);
338 fn check_block(a: &ast::Block);
339 fn check_block_post(a: &ast::Block);
340 fn check_stmt(a: &ast::Stmt);
341 fn check_arm(a: &ast::Arm);
342 fn check_pat(a: &ast::Pat, b: &mut bool); // FIXME: &mut bool looks just broken
343 fn check_expr(a: &ast::Expr);
344 fn check_expr_post(a: &ast::Expr);
345 fn check_ty(a: &ast::Ty);
346 fn check_generic_param(a: &ast::GenericParam);
347 fn check_generics(a: &ast::Generics);
348 fn check_where_predicate(a: &ast::WherePredicate);
349 fn check_poly_trait_ref(a: &ast::PolyTraitRef,
350 b: &ast::TraitBoundModifier);
351 fn check_fn(a: syntax::visit::FnKind<'_>, b: &ast::FnDecl, c: Span, d_: ast::NodeId);
352 fn check_fn_post(
353 a: syntax::visit::FnKind<'_>,
354 b: &ast::FnDecl,
355 c: Span,
356 d: ast::NodeId
357 );
358 fn check_trait_item(a: &ast::TraitItem);
359 fn check_trait_item_post(a: &ast::TraitItem);
360 fn check_impl_item(a: &ast::ImplItem);
361 fn check_impl_item_post(a: &ast::ImplItem);
362 fn check_struct_def(
363 a: &ast::VariantData,
364 b: ast::Ident,
365 c: &ast::Generics,
366 d: ast::NodeId
367 );
368 fn check_struct_def_post(
369 a: &ast::VariantData,
370 b: ast::Ident,
371 c: &ast::Generics,
372 d: ast::NodeId
373 );
374 fn check_struct_field(a: &ast::StructField);
375 fn check_variant(a: &ast::Variant, b: &ast::Generics);
376 fn check_variant_post(a: &ast::Variant, b: &ast::Generics);
377 fn check_lifetime(a: &ast::Lifetime);
378 fn check_path(a: &ast::Path, b: ast::NodeId);
379 fn check_attribute(a: &ast::Attribute);
380 fn check_mac_def(a: &ast::MacroDef, b: ast::NodeId);
381 fn check_mac(a: &ast::Mac);
Nick Cameron76856e12015-09-10 04:40:59382
John Kåre Alsakerbeb0c742019-01-18 06:40:55383 /// Called when entering a syntax node that can have lint attributes such
384 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
385 fn enter_lint_attrs(a: &[ast::Attribute]);
Nick Cameron76856e12015-09-10 04:40:59386
John Kåre Alsakerbeb0c742019-01-18 06:40:55387 /// Counterpart to `enter_lint_attrs`.
388 fn exit_lint_attrs(a: &[ast::Attribute]);
389 ]);
390 )
391}
392
393macro_rules! expand_early_lint_pass_methods {
394 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
395 $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})*
396 )
397}
398
399macro_rules! declare_early_lint_pass {
400 ([], [$($methods:tt)*]) => (
401 pub trait EarlyLintPass: LintPass {
402 expand_early_lint_pass_methods!(&EarlyContext<'_>, [$($methods)*]);
403 }
404 )
405}
406
407early_lint_methods!(declare_early_lint_pass, []);
408
409#[macro_export]
410macro_rules! expand_combined_early_lint_pass_method {
411 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
412 $($self.$passes.$name $params;)*
413 })
414}
415
416#[macro_export]
417macro_rules! expand_combined_early_lint_pass_methods {
418 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
419 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
420 expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*));
421 })*
422 )
423}
424
425#[macro_export]
426macro_rules! declare_combined_early_lint_pass {
427 ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => (
428 #[allow(non_snake_case)]
429 $v struct $name {
430 $($passes: $passes,)*
431 }
432
433 impl $name {
434 $v fn new() -> Self {
435 Self {
436 $($passes: $constructor,)*
437 }
438 }
439 }
440
441 impl EarlyLintPass for $name {
442 expand_combined_early_lint_pass_methods!([$($passes),*], $methods);
443 }
444
445 impl LintPass for $name {
446 fn name(&self) -> &'static str {
447 panic!()
448 }
449
450 fn get_lints(&self) -> LintArray {
451 let mut lints = Vec::new();
452 $(lints.extend_from_slice(&self.$passes.get_lints());)*
453 lints
454 }
455 }
456 )
Keegan McAllister69b6bc52014-06-02 22:27:15457}
458
Keegan McAllisterc7af6062014-06-06 22:49:48459/// A lint pass boxed up as a trait object.
John Kåre Alsakerdc0fb522018-03-03 05:18:09460pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
461pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
462 + sync::Sync + 'static>;
Keegan McAllister69b6bc52014-06-02 22:27:15463
Oliver Schneider15a8a662018-07-14 14:40:17464
465
Keegan McAllister442fbc42014-06-04 21:35:58466/// Identifies a lint known to the compiler.
Niko Matsakis98b046e2015-11-17 23:56:13467#[derive(Clone, Copy, Debug)]
Keegan McAllister442fbc42014-06-04 21:35:58468pub struct LintId {
469 // Identity is based on pointer equality of this field.
470 lint: &'static Lint,
Haitao Li7ffb2cb2012-01-19 08:50:51471}
472
Keegan McAllister442fbc42014-06-04 21:35:58473impl PartialEq for LintId {
474 fn eq(&self, other: &LintId) -> bool {
Vadim Petrochenkov2eb83ee2018-07-18 18:53:54475 ptr::eq(self.lint, other.lint)
Keegan McAllister442fbc42014-06-04 21:35:58476 }
477}
478
479impl Eq for LintId { }
480
Alex Crichtonf83e23a2015-02-18 04:48:07481impl hash::Hash for LintId {
482 fn hash<H: hash::Hasher>(&self, state: &mut H) {
483 let ptr = self.lint as *const Lint;
484 ptr.hash(state);
485 }
486}
Keegan McAllister442fbc42014-06-04 21:35:58487
488impl LintId {
Keegan McAllisterc7af6062014-06-06 22:49:48489 /// Get the `LintId` for a `Lint`.
Keegan McAllister442fbc42014-06-04 21:35:58490 pub fn of(lint: &'static Lint) -> LintId {
491 LintId {
Zack M. Davisf6689992017-07-03 18:19:51492 lint,
Keegan McAllister442fbc42014-06-04 21:35:58493 }
494 }
495
Michael Woeristere6c9a532017-08-14 16:19:42496 pub fn lint_name_raw(&self) -> &'static str {
497 self.lint.name
498 }
499
Keegan McAllisterc7af6062014-06-06 22:49:48500 /// Get the name of the lint.
Corey Farwell2655c892016-08-24 01:27:20501 pub fn to_string(&self) -> String {
Keegan McAllister21e7b932014-06-13 20:04:52502 self.lint.name_lower()
Graydon Hoaredbbaa502012-07-27 00:08:21503 }
504}
505
Keegan McAllisterc7af6062014-06-06 22:49:48506/// Setting for how to handle a lint.
Michael Woerister32414312016-08-02 20:53:58507#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
Huon Wilsona2396632014-05-21 11:50:37508pub enum Level {
Manish Goregaokarda9dc052018-02-23 00:51:42509 Allow, Warn, Deny, Forbid,
Graydon Hoare8a7fd4a2012-04-13 00:30:52510}
511
Michael Woeristere6c9a532017-08-14 16:19:42512impl_stable_hash_for!(enum self::Level {
513 Allow,
514 Warn,
515 Deny,
516 Forbid
517});
518
Keegan McAllister442fbc42014-06-04 21:35:58519impl Level {
Keegan McAllisterc7af6062014-06-06 22:49:48520 /// Convert a level to a lower-case string.
Keegan McAllister442fbc42014-06-04 21:35:58521 pub fn as_str(self) -> &'static str {
522 match self {
523 Allow => "allow",
524 Warn => "warn",
525 Deny => "deny",
526 Forbid => "forbid",
527 }
528 }
Alex Crichton0fd4d5d2013-07-17 04:12:16529
Keegan McAllisterc7af6062014-06-06 22:49:48530 /// Convert a lower-case string to a level.
Keegan McAllister442fbc42014-06-04 21:35:58531 pub fn from_str(x: &str) -> Option<Level> {
532 match x {
533 "allow" => Some(Allow),
534 "warn" => Some(Warn),
535 "deny" => Some(Deny),
536 "forbid" => Some(Forbid),
537 _ => None,
538 }
539 }
540}
Alex Crichton030c6662013-04-30 05:15:17541
Keegan McAllisterc7af6062014-06-06 22:49:48542/// How a lint level was set.
Jorge Aparicio351409a2015-01-04 03:54:18543#[derive(Clone, Copy, PartialEq, Eq)]
Corey Richardsonc3270802014-05-19 21:57:24544pub enum LintSource {
Keegan McAllisterc7af6062014-06-06 22:49:48545 /// Lint is at the default level as declared
546 /// in rustc or a plugin.
Alex Crichton4d44abd2013-05-09 17:22:26547 Default,
Keegan McAllisterc7af6062014-06-06 22:49:48548
549 /// Lint level was set by an attribute.
Zack M. Davis630c6a52018-09-30 00:25:26550 Node(ast::Name, Span, Option<Symbol> /* RFC 2383 reason */),
Keegan McAllisterc7af6062014-06-06 22:49:48551
552 /// Lint level was set by a command-line flag.
Zack M. Davis93014462017-01-06 02:55:43553 CommandLine(Symbol),
Alex Crichton4d44abd2013-05-09 17:22:26554}
555
Michael Woeristere6c9a532017-08-14 16:19:42556impl_stable_hash_for!(enum self::LintSource {
557 Default,
Zack M. Davis630c6a52018-09-30 00:25:26558 Node(name, span, reason),
Michael Woeristere6c9a532017-08-14 16:19:42559 CommandLine(text)
560});
561
Keegan McAllister442fbc42014-06-04 21:35:58562pub type LevelSource = (Level, LintSource);
Graydon Hoare8a7fd4a2012-04-13 00:30:52563
Keegan McAllisterc7af6062014-06-06 22:49:48564pub mod builtin;
Keegan McAllisterc7af6062014-06-06 22:49:48565mod context;
Alex Crichton0374e6a2017-07-27 04:51:09566mod levels;
567
568pub use self::levels::{LintLevelSets, LintLevelMap};
569
Eduard-Mihai Burtescu76831802018-07-25 12:44:06570#[derive(Default)]
Alex Crichton0374e6a2017-07-27 04:51:09571pub struct LintBuffer {
572 map: NodeMap<Vec<BufferedEarlyLint>>,
573}
574
575impl LintBuffer {
Alex Crichton0374e6a2017-07-27 04:51:09576 pub fn add_lint(&mut self,
577 lint: &'static Lint,
578 id: ast::NodeId,
579 sp: MultiSpan,
Manish Goregaokarbd296962018-02-23 06:34:06580 msg: &str,
581 diagnostic: BuiltinLintDiagnostics) {
Alex Crichton0374e6a2017-07-27 04:51:09582 let early_lint = BufferedEarlyLint {
583 lint_id: LintId::of(lint),
584 ast_id: id,
585 span: sp,
586 msg: msg.to_string(),
Manish Goregaokarbd296962018-02-23 06:34:06587 diagnostic
Alex Crichton0374e6a2017-07-27 04:51:09588 };
Eduard-Mihai Burtescu14aed812018-07-21 19:43:31589 let arr = self.map.entry(id).or_default();
Alex Crichton0374e6a2017-07-27 04:51:09590 if !arr.contains(&early_lint) {
591 arr.push(early_lint);
592 }
593 }
594
595 pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
ljedrzd28aed62018-10-12 14:16:00596 self.map.remove(&id).unwrap_or_default()
Alex Crichton0374e6a2017-07-27 04:51:09597 }
598
599 pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
600 let key = self.map.keys().next().map(|k| *k);
601 key.map(|k| &self.map[&k][..])
602 }
603}
604
605pub fn struct_lint_level<'a>(sess: &'a Session,
606 lint: &'static Lint,
607 level: Level,
608 src: LintSource,
609 span: Option<MultiSpan>,
610 msg: &str)
611 -> DiagnosticBuilder<'a>
612{
613 let mut err = match (level, span) {
614 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
615 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
616 (Level::Warn, None) => sess.struct_warn(msg),
617 (Level::Deny, Some(span)) |
618 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
619 (Level::Deny, None) |
620 (Level::Forbid, None) => sess.struct_err(msg),
621 };
622
623 let name = lint.name_lower();
624 match src {
625 LintSource::Default => {
626 sess.diag_note_once(
627 &mut err,
Zack M. Davis883f5e52017-11-24 18:26:42628 DiagnosticMessageId::from(lint),
Alex Crichton0374e6a2017-07-27 04:51:09629 &format!("#[{}({})] on by default", level.as_str(), name));
630 }
631 LintSource::CommandLine(lint_flag_val) => {
632 let flag = match level {
633 Level::Warn => "-W",
634 Level::Deny => "-D",
635 Level::Forbid => "-F",
636 Level::Allow => panic!(),
637 };
638 let hyphen_case_lint_name = name.replace("_", "-");
639 if lint_flag_val.as_str() == name {
640 sess.diag_note_once(
641 &mut err,
Zack M. Davis883f5e52017-11-24 18:26:42642 DiagnosticMessageId::from(lint),
Alex Crichton0374e6a2017-07-27 04:51:09643 &format!("requested on the command line with `{} {}`",
644 flag, hyphen_case_lint_name));
645 } else {
646 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
647 sess.diag_note_once(
648 &mut err,
Zack M. Davis883f5e52017-11-24 18:26:42649 DiagnosticMessageId::from(lint),
Alex Crichton0374e6a2017-07-27 04:51:09650 &format!("`{} {}` implied by `{} {}`",
651 flag, hyphen_case_lint_name, flag,
652 hyphen_case_flag_val));
653 }
654 }
Zack M. Davis630c6a52018-09-30 00:25:26655 LintSource::Node(lint_attr_name, src, reason) => {
656 if let Some(rationale) = reason {
657 err.note(&rationale.as_str());
658 }
Zack M. Davis883f5e52017-11-24 18:26:42659 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
660 src, "lint level defined here");
Alex Crichton0374e6a2017-07-27 04:51:09661 if lint_attr_name.as_str() != name {
662 let level_str = level.as_str();
Zack M. Davis883f5e52017-11-24 18:26:42663 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
Alex Crichton0374e6a2017-07-27 04:51:09664 &format!("#[{}({})] implied by #[{}({})]",
665 level_str, name, level_str, lint_attr_name));
666 }
667 }
668 }
669
Oliver Schneider6ae440e2017-10-27 06:21:22670 err.code(DiagnosticId::Lint(name));
Oliver Schneider88fb4c42017-10-24 06:37:41671
Alex Crichton0374e6a2017-07-27 04:51:09672 // Check for future incompatibility lints and issue a stronger warning.
673 let lints = sess.lint_store.borrow();
kennytm28b2bba2018-03-03 11:27:49674 let lint_id = LintId::of(lint);
Alex Crichtonca762ba2018-07-26 21:53:15675 let future_incompatible = lints.future_incompatible(lint_id);
676 if let Some(future_incompatible) = future_incompatible {
kennytm28b2bba2018-03-03 11:27:49677 const STANDARD_MESSAGE: &str =
678 "this was previously accepted by the compiler but is being phased out; \
679 it will become a hard error";
680
Mark Mansie957ed92019-02-05 17:20:45681 let explanation = if lint_id == LintId::of(crate::lint::builtin::UNSTABLE_NAME_COLLISIONS) {
kennytm28b2bba2018-03-03 11:27:49682 "once this method is added to the standard library, \
kennytma78028d2018-05-01 08:52:03683 the ambiguity may cause an error or change in behavior!"
kennytm28b2bba2018-03-03 11:27:49684 .to_owned()
685 } else if let Some(edition) = future_incompatible.edition {
686 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
Manish Goregaokar66797322018-03-08 21:16:36687 } else {
kennytm28b2bba2018-03-03 11:27:49688 format!("{} in a future release!", STANDARD_MESSAGE)
Manish Goregaokar66797322018-03-08 21:16:36689 };
Alex Crichton0374e6a2017-07-27 04:51:09690 let citation = format!("for more information, see {}",
691 future_incompatible.reference);
692 err.warn(&explanation);
693 err.note(&citation);
Alex Crichtonca762ba2018-07-26 21:53:15694 }
Alex Crichton8adf08c2018-07-17 17:23:03695
Alex Crichtonca762ba2018-07-26 21:53:15696 // If this code originates in a foreign macro, aka something that this crate
697 // did not itself author, then it's likely that there's nothing this crate
698 // can do about it. We probably want to skip the lint entirely.
699 if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
700 // Any suggestions made here are likely to be incorrect, so anything we
701 // emit shouldn't be automatically fixed by rustfix.
702 err.allow_suggestions(false);
703
704 // If this is a future incompatible lint it'll become a hard error, so
705 // we have to emit *something*. Also allow lints to whitelist themselves
706 // on a case-by-case basis for emission in a foreign macro.
707 if future_incompatible.is_none() && !lint.report_in_external_macro {
708 err.cancel()
Alex Crichton8adf08c2018-07-17 17:23:03709 }
Alex Crichton0374e6a2017-07-27 04:51:09710 }
711
712 return err
713}
714
715fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
John Kåre Alsakerb74e97c2018-02-27 16:11:14716 -> Lrc<LintLevelMap>
Alex Crichton0374e6a2017-07-27 04:51:09717{
718 assert_eq!(cnum, LOCAL_CRATE);
719 let mut builder = LintLevelMapBuilder {
720 levels: LintLevelSets::builder(tcx.sess),
721 tcx: tcx,
722 };
John Kåre Alsakera70babe2018-12-04 12:45:36723 let krate = tcx.hir().krate();
Alex Crichton0374e6a2017-07-27 04:51:09724
725 builder.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |builder| {
726 intravisit::walk_crate(builder, krate);
727 });
728
John Kåre Alsakerb74e97c2018-02-27 16:11:14729 Lrc::new(builder.levels.build_map())
Alex Crichton0374e6a2017-07-27 04:51:09730}
731
732struct LintLevelMapBuilder<'a, 'tcx: 'a> {
733 levels: levels::LintLevelsBuilder<'tcx>,
734 tcx: TyCtxt<'a, 'tcx, 'tcx>,
735}
736
737impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
738 fn with_lint_attrs<F>(&mut self,
739 id: ast::NodeId,
740 attrs: &[ast::Attribute],
741 f: F)
742 where F: FnOnce(&mut Self)
743 {
744 let push = self.levels.push(attrs);
John Kåre Alsakera70babe2018-12-04 12:45:36745 self.levels.register_id(self.tcx.hir().definitions().node_to_hir_id(id));
Alex Crichton0374e6a2017-07-27 04:51:09746 f(self);
747 self.levels.pop(push);
748 }
749}
750
751impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
752 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
John Kåre Alsakera70babe2018-12-04 12:45:36753 intravisit::NestedVisitorMap::All(&self.tcx.hir())
Alex Crichton0374e6a2017-07-27 04:51:09754 }
755
756 fn visit_item(&mut self, it: &'tcx hir::Item) {
757 self.with_lint_attrs(it.id, &it.attrs, |builder| {
758 intravisit::walk_item(builder, it);
759 });
760 }
761
762 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
763 self.with_lint_attrs(it.id, &it.attrs, |builder| {
764 intravisit::walk_foreign_item(builder, it);
765 })
766 }
767
768 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
769 self.with_lint_attrs(e.id, &e.attrs, |builder| {
770 intravisit::walk_expr(builder, e);
771 })
772 }
773
774 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
775 self.with_lint_attrs(s.id, &s.attrs, |builder| {
776 intravisit::walk_struct_field(builder, s);
777 })
778 }
779
780 fn visit_variant(&mut self,
781 v: &'tcx hir::Variant,
782 g: &'tcx hir::Generics,
783 item_id: ast::NodeId) {
784 self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |builder| {
785 intravisit::walk_variant(builder, v, g, item_id);
786 })
787 }
788
789 fn visit_local(&mut self, l: &'tcx hir::Local) {
790 self.with_lint_attrs(l.id, &l.attrs, |builder| {
791 intravisit::walk_local(builder, l);
792 })
793 }
794
795 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
796 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |builder| {
797 intravisit::walk_trait_item(builder, trait_item);
798 });
799 }
800
801 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
802 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |builder| {
803 intravisit::walk_impl_item(builder, impl_item);
804 });
805 }
806}
807
Zack M. Davis5b22d9b2018-08-30 05:02:42808pub fn provide(providers: &mut Providers<'_>) {
Alex Crichton0374e6a2017-07-27 04:51:09809 providers.lint_levels = lint_levels;
810}
dylan_DPCdd0808d2018-04-07 10:20:36811
Alex Crichton8adf08c2018-07-17 17:23:03812/// Returns whether `span` originates in a foreign crate's external macro.
813///
814/// This is used to test whether a lint should be entirely aborted above.
815pub fn in_external_macro(sess: &Session, span: Span) -> bool {
816 let info = match span.ctxt().outer().expn_info() {
817 Some(info) => info,
818 // no ExpnInfo means this span doesn't come from a macro
819 None => return false,
820 };
821
822 match info.format {
823 ExpnFormat::MacroAttribute(..) => return true, // definitely a plugin
824 ExpnFormat::CompilerDesugaring(_) => return true, // well, it's "external"
825 ExpnFormat::MacroBang(..) => {} // check below
dylan_DPCdd0808d2018-04-07 10:20:36826 }
827
Alex Crichton8adf08c2018-07-17 17:23:03828 let def_site = match info.def_site {
829 Some(span) => span,
830 // no span for the def_site means it's an external macro
831 None => return true,
832 };
833
Donato Sciarrad3fe97f2018-08-18 10:14:09834 match sess.source_map().span_to_snippet(def_site) {
Alex Crichton8adf08c2018-07-17 17:23:03835 Ok(code) => !code.starts_with("macro_rules"),
836 // no snippet = external macro or compiler-builtin expansion
837 Err(_) => true,
838 }
dylan_DPCdd0808d2018-04-07 10:20:36839}