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) { }
331 /// Called when entering a syntax node that can have lint attributes such
332 /// as `#[allow(...)]`. Called with *all* the attributes of that node.
333 fn enter_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
335 /// Counterpart to `enter_lint_attrs`.
336 fn exit_lint_attrs(&mut self, _: &EarlyContext, _: &[ast::Attribute]) { }
339 /// A lint pass boxed up as a trait object.
340 pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
341 pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
342 + sync::Sync + 'static>;
344 /// Identifies a lint known to the compiler.
345 #[derive(Clone, Copy, Debug)]
347 // Identity is based on pointer equality of this field.
351 impl PartialEq for LintId {
352 fn eq(&self, other: &LintId) -> bool {
353 (self.lint as *const Lint) == (other.lint as *const Lint)
357 impl Eq for LintId { }
359 impl hash::Hash for LintId {
360 fn hash<H: hash::Hasher>(&self, state: &mut H) {
361 let ptr = self.lint as *const Lint;
367 /// Get the `LintId` for a `Lint`.
368 pub fn of(lint: &'static Lint) -> LintId {
374 pub fn lint_name_raw(&self) -> &'static str {
378 /// Get the name of the lint.
379 pub fn to_string(&self) -> String {
380 self.lint.name_lower()
384 /// Setting for how to handle a lint.
385 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
387 Allow, Warn, Deny, Forbid,
390 impl_stable_hash_for!(enum self::Level {
398 /// Convert a level to a lower-case string.
399 pub fn as_str(self) -> &'static str {
408 /// Convert a lower-case string to a level.
409 pub fn from_str(x: &str) -> Option<Level> {
411 "allow" => Some(Allow),
412 "warn" => Some(Warn),
413 "deny" => Some(Deny),
414 "forbid" => Some(Forbid),
420 /// How a lint level was set.
421 #[derive(Clone, Copy, PartialEq, Eq)]
422 pub enum LintSource {
423 /// Lint is at the default level as declared
424 /// in rustc or a plugin.
427 /// Lint level was set by an attribute.
428 Node(ast::Name, Span),
430 /// Lint level was set by a command-line flag.
434 impl_stable_hash_for!(enum self::LintSource {
440 pub type LevelSource = (Level, LintSource);
446 pub use self::levels::{LintLevelSets, LintLevelMap};
448 pub struct LintBuffer {
449 map: NodeMap<Vec<BufferedEarlyLint>>,
453 pub fn new() -> LintBuffer {
454 LintBuffer { map: NodeMap() }
457 pub fn add_lint(&mut self,
462 diagnostic: BuiltinLintDiagnostics) {
463 let early_lint = BufferedEarlyLint {
464 lint_id: LintId::of(lint),
467 msg: msg.to_string(),
470 let arr = self.map.entry(id).or_insert(Vec::new());
471 if !arr.contains(&early_lint) {
472 arr.push(early_lint);
476 pub fn take(&mut self, id: ast::NodeId) -> Vec<BufferedEarlyLint> {
477 self.map.remove(&id).unwrap_or(Vec::new())
480 pub fn get_any(&self) -> Option<&[BufferedEarlyLint]> {
481 let key = self.map.keys().next().map(|k| *k);
482 key.map(|k| &self.map[&k][..])
486 pub fn struct_lint_level<'a>(sess: &'a Session,
490 span: Option<MultiSpan>,
492 -> DiagnosticBuilder<'a>
494 let mut err = match (level, span) {
495 (Level::Allow, _) => return sess.diagnostic().struct_dummy(),
496 (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg),
497 (Level::Warn, None) => sess.struct_warn(msg),
498 (Level::Deny, Some(span)) |
499 (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg),
500 (Level::Deny, None) |
501 (Level::Forbid, None) => sess.struct_err(msg),
504 let name = lint.name_lower();
506 LintSource::Default => {
509 DiagnosticMessageId::from(lint),
510 &format!("#[{}({})] on by default", level.as_str(), name));
512 LintSource::CommandLine(lint_flag_val) => {
513 let flag = match level {
516 Level::Forbid => "-F",
517 Level::Allow => panic!(),
519 let hyphen_case_lint_name = name.replace("_", "-");
520 if lint_flag_val.as_str() == name {
523 DiagnosticMessageId::from(lint),
524 &format!("requested on the command line with `{} {}`",
525 flag, hyphen_case_lint_name));
527 let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-");
530 DiagnosticMessageId::from(lint),
531 &format!("`{} {}` implied by `{} {}`",
532 flag, hyphen_case_lint_name, flag,
533 hyphen_case_flag_val));
536 LintSource::Node(lint_attr_name, src) => {
537 sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint),
538 src, "lint level defined here");
539 if lint_attr_name.as_str() != name {
540 let level_str = level.as_str();
541 sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint),
542 &format!("#[{}({})] implied by #[{}({})]",
543 level_str, name, level_str, lint_attr_name));
548 err.code(DiagnosticId::Lint(name));
550 // Check for future incompatibility lints and issue a stronger warning.
551 let lints = sess.lint_store.borrow();
552 let lint_id = LintId::of(lint);
553 if let Some(future_incompatible) = lints.future_incompatible(lint_id) {
554 const STANDARD_MESSAGE: &str =
555 "this was previously accepted by the compiler but is being phased out; \
556 it will become a hard error";
558 let explanation = if lint_id == LintId::of(::lint::builtin::UNSTABLE_NAME_COLLISIONS) {
559 "once this method is added to the standard library, \
560 the ambiguity may cause an error or change in behavior!"
562 } else if let Some(edition) = future_incompatible.edition {
563 format!("{} in the {} edition!", STANDARD_MESSAGE, edition)
565 format!("{} in a future release!", STANDARD_MESSAGE)
567 let citation = format!("for more information, see {}",
568 future_incompatible.reference);
569 err.warn(&explanation);
576 fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum)
579 assert_eq!(cnum, LOCAL_CRATE);
580 let mut builder = LintLevelMapBuilder {
581 levels: LintLevelSets::builder(tcx.sess),
584 let krate = tcx.hir.krate();
586 builder.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |builder| {
587 intravisit::walk_crate(builder, krate);
590 Lrc::new(builder.levels.build_map())
593 struct LintLevelMapBuilder<'a, 'tcx: 'a> {
594 levels: levels::LintLevelsBuilder<'tcx>,
595 tcx: TyCtxt<'a, 'tcx, 'tcx>,
598 impl<'a, 'tcx> LintLevelMapBuilder<'a, 'tcx> {
599 fn with_lint_attrs<F>(&mut self,
601 attrs: &[ast::Attribute],
603 where F: FnOnce(&mut Self)
605 let push = self.levels.push(attrs);
606 self.levels.register_id(self.tcx.hir.definitions().node_to_hir_id(id));
608 self.levels.pop(push);
612 impl<'a, 'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'a, 'tcx> {
613 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
614 intravisit::NestedVisitorMap::All(&self.tcx.hir)
617 fn visit_item(&mut self, it: &'tcx hir::Item) {
618 self.with_lint_attrs(it.id, &it.attrs, |builder| {
619 intravisit::walk_item(builder, it);
623 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
624 self.with_lint_attrs(it.id, &it.attrs, |builder| {
625 intravisit::walk_foreign_item(builder, it);
629 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
630 self.with_lint_attrs(e.id, &e.attrs, |builder| {
631 intravisit::walk_expr(builder, e);
635 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
636 self.with_lint_attrs(s.id, &s.attrs, |builder| {
637 intravisit::walk_struct_field(builder, s);
641 fn visit_variant(&mut self,
642 v: &'tcx hir::Variant,
643 g: &'tcx hir::Generics,
644 item_id: ast::NodeId) {
645 self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |builder| {
646 intravisit::walk_variant(builder, v, g, item_id);
650 fn visit_local(&mut self, l: &'tcx hir::Local) {
651 self.with_lint_attrs(l.id, &l.attrs, |builder| {
652 intravisit::walk_local(builder, l);
656 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
657 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |builder| {
658 intravisit::walk_trait_item(builder, trait_item);
662 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
663 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |builder| {
664 intravisit::walk_impl_item(builder, impl_item);
669 pub fn provide(providers: &mut Providers) {
670 providers.lint_levels = lint_levels;