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 session::{Session, DiagnosticMessageId};
44 use syntax::codemap::MultiSpan;
45 use syntax::edition::Edition;
46 use syntax::symbol::Symbol;
47 use syntax::visit as ast_visit;
50 use ty::query::Providers;
51 use util::nodemap::NodeMap;
53 pub use lint::context::{LateContext, EarlyContext, LintContext, LintStore,
54 check_crate, check_ast_crate,
55 FutureIncompatibleInfo, BufferedEarlyLint};
57 /// Specification of a single lint.
58 #[derive(Copy, Clone, Debug)]
60 /// A string identifier for the lint.
62 /// This identifies the lint in attributes and in command-line arguments.
63 /// In those contexts it is always lowercase, but this field is compared
64 /// in a way which is case-insensitive for ASCII characters. This allows
65 /// `declare_lint!()` invocations to follow the convention of upper-case
66 /// statics without repeating the name.
68 /// The name is written with underscores, e.g. "unused_imports".
69 /// On the command line, underscores become dashes.
70 pub name: &'static str,
72 /// Default level for the lint.
73 pub default_level: Level,
75 /// Description of the lint or the issue it detects.
77 /// e.g. "imports that are never used"
78 pub desc: &'static str,
80 /// Starting at the given edition, default to the given lint level. If this is `None`, then use
82 pub edition_lint_opts: Option<(Edition, Level)>,
86 /// Get the lint's name, with ASCII letters converted to lowercase.
87 pub fn name_lower(&self) -> String {
88 self.name.to_ascii_lowercase()
91 pub fn default_level(&self, session: &Session) -> Level {
92 self.edition_lint_opts
93 .filter(|(e, _)| *e <= session.edition())
95 .unwrap_or(self.default_level)
99 /// Declare a static item of type `&'static Lint`.
101 macro_rules! declare_lint {
102 ($vis: vis $NAME: ident, $Level: ident, $desc: expr) => (
103 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
104 name: stringify!($NAME),
105 default_level: $crate::lint::$Level,
107 edition_lint_opts: None,
110 ($vis: vis $NAME: ident, $Level: ident, $desc: expr,
111 $lint_edition: expr => $edition_level: ident $(,)?
113 $vis static $NAME: &$crate::lint::Lint = &$crate::lint::Lint {
114 name: stringify!($NAME),
115 default_level: $crate::lint::$Level,
117 edition_lint_opts: Some(($lint_edition, $crate::lint::Level::$edition_level)),
122 /// Declare a static `LintArray` and return it as an expression.
124 macro_rules! lint_array {
125 ($( $lint:expr ),* $(,)?) => {{
130 pub type LintArray = Vec<&'static Lint>;
133 /// Get descriptions of the lints this `LintPass` object can emit.
135 /// NB: there is no enforcement that the object only emits lints it registered.
136 /// And some `rustc` internal `LintPass`es register lints to be emitted by other
137 /// parts of the compiler. If you want enforced access restrictions for your
138 /// `Lint`, make it a private `static` item in its own module.
139 fn get_lints(&self) -> LintArray;
143 macro_rules! late_lint_methods {
144 ($macro:path, $args:tt, [$hir:tt]) => (
145 $macro!($args, [$hir], [
146 fn check_body(a: &$hir hir::Body);
147 fn check_body_post(a: &$hir hir::Body);
148 fn check_name(a: Span, b: ast::Name);
149 fn check_crate(a: &$hir hir::Crate);
150 fn check_crate_post(a: &$hir hir::Crate);
151 fn check_mod(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
152 fn check_mod_post(a: &$hir hir::Mod, b: Span, c: ast::NodeId);
153 fn check_foreign_item(a: &$hir hir::ForeignItem);
154 fn check_foreign_item_post(a: &$hir hir::ForeignItem);
155 fn check_item(a: &$hir hir::Item);
156 fn check_item_post(a: &$hir hir::Item);
157 fn check_local(a: &$hir hir::Local);
158 fn check_block(a: &$hir hir::Block);
159 fn check_block_post(a: &$hir hir::Block);
160 fn check_stmt(a: &$hir hir::Stmt);
161 fn check_arm(a: &$hir hir::Arm);
162 fn check_pat(a: &$hir hir::Pat);
163 fn check_decl(a: &$hir hir::Decl);
164 fn check_expr(a: &$hir hir::Expr);
165 fn check_expr_post(a: &$hir hir::Expr);
166 fn check_ty(a: &$hir hir::Ty);
167 fn check_generic_param(a: &$hir hir::GenericParam);
168 fn check_generics(a: &$hir hir::Generics);
169 fn check_where_predicate(a: &$hir hir::WherePredicate);
170 fn check_poly_trait_ref(a: &$hir hir::PolyTraitRef, b: hir::TraitBoundModifier);
172 a: hir::intravisit::FnKind<$hir>,
173 b: &$hir hir::FnDecl,
178 a: hir::intravisit::FnKind<$hir>,
179 b: &$hir hir::FnDecl,
184 fn check_trait_item(a: &$hir hir::TraitItem);
185 fn check_trait_item_post(a: &$hir hir::TraitItem);
186 fn check_impl_item(a: &$hir hir::ImplItem);
187 fn check_impl_item_post(a: &$hir hir::ImplItem);
189 a: &$hir hir::VariantData,
191 c: &$hir hir::Generics,
194 fn check_struct_def_post(
195 a: &$hir hir::VariantData,
197 c: &$hir hir::Generics,
200 fn check_struct_field(a: &$hir hir::StructField);
201 fn check_variant(a: &$hir hir::Variant, b: &$hir hir::Generics);
202 fn check_variant_post(a: &$hir hir::Variant, b: &$hir hir::Generics);
203 fn check_lifetime(a: &$hir hir::Lifetime);
204 fn check_path(a: &$hir hir::Path, b: ast::NodeId);
205 fn check_attribute(a: &$hir ast::Attribute);
207 /// Called when entering a syntax node that can have lint attributes such
208 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
209 fn enter_lint_attrs(a: &$hir [ast::Attribute]);
211 /// Counterpart to `enter_lint_attrs`.
212 fn exit_lint_attrs(a: &$hir [ast::Attribute]);
217 /// Trait for types providing lint checks.
219 /// Each `check` method checks a single syntax node, and should not
220 /// invoke methods recursively (unlike `Visitor`). By default they
223 // FIXME: eliminate the duplication with `Visitor`. But this also
224 // contains a few lint-specific methods with no equivalent in `Visitor`.
226 macro_rules! expand_lint_pass_methods {
227 ($context:ty, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
228 $(#[inline(always)] fn $name(&mut self, $context, $(_: $arg),*) {})*
232 macro_rules! declare_late_lint_pass {
233 ([], [$hir:tt], [$($methods:tt)*]) => (
234 pub trait LateLintPass<'a, $hir>: LintPass {
235 expand_lint_pass_methods!(&LateContext<'a, $hir>, [$($methods)*]);
240 late_lint_methods!(declare_late_lint_pass, [], ['tcx]);
243 macro_rules! expand_combined_late_lint_pass_method {
244 ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({
245 $($self.$passes.$name $params;)*
250 macro_rules! expand_combined_late_lint_pass_methods {
251 ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
252 $(fn $name(&mut self, context: &LateContext<'a, 'tcx>, $($param: $arg),*) {
253 expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*));
259 macro_rules! declare_combined_late_lint_pass {
260 ([$name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => (
261 #[allow(non_snake_case)]
263 $($passes: $passes,)*
269 $($passes: $constructor,)*
274 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $name {
275 expand_combined_late_lint_pass_methods!([$($passes),*], $methods);
278 impl LintPass for $name {
279 fn get_lints(&self) -> LintArray {
280 let mut lints = Vec::new();
281 $(lints.extend_from_slice(&self.$passes.get_lints());)*
288 pub trait EarlyLintPass: LintPass {
289 fn check_ident(&mut self, _: &EarlyContext, _: ast::Ident) { }
290 fn check_crate(&mut self, _: &EarlyContext, _: &ast::Crate) { }
291 fn check_crate_post(&mut self, _: &EarlyContext, _: &ast::Crate) { }
292 fn check_mod(&mut self, _: &EarlyContext, _: &ast::Mod, _: Span, _: ast::NodeId) { }
293 fn check_mod_post(&mut self, _: &EarlyContext, _: &ast::Mod, _: Span, _: ast::NodeId) { }
294 fn check_foreign_item(&mut self, _: &EarlyContext, _: &ast::ForeignItem) { }
295 fn check_foreign_item_post(&mut self, _: &EarlyContext, _: &ast::ForeignItem) { }
296 fn check_item(&mut self, _: &EarlyContext, _: &ast::Item) { }
297 fn check_item_post(&mut self, _: &EarlyContext, _: &ast::Item) { }
298 fn check_local(&mut self, _: &EarlyContext, _: &ast::Local) { }
299 fn check_block(&mut self, _: &EarlyContext, _: &ast::Block) { }
300 fn check_block_post(&mut self, _: &EarlyContext, _: &ast::Block) { }
301 fn check_stmt(&mut self, _: &EarlyContext, _: &ast::Stmt) { }
302 fn check_arm(&mut self, _: &EarlyContext, _: &ast::Arm) { }
303 fn check_pat(&mut self, _: &EarlyContext, _: &ast::Pat) { }
304 fn check_expr(&mut self, _: &EarlyContext, _: &ast::Expr) { }
305 fn check_expr_post(&mut self, _: &EarlyContext, _: &ast::Expr) { }
306 fn check_ty(&mut self, _: &EarlyContext, _: &ast::Ty) { }
307 fn check_generic_param(&mut self, _: &EarlyContext, _: &ast::GenericParam) { }
308 fn check_generics(&mut self, _: &EarlyContext, _: &ast::Generics) { }
309 fn check_where_predicate(&mut self, _: &EarlyContext, _: &ast::WherePredicate) { }
310 fn check_poly_trait_ref(&mut self, _: &EarlyContext, _: &ast::PolyTraitRef,
311 _: &ast::TraitBoundModifier) { }
312 fn check_fn(&mut self, _: &EarlyContext,
313 _: ast_visit::FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) { }
314 fn check_fn_post(&mut self, _: &EarlyContext,
315 _: ast_visit::FnKind, _: &ast::FnDecl, _: Span, _: ast::NodeId) { }
316 fn check_trait_item(&mut self, _: &EarlyContext, _: &ast::TraitItem) { }
317 fn check_trait_item_post(&mut self, _: &EarlyContext, _: &ast::TraitItem) { }
318 fn check_impl_item(&mut self, _: &EarlyContext, _: &ast::ImplItem) { }
319 fn check_impl_item_post(&mut self, _: &EarlyContext, _: &ast::ImplItem) { }
320 fn check_struct_def(&mut self, _: &EarlyContext,
321 _: &ast::VariantData, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
322 fn check_struct_def_post(&mut self, _: &EarlyContext,
323 _: &ast::VariantData, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
324 fn check_struct_field(&mut self, _: &EarlyContext, _: &ast::StructField) { }
325 fn check_variant(&mut self, _: &EarlyContext, _: &ast::Variant, _: &ast::Generics) { }
326 fn check_variant_post(&mut self, _: &EarlyContext, _: &ast::Variant, _: &ast::Generics) { }
327 fn check_lifetime(&mut self, _: &EarlyContext, _: &ast::Lifetime) { }
328 fn check_path(&mut self, _: &EarlyContext, _: &ast::Path, _: ast::NodeId) { }
329 fn check_attribute(&mut self, _: &EarlyContext, _: &ast::Attribute) { }
330 fn check_mac_def(&mut self, _: &EarlyContext, _: &ast::MacroDef, _id: ast::NodeId) { }
331 fn check_mac(&mut self, _: &EarlyContext, _: &ast::Mac) { }
333 /// Called when entering a syntax node that can have lint attributes such
334 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
335 fn enter_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
337 /// Counterpart to `enter_lint_attrs`.
338 fn exit_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
341 /// A lint pass boxed up as a trait object.
342 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
343 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
344 + sync::Sync + 'static>;
348 /// Identifies a lint known to the compiler.
349 #[derive(Clone, Copy, Debug)]
351 // Identity is based on pointer equality of this field.
355 impl PartialEq for LintId {
356 fn eq(&self, other: &LintId) -> bool {
357 (self.lint as *const Lint) == (other.lint as *const Lint)
361 impl Eq for LintId { }
363 impl hash::Hash for LintId {
364 fn hash<H: hash::Hasher>(&self, state: &mut H) {
365 let ptr = self.lint as *const Lint;
371 /// Get the `LintId` for a `Lint`.
372 pub fn of(lint: &'static Lint) -> LintId {
378 pub fn lint_name_raw(&self) -> &'static str {
382 /// Get the name of the lint.
383 pub fn to_string(&self) -> String {
384 self.lint.name_lower()
388 /// Setting for how to handle a lint.
389 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
391 Allow, Warn, Deny, Forbid,
394 impl_stable_hash_for!(enum self::Level {
402 /// Convert a level to a lower-case string.
403 pub fn as_str(self) -> &'static str {
412 /// Convert a lower-case string to a level.
413 pub fn from_str(x: &str) -> Option<Level> {
415 "allow" => Some(Allow),
416 "warn" => Some(Warn),
417 "deny" => Some(Deny),
418 "forbid" => Some(Forbid),
424 /// How a lint level was set.
425 #[derive(Clone, Copy, PartialEq, Eq)]
426 pub enum LintSource {
427 /// Lint is at the default level as declared
428 /// in rustc or a plugin.
431 /// Lint level was set by an attribute.
432 Node(ast::Name, Span),
434 /// Lint level was set by a command-line flag.
438 impl_stable_hash_for!(enum self::LintSource {
444 pub type LevelSource = (Level, LintSource);
450 pub use self::levels::{LintLevelSets, LintLevelMap};
452 pub struct LintBuffer {
453 map: NodeMap<Vec<BufferedEarlyLint>>,
457 pub fn new() -> LintBuffer {
458 LintBuffer { map: NodeMap() }
461 pub fn add_lint(&mut self,
466 diagnostic: BuiltinLintDiagnostics) {
467 let early_lint = BufferedEarlyLint {
468 lint_id: LintId::of(lint),
471 msg: msg.to_string(),
474 let arr = self.map.entry(id).or_insert(Vec::new());
475 if !arr.contains(&early_lint) {
476 arr.push(early_lint);
480 pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
481 self.map.remove(&id).unwrap_or(Vec::new())
484 pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
485 let key = self.map.keys().next().map(|k| *k);
486 key.map(|k| &self.map[&k][..])
490 pub fn struct_lint_level<'a>(sess: &'a Session,
494 span: Option<MultiSpan>,
496 -> DiagnosticBuilder<'a>
498 let mut err = match (level, span) {
499 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
500 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
501 (Level::Warn, None) => sess.struct_warn(msg),
502 (Level::Deny, Some(span)) |
503 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
504 (Level::Deny, None) |
505 (Level::Forbid, None) => sess.struct_err(msg),
508 let name = lint.name_lower();
510 LintSource::Default => {
513 DiagnosticMessageId::from(lint),
514 &format!("#[{}({})] on by default", level.as_str(), name));
516 LintSource::CommandLine(lint_flag_val) => {
517 let flag = match level {
520 Level::Forbid => "-F",
521 Level::Allow => panic!(),
523 let hyphen_case_lint_name = name.replace("_", "-");
524 if lint_flag_val.as_str() == name {
527 DiagnosticMessageId::from(lint),
528 &format!("requested on the command line with `{} {}`",
529 flag, hyphen_case_lint_name));
531 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
534 DiagnosticMessageId::from(lint),
535 &format!("`{} {}` implied by `{} {}`",
536 flag, hyphen_case_lint_name, flag,
537 hyphen_case_flag_val));
540 LintSource::Node(lint_attr_name, src) => {
541 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
542 src, "lint level defined here");
543 if lint_attr_name.as_str() != name {
544 let level_str = level.as_str();
545 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
546 &format!("#[{}({})] implied by #[{}({})]",
547 level_str, name, level_str, lint_attr_name));
552 err.code(DiagnosticId::Lint(name));
554 // Check for future incompatibility lints and issue a stronger warning.
555 let lints = sess.lint_store.borrow();
556 let lint_id = LintId::of(lint);
557 if let Some(future_incompatible) = lints.future_incompatible(lint_id) {
558 const STANDARD_MESSAGE: &str =
559 "this was previously accepted by the compiler but is being phased out; \
560 it will become a hard error";
562 let explanation = if lint_id == LintId::of(::lint::builtin::UNSTABLE_NAME_COLLISIONS) {
563 "once this method is added to the standard library, \
564 the ambiguity may cause an error or change in behavior!"
566 } else if let Some(edition) = future_incompatible.edition {
567 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
569 format!("{} in a future release!", STANDARD_MESSAGE)
571 let citation = format!("for more information, see {}",
572 future_incompatible.reference);
573 err.warn(&explanation);
580 fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
583 assert_eq!(cnum, LOCAL_CRATE);
584 let mut builder = LintLevelMapBuilder {
585 levels: LintLevelSets::builder(tcx.sess),
588 let krate = tcx.hir.krate();
590 builder.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |builder| {
591 intravisit::walk_crate(builder, krate);
594 Lrc::new(builder.levels.build_map())
597 struct LintLevelMapBuilder<'a, 'tcx: 'a> {
598 levels: levels::LintLevelsBuilder<'tcx>,
599 tcx: TyCtxt<'a, 'tcx, 'tcx>,
602 impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
603 fn with_lint_attrs<F>(&mut self,
605 attrs: &[ast::Attribute],
607 where F: FnOnce(&mut Self)
609 let push = self.levels.push(attrs);
610 self.levels.register_id(self.tcx.hir.definitions().node_to_hir_id(id));
612 self.levels.pop(push);
616 impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
617 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
618 intravisit::NestedVisitorMap::All(&self.tcx.hir)
621 fn visit_item(&mut self, it: &'tcx hir::Item) {
622 self.with_lint_attrs(it.id, &it.attrs, |builder| {
623 intravisit::walk_item(builder, it);
627 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
628 self.with_lint_attrs(it.id, &it.attrs, |builder| {
629 intravisit::walk_foreign_item(builder, it);
633 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
634 self.with_lint_attrs(e.id, &e.attrs, |builder| {
635 intravisit::walk_expr(builder, e);
639 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
640 self.with_lint_attrs(s.id, &s.attrs, |builder| {
641 intravisit::walk_struct_field(builder, s);
645 fn visit_variant(&mut self,
646 v: &'tcx hir::Variant,
647 g: &'tcx hir::Generics,
648 item_id: ast::NodeId) {
649 self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |builder| {
650 intravisit::walk_variant(builder, v, g, item_id);
654 fn visit_local(&mut self, l: &'tcx hir::Local) {
655 self.with_lint_attrs(l.id, &l.attrs, |builder| {
656 intravisit::walk_local(builder, l);
660 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
661 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |builder| {
662 intravisit::walk_trait_item(builder, trait_item);
666 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
667 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |builder| {
668 intravisit::walk_impl_item(builder, impl_item);
673 pub fn provide(providers: &mut Providers) {
674 providers.lint_levels = lint_levels;