1 //! Lints in the Rust compiler.
3 //! This contains lints which can feasibly be implemented as their own
4 //! AST visitor. Also see `rustc::lint::builtin`, which contains the
5 //! definitions of lints that are emitted directly inside the main
8 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
9 //! Then add code to emit the new lint in the appropriate circumstances.
10 //! You can do that in an existing `LintPass` if it makes sense, or in a
11 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
12 //! compiler. Only do the latter if the check can't be written cleanly as a
13 //! `LintPass` (also, note that such lints will need to be defined in
14 //! `rustc::lint::builtin`, not here).
16 //! If you define a new `EarlyLintPass`, you will also need to add it to the
17 //! `add_early_builtin!` or `add_early_builtin_with_new!` invocation in
18 //! `lib.rs`. Use the former for unit-like structs and the latter for structs
19 //! with a `pub fn new()`.
21 //! If you define a new `LateLintPass`, you will also need to add it to the
22 //! `late_lint_methods!` invocation in `lib.rs`.
24 use rustc::hir::def::{Res, DefKind};
25 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
26 use rustc::ty::{self, Ty, TyCtxt};
27 use rustc::{lint, util};
29 use util::nodemap::HirIdSet;
30 use lint::{LateContext, LintContext, LintArray};
31 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
33 use rustc::util::nodemap::FxHashSet;
35 use syntax::tokenstream::{TokenTree, TokenStream};
38 use syntax::ast::Expr;
39 use syntax::attr::{self, HasAttrs};
40 use syntax::source_map::Spanned;
41 use syntax::edition::Edition;
42 use syntax::feature_gate::{AttributeGate, AttributeTemplate, AttributeType};
43 use syntax::feature_gate::{Stability, deprecated_attributes};
44 use syntax_pos::{BytePos, Span, SyntaxContext};
45 use syntax::symbol::{Symbol, kw, sym};
46 use syntax::errors::{Applicability, DiagnosticBuilder};
47 use syntax::print::pprust::expr_to_string;
48 use syntax::visit::FnKind;
50 use rustc::hir::{self, GenericParamKind, PatKind};
52 use crate::nonstandard_style::{MethodLateContext, method_context};
56 // hardwired lints from librustc
57 pub use lint::builtin::*;
62 "suggest using `loop { }` instead of `while true { }`"
65 declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
67 fn as_while_cond(expr: &hir::Expr) -> Option<&hir::Expr> {
68 if let hir::ExprKind::Loop(blk, ..) = &expr.node {
69 if let Some(match_expr) = &blk.expr {
70 if let hir::ExprKind::Match(cond, .., hir::MatchSource::WhileDesugar)
73 if let hir::ExprKind::DropTemps(cond) = &cond.node {
83 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
84 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
85 if let Some(ref cond) = as_while_cond(e) {
86 if let hir::ExprKind::Lit(ref lit) = cond.node {
87 if let ast::LitKind::Bool(true) = lit.node {
88 if lit.span.ctxt() == SyntaxContext::empty() {
89 let msg = "denote infinite loops with `loop { ... }`";
90 let condition_span = cx.tcx.sess.source_map().def_span(e.span);
91 let mut err = cx.struct_span_lint(WHILE_TRUE, condition_span, msg);
92 err.span_suggestion_short(
96 Applicability::MachineApplicable
109 "use of owned (Box type) heap memory"
112 declare_lint_pass!(BoxPointers => [BOX_POINTERS]);
115 fn check_heap_type(&self, cx: &LateContext<'_, '_>, span: Span, ty: Ty<'_>) {
116 for leaf_ty in ty.walk() {
117 if leaf_ty.is_box() {
118 let m = format!("type uses owned (Box type) pointers: {}", ty);
119 cx.span_lint(BOX_POINTERS, span, &m);
125 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
126 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
128 hir::ItemKind::Fn(..) |
129 hir::ItemKind::Ty(..) |
130 hir::ItemKind::Enum(..) |
131 hir::ItemKind::Struct(..) |
132 hir::ItemKind::Union(..) => {
133 let def_id = cx.tcx.hir().local_def_id(it.hir_id);
134 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
139 // If it's a struct, we also have to check the fields' types
141 hir::ItemKind::Struct(ref struct_def, _) |
142 hir::ItemKind::Union(ref struct_def, _) => {
143 for struct_field in struct_def.fields() {
144 let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id);
145 self.check_heap_type(cx, struct_field.span,
146 cx.tcx.type_of(def_id));
153 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
154 let ty = cx.tables.node_type(e.hir_id);
155 self.check_heap_type(cx, e.span, ty);
160 NON_SHORTHAND_FIELD_PATTERNS,
162 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
165 declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
167 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
168 fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat) {
169 if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node {
170 let variant = cx.tables.pat_ty(pat).ty_adt_def()
171 .expect("struct pattern type is not an ADT")
172 .variant_of_res(cx.tables.qpath_res(qpath, pat.hir_id));
173 for fieldpat in field_pats {
174 if fieldpat.node.is_shorthand {
177 if fieldpat.span.ctxt().outer_expn_info().is_some() {
178 // Don't lint if this is a macro expansion: macro authors
179 // shouldn't have to worry about this kind of style issue
183 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
184 if cx.tcx.find_field_index(ident, &variant) ==
185 Some(cx.tcx.field_index(fieldpat.node.hir_id, cx.tables)) {
186 let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
188 &format!("the `{}:` in this pattern is redundant", ident));
189 let subspan = cx.tcx.sess.source_map().span_through_char(fieldpat.span,
191 err.span_suggestion_short(
195 Applicability::MachineApplicable
208 "usage of `unsafe` code"
211 declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
214 fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) {
215 // This comes from a macro that has `#[allow_internal_unsafe]`.
216 if span.allows_unsafe() {
220 cx.span_lint(UNSAFE_CODE, span, desc);
224 impl EarlyLintPass for UnsafeCode {
225 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
226 if attr.check_name(sym::allow_internal_unsafe) {
227 self.report_unsafe(cx, attr.span, "`allow_internal_unsafe` allows defining \
228 macros using unsafe without triggering \
229 the `unsafe_code` lint at their call site");
233 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
234 if let ast::ExprKind::Block(ref blk, _) = e.node {
235 // Don't warn about generated blocks; that'll just pollute the output.
236 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
237 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
242 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
244 ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => {
245 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
248 ast::ItemKind::Impl(ast::Unsafety::Unsafe, ..) => {
249 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
256 fn check_fn(&mut self,
257 cx: &EarlyContext<'_>,
263 FnKind::ItemFn(_, ast::FnHeader { unsafety: ast::Unsafety::Unsafe, .. }, ..) => {
264 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
267 FnKind::Method(_, sig, ..) => {
268 if sig.header.unsafety == ast::Unsafety::Unsafe {
269 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
277 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, item: &ast::TraitItem) {
278 if let ast::TraitItemKind::Method(ref sig, None) = item.node {
279 if sig.header.unsafety == ast::Unsafety::Unsafe {
280 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
289 "detects missing documentation for public members",
290 report_in_external_macro: true
293 pub struct MissingDoc {
294 /// Stack of whether `#[doc(hidden)]` is set at each level which has lint attributes.
295 doc_hidden_stack: Vec<bool>,
297 /// Private traits or trait items that leaked through. Don't check their methods.
298 private_traits: FxHashSet<hir::HirId>,
301 impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
303 fn has_doc(attr: &ast::Attribute) -> bool {
304 if !attr.check_name(sym::doc) {
308 if attr.is_value_str() {
312 if let Some(list) = attr.meta_item_list() {
314 if meta.check_name(sym::include) || meta.check_name(sym::hidden) {
324 pub fn new() -> MissingDoc {
326 doc_hidden_stack: vec![false],
327 private_traits: FxHashSet::default(),
331 fn doc_hidden(&self) -> bool {
332 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
335 fn check_missing_docs_attrs(&self,
336 cx: &LateContext<'_, '_>,
337 id: Option<hir::HirId>,
338 attrs: &[ast::Attribute],
340 desc: &'static str) {
341 // If we're building a test harness, then warning about
342 // documentation is probably not really relevant right now.
343 if cx.sess().opts.test {
347 // `#[doc(hidden)]` disables missing_docs check.
348 if self.doc_hidden() {
352 // Only check publicly-visible items, using the result from the privacy pass.
353 // It's an option so the crate root can also use this function (it doesn't
355 if let Some(id) = id {
356 if !cx.access_levels.is_exported(id) {
361 let has_doc = attrs.iter().any(|a| has_doc(a));
363 cx.span_lint(MISSING_DOCS,
364 cx.tcx.sess.source_map().def_span(sp),
365 &format!("missing documentation for {}", desc));
370 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
371 fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) {
372 let doc_hidden = self.doc_hidden() ||
373 attrs.iter().any(|attr| {
374 attr.check_name(sym::doc) &&
375 match attr.meta_item_list() {
377 Some(l) => attr::list_contains_name(&l, sym::hidden),
380 self.doc_hidden_stack.push(doc_hidden);
383 fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) {
384 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
387 fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate) {
388 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
390 for macro_def in &krate.exported_macros {
391 let has_doc = macro_def.attrs.iter().any(|a| has_doc(a));
393 cx.span_lint(MISSING_DOCS,
394 cx.tcx.sess.source_map().def_span(macro_def.span),
395 "missing documentation for macro");
400 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
401 let desc = match it.node {
402 hir::ItemKind::Fn(..) => "a function",
403 hir::ItemKind::Mod(..) => "a module",
404 hir::ItemKind::Enum(..) => "an enum",
405 hir::ItemKind::Struct(..) => "a struct",
406 hir::ItemKind::Union(..) => "a union",
407 hir::ItemKind::Trait(.., ref trait_item_refs) => {
408 // Issue #11592: traits are always considered exported, even when private.
409 if let hir::VisibilityKind::Inherited = it.vis.node {
410 self.private_traits.insert(it.hir_id);
411 for trait_item_ref in trait_item_refs {
412 self.private_traits.insert(trait_item_ref.id.hir_id);
418 hir::ItemKind::Ty(..) => "a type alias",
419 hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
420 // If the trait is private, add the impl items to `private_traits` so they don't get
421 // reported for missing docs.
422 let real_trait = trait_ref.path.res.def_id();
423 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(real_trait) {
424 match cx.tcx.hir().find(hir_id) {
425 Some(Node::Item(item)) => {
426 if let hir::VisibilityKind::Inherited = item.vis.node {
427 for impl_item_ref in impl_item_refs {
428 self.private_traits.insert(impl_item_ref.id.hir_id);
437 hir::ItemKind::Const(..) => "a constant",
438 hir::ItemKind::Static(..) => "a static",
442 self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, desc);
445 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem) {
446 if self.private_traits.contains(&trait_item.hir_id) {
450 let desc = match trait_item.node {
451 hir::TraitItemKind::Const(..) => "an associated constant",
452 hir::TraitItemKind::Method(..) => "a trait method",
453 hir::TraitItemKind::Type(..) => "an associated type",
456 self.check_missing_docs_attrs(cx,
457 Some(trait_item.hir_id),
463 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
464 // If the method is an impl for a trait, don't doc.
465 if method_context(cx, impl_item.hir_id) == MethodLateContext::TraitImpl {
469 let desc = match impl_item.node {
470 hir::ImplItemKind::Const(..) => "an associated constant",
471 hir::ImplItemKind::Method(..) => "a method",
472 hir::ImplItemKind::Type(_) => "an associated type",
473 hir::ImplItemKind::Existential(_) => "an associated existential type",
475 self.check_missing_docs_attrs(cx,
476 Some(impl_item.hir_id),
482 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField) {
483 if !sf.is_positional() {
484 self.check_missing_docs_attrs(cx,
492 fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant, _: &hir::Generics) {
493 self.check_missing_docs_attrs(cx,
502 pub MISSING_COPY_IMPLEMENTATIONS,
504 "detects potentially-forgotten implementations of `Copy`"
507 declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
509 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
510 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
511 if !cx.access_levels.is_reachable(item.hir_id) {
514 let (def, ty) = match item.node {
515 hir::ItemKind::Struct(_, ref ast_generics) => {
516 if !ast_generics.params.is_empty() {
519 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
520 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
522 hir::ItemKind::Union(_, ref ast_generics) => {
523 if !ast_generics.params.is_empty() {
526 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
527 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
529 hir::ItemKind::Enum(_, ref ast_generics) => {
530 if !ast_generics.params.is_empty() {
533 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
534 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
538 if def.has_dtor(cx.tcx) {
541 let param_env = ty::ParamEnv::empty();
542 if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span) {
545 if param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
546 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
548 "type could implement `Copy`; consider adding `impl \
555 MISSING_DEBUG_IMPLEMENTATIONS,
557 "detects missing implementations of fmt::Debug"
561 pub struct MissingDebugImplementations {
562 impling_types: Option<HirIdSet>,
565 impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
567 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
568 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
569 if !cx.access_levels.is_reachable(item.hir_id) {
574 hir::ItemKind::Struct(..) |
575 hir::ItemKind::Union(..) |
576 hir::ItemKind::Enum(..) => {}
580 let debug = match cx.tcx.lang_items().debug_trait() {
581 Some(debug) => debug,
585 if self.impling_types.is_none() {
586 let mut impls = HirIdSet::default();
587 cx.tcx.for_each_impl(debug, |d| {
588 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
589 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
590 impls.insert(hir_id);
595 self.impling_types = Some(impls);
596 debug!("{:?}", self.impling_types);
599 if !self.impling_types.as_ref().unwrap().contains(&item.hir_id) {
600 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
602 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
603 or a manual implementation")
609 pub ANONYMOUS_PARAMETERS,
611 "detects anonymous parameters"
615 /// Checks for use of anonymous parameters (RFC 1685).
616 AnonymousParameters => [ANONYMOUS_PARAMETERS]
619 impl EarlyLintPass for AnonymousParameters {
620 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::TraitItem) {
622 ast::TraitItemKind::Method(ref sig, _) => {
623 for arg in sig.decl.inputs.iter() {
625 ast::PatKind::Ident(_, ident, None) => {
626 if ident.name == kw::Invalid {
630 .span_to_snippet(arg.ty.span);
632 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
633 (snip, Applicability::MachineApplicable)
635 ("<type>".to_owned(), Applicability::HasPlaceholders)
639 ANONYMOUS_PARAMETERS,
641 "anonymous parameters are deprecated and will be \
642 removed in the next edition."
645 "Try naming the parameter or explicitly \
647 format!("_: {}", ty_snip),
661 /// Check for use of attributes which have been deprecated.
663 pub struct DeprecatedAttr {
664 // This is not free to compute, so we want to keep it around, rather than
665 // compute it for every attribute.
666 depr_attrs: Vec<&'static (Symbol, AttributeType, AttributeTemplate, AttributeGate)>,
669 impl_lint_pass!(DeprecatedAttr => []);
671 impl DeprecatedAttr {
672 pub fn new() -> DeprecatedAttr {
674 depr_attrs: deprecated_attributes(),
679 impl EarlyLintPass for DeprecatedAttr {
680 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
681 for &&(n, _, _, ref g) in &self.depr_attrs {
682 if attr.ident().map(|ident| ident.name) == Some(n) {
683 if let &AttributeGate::Gated(Stability::Deprecated(link, suggestion),
687 let msg = format!("use of deprecated attribute `{}`: {}. See {}",
689 let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
690 err.span_suggestion_short(
692 suggestion.unwrap_or("remove this attribute"),
694 Applicability::MachineApplicable
705 pub UNUSED_DOC_COMMENTS,
707 "detects doc comments that aren't used by rustdoc"
710 declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]);
712 impl UnusedDocComment {
715 cx: &EarlyContext<'_>,
718 is_macro_expansion: bool,
719 attrs: &[ast::Attribute]
721 let mut attrs = attrs.into_iter().peekable();
723 // Accumulate a single span for sugared doc comments.
724 let mut sugared_span: Option<Span> = None;
726 while let Some(attr) = attrs.next() {
727 if attr.is_sugared_doc {
729 sugared_span.map_or_else(
731 |span| span.with_hi(attr.span.hi()),
736 if attrs.peek().map(|next_attr| next_attr.is_sugared_doc).unwrap_or_default() {
740 let span = sugared_span.take().unwrap_or_else(|| attr.span);
742 if attr.check_name(sym::doc) {
743 let mut err = cx.struct_span_lint(UNUSED_DOC_COMMENTS, span, "unused doc comment");
747 format!("rustdoc does not generate documentation for {}", node_kind)
750 if is_macro_expansion {
751 err.help("to document an item produced by a macro, \
752 the macro must produce the documentation as part of its expansion");
761 impl EarlyLintPass for UnusedDocComment {
762 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
763 if let ast::ItemKind::Mac(..) = item.node {
764 self.warn_if_doc(cx, item.span, "macro expansions", true, &item.attrs);
768 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
769 let (kind, is_macro_expansion) = match stmt.node {
770 ast::StmtKind::Local(..) => ("statements", false),
771 ast::StmtKind::Item(..) => ("inner items", false),
772 ast::StmtKind::Mac(..) => ("macro expansions", true),
773 // expressions will be reported by `check_expr`.
774 ast::StmtKind::Semi(..) |
775 ast::StmtKind::Expr(..) => return,
778 self.warn_if_doc(cx, stmt.span, kind, is_macro_expansion, stmt.node.attrs());
781 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
782 let arm_span = arm.pats[0].span.with_hi(arm.body.span.hi());
783 self.warn_if_doc(cx, arm_span, "match arms", false, &arm.attrs);
786 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
787 self.warn_if_doc(cx, expr.span, "expressions", false, &expr.attrs);
794 "compiler plugin used as ordinary library in non-plugin crate"
797 declare_lint_pass!(PluginAsLibrary => [PLUGIN_AS_LIBRARY]);
799 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
800 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
801 if cx.tcx.plugin_registrar_fn(LOCAL_CRATE).is_some() {
802 // We're compiling a plugin; it's fine to link other plugins.
807 hir::ItemKind::ExternCrate(..) => (),
811 let def_id = cx.tcx.hir().local_def_id(it.hir_id);
812 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
813 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
815 // Probably means we aren't linking the crate for some reason.
817 // Not sure if / when this could happen.
823 cx.span_lint(PLUGIN_AS_LIBRARY,
825 "compiler plugin used as an ordinary library");
831 NO_MANGLE_CONST_ITEMS,
833 "const items will not have their symbols exported"
837 NO_MANGLE_GENERIC_ITEMS,
839 "generic items must be mangled"
842 declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
844 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
845 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
847 hir::ItemKind::Fn(.., ref generics, _) => {
848 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
849 for param in &generics.params {
851 GenericParamKind::Lifetime { .. } => {}
852 GenericParamKind::Type { .. } |
853 GenericParamKind::Const { .. } => {
854 let mut err = cx.struct_span_lint(
855 NO_MANGLE_GENERIC_ITEMS,
857 "functions generic over types or consts must be mangled",
859 err.span_suggestion_short(
861 "remove this attribute",
863 // Use of `#[no_mangle]` suggests FFI intent; correct
864 // fix may be to monomorphize source by hand
865 Applicability::MaybeIncorrect
874 hir::ItemKind::Const(..) => {
875 if attr::contains_name(&it.attrs, sym::no_mangle) {
876 // Const items do not refer to a particular location in memory, and therefore
877 // don't have anything to attach a symbol to
878 let msg = "const items should never be #[no_mangle]";
879 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
881 // account for "pub const" (#45562)
882 let start = cx.tcx.sess.source_map().span_to_snippet(it.span)
883 .map(|snippet| snippet.find("const").unwrap_or(0))
884 .unwrap_or(0) as u32;
885 // `const` is 5 chars
886 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
889 "try a static value",
890 "pub static".to_owned(),
891 Applicability::MachineApplicable
904 "mutating transmuted &mut T from &T may cause undefined behavior"
907 declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
909 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
910 fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr) {
911 use rustc_target::spec::abi::Abi::RustIntrinsic;
913 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
914 consider instead using an UnsafeCell";
915 match get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (&ty1.sty, &ty2.sty)) {
916 Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
917 if to_mt == hir::Mutability::MutMutable &&
918 from_mt == hir::Mutability::MutImmutable {
919 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
925 fn get_transmute_from_to<'a, 'tcx>
926 (cx: &LateContext<'a, 'tcx>,
928 -> Option<(Ty<'tcx>, Ty<'tcx>)> {
929 let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
930 cx.tables.qpath_res(qpath, expr.hir_id)
934 if let Res::Def(DefKind::Fn, did) = def {
935 if !def_id_is_transmute(cx, did) {
938 let sig = cx.tables.node_type(expr.hir_id).fn_sig(cx.tcx);
939 let from = sig.inputs().skip_binder()[0];
940 let to = *sig.output().skip_binder();
941 return Some((from, to));
946 fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
947 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
948 cx.tcx.item_name(def_id) == sym::transmute
956 "enabling unstable features (deprecated. do not use)"
960 /// Forbids using the `#[feature(...)]` attribute
961 UnstableFeatures => [UNSTABLE_FEATURES]
964 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
965 fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) {
966 if attr.check_name(sym::feature) {
967 if let Some(items) = attr.meta_item_list() {
969 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
977 UNIONS_WITH_DROP_FIELDS,
979 "use of unions that contain fields with possibly non-trivial drop code"
983 /// Lint for unions that contain fields with possibly non-trivial destructors.
984 UnionsWithDropFields => [UNIONS_WITH_DROP_FIELDS]
987 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
988 fn check_item(&mut self, ctx: &LateContext<'_, '_>, item: &hir::Item) {
989 if let hir::ItemKind::Union(ref vdata, _) = item.node {
990 for field in vdata.fields() {
991 let field_ty = ctx.tcx.type_of(
992 ctx.tcx.hir().local_def_id(field.hir_id));
993 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
994 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
996 "union contains a field with possibly non-trivial drop code, \
997 drop code of union fields is ignored when dropping the union");
1006 pub UNREACHABLE_PUB,
1008 "`pub` items not reachable from crate root"
1012 /// Lint for items marked `pub` that aren't reachable from other crates.
1013 UnreachablePub => [UNREACHABLE_PUB]
1016 impl UnreachablePub {
1017 fn perform_lint(&self, cx: &LateContext<'_, '_>, what: &str, id: hir::HirId,
1018 vis: &hir::Visibility, span: Span, exportable: bool) {
1019 let mut applicability = Applicability::MachineApplicable;
1021 hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
1022 if span.ctxt().outer_expn_info().is_some() {
1023 applicability = Applicability::MaybeIncorrect;
1025 let def_span = cx.tcx.sess.source_map().def_span(span);
1026 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1027 &format!("unreachable `pub` {}", what));
1028 let replacement = if cx.tcx.features().crate_visibility_modifier {
1034 err.span_suggestion(
1036 "consider restricting its visibility",
1041 err.help("or consider exporting it for use by other crates");
1050 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1051 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1052 self.perform_lint(cx, "item", item.hir_id, &item.vis, item.span, true);
1055 fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, foreign_item: &hir::ForeignItem) {
1056 self.perform_lint(cx, "item", foreign_item.hir_id, &foreign_item.vis,
1057 foreign_item.span, true);
1060 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) {
1061 self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false);
1064 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
1065 self.perform_lint(cx, "item", impl_item.hir_id, &impl_item.vis, impl_item.span, false);
1072 "bounds in type aliases are not enforced"
1076 /// Lint for trait and lifetime bounds in type aliases being mostly ignored.
1077 /// They are relevant when using associated types, but otherwise neither checked
1078 /// at definition site nor enforced at use site.
1079 TypeAliasBounds => [TYPE_ALIAS_BOUNDS]
1082 impl TypeAliasBounds {
1083 fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1085 hir::QPath::TypeRelative(ref ty, _) => {
1086 // If this is a type variable, we found a `T::Assoc`.
1088 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1090 Res::Def(DefKind::TyParam, _) => true,
1097 hir::QPath::Resolved(..) => false,
1101 fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder<'_>) {
1102 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1103 // bound. Let's see if this type does that.
1105 // We use a HIR visitor to walk the type.
1106 use rustc::hir::intravisit::{self, Visitor};
1107 struct WalkAssocTypes<'a, 'db> {
1108 err: &'a mut DiagnosticBuilder<'db>
1110 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1111 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1113 intravisit::NestedVisitorMap::None
1116 fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: hir::HirId, span: Span) {
1117 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1118 self.err.span_help(span,
1119 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1120 associated types in type aliases");
1122 intravisit::walk_qpath(self, qpath, id, span)
1126 // Let's go for a walk!
1127 let mut visitor = WalkAssocTypes { err };
1128 visitor.visit_ty(ty);
1132 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1133 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1134 let (ty, type_alias_generics) = match item.node {
1135 hir::ItemKind::Ty(ref ty, ref generics) => (&*ty, generics),
1138 let mut suggested_changing_assoc_types = false;
1139 // There must not be a where clause
1140 if !type_alias_generics.where_clause.predicates.is_empty() {
1141 let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1142 .map(|pred| pred.span()).collect();
1143 let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1144 "where clauses are not enforced in type aliases");
1145 err.help("the clause will not be checked when the type alias is used, \
1146 and should be removed");
1147 if !suggested_changing_assoc_types {
1148 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1149 suggested_changing_assoc_types = true;
1153 // The parameters must not have bounds
1154 for param in type_alias_generics.params.iter() {
1155 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1156 if !spans.is_empty() {
1157 let mut err = cx.struct_span_lint(
1160 "bounds on generic parameters are not enforced in type aliases",
1162 err.help("the bound will not be checked when the type alias is used, \
1163 and should be removed");
1164 if !suggested_changing_assoc_types {
1165 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1166 suggested_changing_assoc_types = true;
1175 /// Lint constants that are erroneous.
1176 /// Without this lint, we might not get any diagnostic if the constant is
1177 /// unused within this crate, even though downstream crates can't use it
1178 /// without producing an error.
1179 UnusedBrokenConst => []
1182 fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) {
1183 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
1184 let param_env = if cx.tcx.is_static(def_id) {
1185 // Use the same param_env as `codegen_static_initializer`, to reuse the cache.
1186 ty::ParamEnv::reveal_all()
1188 cx.tcx.param_env(def_id)
1190 let cid = ::rustc::mir::interpret::GlobalId {
1191 instance: ty::Instance::mono(cx.tcx, def_id),
1194 // trigger the query once for all constants since that will already report the errors
1195 // FIXME: Use ensure here
1196 let _ = cx.tcx.const_eval(param_env.and(cid));
1199 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1200 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1202 hir::ItemKind::Const(_, body_id) => {
1203 check_const(cx, body_id);
1205 hir::ItemKind::Static(_, _, body_id) => {
1206 check_const(cx, body_id);
1216 "these bounds don't depend on an type parameters"
1220 /// Lint for trait and lifetime bounds that don't depend on type parameters
1221 /// which either do nothing, or stop the item from being used.
1222 TrivialConstraints => [TRIVIAL_BOUNDS]
1225 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1228 cx: &LateContext<'a, 'tcx>,
1229 item: &'tcx hir::Item,
1231 use rustc::ty::fold::TypeFoldable;
1232 use rustc::ty::Predicate::*;
1234 if cx.tcx.features().trivial_bounds {
1235 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1236 let predicates = cx.tcx.predicates_of(def_id);
1237 for &(predicate, span) in &predicates.predicates {
1238 let predicate_kind_name = match predicate {
1239 Trait(..) => "Trait",
1241 RegionOutlives(..) => "Lifetime",
1243 // Ignore projections, as they can only be global
1244 // if the trait bound is global
1246 // Ignore bounds that a user can't type
1251 ConstEvaluatable(..) => continue,
1253 if predicate.is_global() {
1257 &format!("{} bound {} does not depend on any type \
1258 or lifetime parameters", predicate_kind_name, predicate),
1267 /// Does nothing as a lint pass, but registers some `Lint`s
1268 /// which are used by other parts of the compiler.
1272 NON_SHORTHAND_FIELD_PATTERNS,
1275 MISSING_COPY_IMPLEMENTATIONS,
1276 MISSING_DEBUG_IMPLEMENTATIONS,
1277 ANONYMOUS_PARAMETERS,
1278 UNUSED_DOC_COMMENTS,
1280 NO_MANGLE_CONST_ITEMS,
1281 NO_MANGLE_GENERIC_ITEMS,
1284 UNIONS_WITH_DROP_FIELDS,
1292 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1294 "`...` range patterns are deprecated"
1298 pub struct EllipsisInclusiveRangePatterns {
1299 /// If `Some(_)`, suppress all subsequent pattern
1300 /// warnings for better diagnostics.
1301 node_id: Option<ast::NodeId>,
1304 impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1306 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1307 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1308 if self.node_id.is_some() {
1309 // Don't recursively warn about patterns inside range endpoints.
1313 use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot};
1315 /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1316 /// corresponding to the ellipsis.
1317 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(&P<Expr>, &P<Expr>, Span)> {
1319 PatKind::Range(a, b, Spanned { span, node: RangeEnd::Included(DotDotDot), .. }) => {
1326 let (parenthesise, endpoints) = match &pat.node {
1327 PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)),
1328 _ => (false, matches_ellipsis_pat(pat)),
1331 if let Some((start, end, join)) = endpoints {
1332 let msg = "`...` range patterns are deprecated";
1333 let suggestion = "use `..=` for an inclusive range";
1335 self.node_id = Some(pat.id);
1336 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, pat.span, msg);
1337 err.span_suggestion(
1340 format!("&({}..={})", expr_to_string(&start), expr_to_string(&end)),
1341 Applicability::MachineApplicable,
1345 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, join, msg);
1346 err.span_suggestion_short(
1350 Applicability::MachineApplicable,
1357 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1358 if let Some(node_id) = self.node_id {
1359 if pat.id == node_id {
1367 UNNAMEABLE_TEST_ITEMS,
1369 "detects an item that cannot be named being marked as #[test_case]",
1370 report_in_external_macro: true
1373 pub struct UnnameableTestItems {
1374 boundary: hir::HirId, // HirId of the item under which things are not nameable
1375 items_nameable: bool,
1378 impl_lint_pass!(UnnameableTestItems => [UNNAMEABLE_TEST_ITEMS]);
1380 impl UnnameableTestItems {
1381 pub fn new() -> Self {
1383 boundary: hir::DUMMY_HIR_ID,
1384 items_nameable: true
1389 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
1390 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1391 if self.items_nameable {
1392 if let hir::ItemKind::Mod(..) = it.node {}
1394 self.items_nameable = false;
1395 self.boundary = it.hir_id;
1400 if let Some(attr) = attr::find_by_name(&it.attrs, sym::rustc_test_marker) {
1401 cx.struct_span_lint(
1402 UNNAMEABLE_TEST_ITEMS,
1404 "cannot test inner items",
1409 fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item) {
1410 if !self.items_nameable && self.boundary == it.hir_id {
1411 self.items_nameable = true;
1419 "detects edition keywords being used as an identifier"
1423 /// Check for uses of edition keywords used as an identifier.
1424 KeywordIdents => [KEYWORD_IDENTS]
1427 struct UnderMacro(bool);
1429 impl KeywordIdents {
1430 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) {
1431 for tt in tokens.into_trees() {
1433 // Only report non-raw idents.
1434 TokenTree::Token(token) => if let Some((ident, false)) = token.ident() {
1435 self.check_ident_token(cx, UnderMacro(true), ident);
1437 TokenTree::Delimited(_, _, tts) => {
1438 self.check_tokens(cx, tts)
1444 fn check_ident_token(&mut self,
1445 cx: &EarlyContext<'_>,
1446 UnderMacro(under_macro): UnderMacro,
1449 let next_edition = match cx.sess.edition() {
1450 Edition::Edition2015 => {
1452 kw::Async | kw::Await | kw::Try => Edition::Edition2018,
1454 // rust-lang/rust#56327: Conservatively do not
1455 // attempt to report occurrences of `dyn` within
1456 // macro definitions or invocations, because `dyn`
1457 // can legitimately occur as a contextual keyword
1458 // in 2015 code denoting its 2018 meaning, and we
1459 // do not want rustfix to inject bugs into working
1460 // code by rewriting such occurrences.
1462 // But if we see `dyn` outside of a macro, we know
1463 // its precise role in the parsed AST and thus are
1464 // assured this is truly an attempt to use it as
1466 kw::Dyn if !under_macro => Edition::Edition2018,
1472 // There are no new keywords yet for the 2018 edition and beyond.
1476 // Don't lint `r#foo`.
1477 if cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span) {
1481 let mut lint = cx.struct_span_lint(
1484 &format!("`{}` is a keyword in the {} edition",
1488 lint.span_suggestion(
1490 "you can use a raw identifier to stay compatible",
1491 format!("r#{}", ident.as_str()),
1492 Applicability::MachineApplicable,
1498 impl EarlyLintPass for KeywordIdents {
1499 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) {
1500 self.check_tokens(cx, mac_def.stream());
1502 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
1503 self.check_tokens(cx, mac.node.tts.clone().into());
1505 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: ast::Ident) {
1506 self.check_ident_token(cx, UnderMacro(false), ident);
1510 declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1512 impl ExplicitOutlivesRequirements {
1513 fn lifetimes_outliving_lifetime<'tcx>(
1514 inferred_outlives: &'tcx [ty::Predicate<'tcx>],
1516 ) -> Vec<ty::Region<'tcx>> {
1517 inferred_outlives.iter().filter_map(|pred| {
1519 ty::Predicate::RegionOutlives(outlives) => {
1520 let outlives = outlives.skip_binder();
1522 ty::ReEarlyBound(ebr) if ebr.index == index => {
1533 fn lifetimes_outliving_type<'tcx>(
1534 inferred_outlives: &'tcx [ty::Predicate<'tcx>],
1536 ) -> Vec<ty::Region<'tcx>> {
1537 inferred_outlives.iter().filter_map(|pred| {
1539 ty::Predicate::TypeOutlives(outlives) => {
1540 let outlives = outlives.skip_binder();
1541 if outlives.0.is_param(index) {
1552 fn collect_outlived_lifetimes<'tcx>(
1554 param: &'tcx hir::GenericParam,
1556 inferred_outlives: &'tcx [ty::Predicate<'tcx>],
1557 ty_generics: &'tcx ty::Generics,
1558 ) -> Vec<ty::Region<'tcx>> {
1559 let index = ty_generics.param_def_id_to_index[
1560 &tcx.hir().local_def_id(param.hir_id)];
1563 hir::GenericParamKind::Lifetime { .. } => {
1564 Self::lifetimes_outliving_lifetime(inferred_outlives, index)
1566 hir::GenericParamKind::Type { .. } => {
1567 Self::lifetimes_outliving_type(inferred_outlives, index)
1569 hir::GenericParamKind::Const { .. } => Vec::new(),
1574 fn collect_outlives_bound_spans<'tcx>(
1577 bounds: &hir::GenericBounds,
1578 inferred_outlives: &[ty::Region<'tcx>],
1580 ) -> Vec<(usize, Span)> {
1581 use rustc::middle::resolve_lifetime::Region;
1586 .filter_map(|(i, bound)| {
1587 if let hir::GenericBound::Outlives(lifetime) = bound {
1588 let is_inferred = match tcx.named_region(lifetime.hir_id) {
1589 Some(Region::Static) if infer_static => {
1590 inferred_outlives.iter()
1591 .any(|r| if let ty::ReStatic = r { true } else { false })
1593 Some(Region::EarlyBound(index, ..)) => inferred_outlives
1596 if let ty::ReEarlyBound(ebr) = r {
1605 Some((i, bound.span()))
1616 fn consolidate_outlives_bound_spans(
1619 bounds: &hir::GenericBounds,
1620 bound_spans: Vec<(usize, Span)>
1622 if bounds.is_empty() {
1625 if bound_spans.len() == bounds.len() {
1626 let (_, last_bound_span) = bound_spans[bound_spans.len()-1];
1627 // If all bounds are inferable, we want to delete the colon, so
1628 // start from just after the parameter (span passed as argument)
1629 vec![lo.to(last_bound_span)]
1631 let mut merged = Vec::new();
1632 let mut last_merged_i = None;
1634 let mut from_start = true;
1635 for (i, bound_span) in bound_spans {
1636 match last_merged_i {
1637 // If the first bound is inferable, our span should also eat the leading `+`.
1639 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
1640 last_merged_i = Some(0);
1642 // If consecutive bounds are inferable, merge their spans
1643 Some(h) if i == h+1 => {
1644 if let Some(tail) = merged.last_mut() {
1645 // Also eat the trailing `+` if the first
1646 // more-than-one bound is inferable
1647 let to_span = if from_start && i < bounds.len() {
1648 bounds[i+1].span().shrink_to_lo()
1652 *tail = tail.to(to_span);
1653 last_merged_i = Some(i);
1655 bug!("another bound-span visited earlier");
1659 // When we find a non-inferable bound, subsequent inferable bounds
1660 // won't be consecutive from the start (and we'll eat the leading
1661 // `+` rather than the trailing one)
1663 merged.push(bounds[i-1].span().shrink_to_hi().to(bound_span));
1664 last_merged_i = Some(i);
1673 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitOutlivesRequirements {
1674 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
1675 use rustc::middle::resolve_lifetime::Region;
1677 let infer_static = cx.tcx.features().infer_static_outlives_requirements;
1678 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1679 if let hir::ItemKind::Struct(_, ref hir_generics)
1680 | hir::ItemKind::Enum(_, ref hir_generics)
1681 | hir::ItemKind::Union(_, ref hir_generics) = item.node
1683 let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
1684 if inferred_outlives.is_empty() {
1688 let ty_generics = cx.tcx.generics_of(def_id);
1690 let mut bound_count = 0;
1691 let mut lint_spans = Vec::new();
1693 for param in &hir_generics.params {
1694 let has_lifetime_bounds = param.bounds.iter().any(|bound| {
1695 if let hir::GenericBound::Outlives(_) = bound {
1701 if !has_lifetime_bounds {
1705 let relevant_lifetimes = self.collect_outlived_lifetimes(
1711 if relevant_lifetimes.is_empty() {
1715 let bound_spans = self.collect_outlives_bound_spans(
1716 cx.tcx, ¶m.bounds, &relevant_lifetimes, infer_static,
1718 bound_count += bound_spans.len();
1720 self.consolidate_outlives_bound_spans(
1721 param.span.shrink_to_hi(), ¶m.bounds, bound_spans
1726 let mut where_lint_spans = Vec::new();
1727 let mut dropped_predicate_count = 0;
1728 let num_predicates = hir_generics.where_clause.predicates.len();
1729 for (i, where_predicate) in hir_generics.where_clause.predicates.iter().enumerate() {
1730 let (relevant_lifetimes, bounds, span) = match where_predicate {
1731 hir::WherePredicate::RegionPredicate(predicate) => {
1732 if let Some(Region::EarlyBound(index, ..))
1733 = cx.tcx.named_region(predicate.lifetime.hir_id)
1736 Self::lifetimes_outliving_lifetime(inferred_outlives, index),
1744 hir::WherePredicate::BoundPredicate(predicate) => {
1745 // FIXME we can also infer bounds on associated types,
1746 // and should check for them here.
1747 match predicate.bounded_ty.node {
1748 hir::TyKind::Path(hir::QPath::Resolved(
1752 if let Res::Def(DefKind::TyParam, def_id) = path.res {
1753 let index = ty_generics.param_def_id_to_index[&def_id];
1755 Self::lifetimes_outliving_type(inferred_outlives, index),
1768 if relevant_lifetimes.is_empty() {
1772 let bound_spans = self.collect_outlives_bound_spans(
1773 cx.tcx, bounds, &relevant_lifetimes, infer_static,
1775 bound_count += bound_spans.len();
1777 let drop_predicate = bound_spans.len() == bounds.len();
1779 dropped_predicate_count += 1;
1782 // If all the bounds on a predicate were inferable and there are
1783 // further predicates, we want to eat the trailing comma.
1784 if drop_predicate && i + 1 < num_predicates {
1785 let next_predicate_span = hir_generics.where_clause.predicates[i + 1].span();
1786 where_lint_spans.push(
1787 span.to(next_predicate_span.shrink_to_lo())
1790 where_lint_spans.extend(
1791 self.consolidate_outlives_bound_spans(
1792 span.shrink_to_lo(),
1800 // If all predicates are inferable, drop the entire clause
1801 // (including the `where`)
1802 if num_predicates > 0 && dropped_predicate_count == num_predicates {
1803 let where_span = hir_generics.where_clause.span()
1804 .expect("span of (nonempty) where clause should exist");
1805 // Extend the where clause back to the closing `>` of the
1806 // generics, except for tuple struct, which have the `where`
1807 // after the fields of the struct.
1808 let full_where_span = if let hir::ItemKind::Struct(hir::VariantData::Tuple(..), _)
1813 hir_generics.span.shrink_to_hi().to(where_span)
1819 lint_spans.extend(where_lint_spans);
1822 if !lint_spans.is_empty() {
1823 let mut err = cx.struct_span_lint(
1824 EXPLICIT_OUTLIVES_REQUIREMENTS,
1826 "outlives requirements can be inferred"
1828 err.multipart_suggestion(
1829 if bound_count == 1 {
1832 "remove these bounds"
1834 lint_spans.into_iter().map(|span| (span, "".to_owned())).collect::<Vec<_>>(),
1835 Applicability::MachineApplicable