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::Def;
25 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
26 use rustc::ty::{self, Ty};
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;
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::keywords;
46 use syntax::errors::{Applicability, DiagnosticBuilder};
47 use syntax::print::pprust::expr_to_string;
48 use syntax::visit::FnKind;
49 use syntax::struct_span_err;
51 use rustc::hir::{self, GenericParamKind, PatKind};
53 use crate::nonstandard_style::{MethodLateContext, method_context};
57 // hardwired lints from librustc
58 pub use lint::builtin::*;
63 "suggest using `loop { }` instead of `while true { }`"
66 #[derive(Copy, Clone)]
69 impl LintPass for WhileTrue {
70 fn name(&self) -> &'static str {
74 fn get_lints(&self) -> LintArray {
75 lint_array!(WHILE_TRUE)
79 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
80 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
81 if let hir::ExprKind::While(ref cond, ..) = e.node {
82 if let hir::ExprKind::Lit(ref lit) = cond.node {
83 if let ast::LitKind::Bool(true) = lit.node {
84 if lit.span.ctxt() == SyntaxContext::empty() {
85 let msg = "denote infinite loops with `loop { ... }`";
86 let condition_span = cx.tcx.sess.source_map().def_span(e.span);
87 let mut err = cx.struct_span_lint(WHILE_TRUE, condition_span, msg);
88 err.span_suggestion_short(
92 Applicability::MachineApplicable
105 "use of owned (Box type) heap memory"
108 #[derive(Copy, Clone)]
109 pub struct BoxPointers;
112 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext<'_, '_>, span: Span, ty: Ty<'_>) {
113 for leaf_ty in ty.walk() {
114 if leaf_ty.is_box() {
115 let m = format!("type uses owned (Box type) pointers: {}", ty);
116 cx.span_lint(BOX_POINTERS, span, &m);
122 impl LintPass for BoxPointers {
123 fn name(&self) -> &'static str {
127 fn get_lints(&self) -> LintArray {
128 lint_array!(BOX_POINTERS)
132 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
133 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
135 hir::ItemKind::Fn(..) |
136 hir::ItemKind::Ty(..) |
137 hir::ItemKind::Enum(..) |
138 hir::ItemKind::Struct(..) |
139 hir::ItemKind::Union(..) => {
140 let def_id = cx.tcx.hir().local_def_id_from_hir_id(it.hir_id);
141 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
146 // If it's a struct, we also have to check the fields' types
148 hir::ItemKind::Struct(ref struct_def, _) |
149 hir::ItemKind::Union(ref struct_def, _) => {
150 for struct_field in struct_def.fields() {
151 let def_id = cx.tcx.hir().local_def_id_from_hir_id(struct_field.hir_id);
152 self.check_heap_type(cx, struct_field.span,
153 cx.tcx.type_of(def_id));
160 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
161 let ty = cx.tables.node_type(e.hir_id);
162 self.check_heap_type(cx, e.span, ty);
167 NON_SHORTHAND_FIELD_PATTERNS,
169 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
172 #[derive(Copy, Clone)]
173 pub struct NonShorthandFieldPatterns;
175 impl LintPass for NonShorthandFieldPatterns {
176 fn name(&self) -> &'static str {
177 "NonShorthandFieldPatterns"
180 fn get_lints(&self) -> LintArray {
181 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
185 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
186 fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat) {
187 if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node {
188 let variant = cx.tables.pat_ty(pat).ty_adt_def()
189 .expect("struct pattern type is not an ADT")
190 .variant_of_def(cx.tables.qpath_def(qpath, pat.hir_id));
191 for fieldpat in field_pats {
192 if fieldpat.node.is_shorthand {
195 if fieldpat.span.ctxt().outer().expn_info().is_some() {
196 // Don't lint if this is a macro expansion: macro authors
197 // shouldn't have to worry about this kind of style issue
201 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
202 if cx.tcx.find_field_index(ident, &variant) ==
203 Some(cx.tcx.field_index(fieldpat.node.hir_id, cx.tables)) {
204 let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
206 &format!("the `{}:` in this pattern is redundant", ident));
207 let subspan = cx.tcx.sess.source_map().span_through_char(fieldpat.span,
209 err.span_suggestion_short(
213 Applicability::MachineApplicable
226 "usage of `unsafe` code"
229 #[derive(Copy, Clone)]
230 pub struct UnsafeCode;
232 impl LintPass for UnsafeCode {
233 fn name(&self) -> &'static str {
237 fn get_lints(&self) -> LintArray {
238 lint_array!(UNSAFE_CODE)
243 fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) {
244 // This comes from a macro that has #[allow_internal_unsafe].
245 if span.allows_unsafe() {
249 cx.span_lint(UNSAFE_CODE, span, desc);
253 impl EarlyLintPass for UnsafeCode {
254 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
255 if attr.check_name("allow_internal_unsafe") {
256 self.report_unsafe(cx, attr.span, "`allow_internal_unsafe` allows defining \
257 macros using unsafe without triggering \
258 the `unsafe_code` lint at their call site");
262 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
263 if let ast::ExprKind::Block(ref blk, _) = e.node {
264 // Don't warn about generated blocks, that'll just pollute the output.
265 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
266 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
271 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
273 ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => {
274 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
277 ast::ItemKind::Impl(ast::Unsafety::Unsafe, ..) => {
278 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
285 fn check_fn(&mut self,
286 cx: &EarlyContext<'_>,
292 FnKind::ItemFn(_, ast::FnHeader { unsafety: ast::Unsafety::Unsafe, .. }, ..) => {
293 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
296 FnKind::Method(_, sig, ..) => {
297 if sig.header.unsafety == ast::Unsafety::Unsafe {
298 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
306 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, item: &ast::TraitItem) {
307 if let ast::TraitItemKind::Method(ref sig, None) = item.node {
308 if sig.header.unsafety == ast::Unsafety::Unsafe {
309 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
318 "detects missing documentation for public members",
319 report_in_external_macro: true
322 pub struct MissingDoc {
323 /// Stack of whether `#[doc(hidden)]` is set at each level which has lint attributes.
324 doc_hidden_stack: Vec<bool>,
326 /// Private traits or trait items that leaked through. Don't check their methods.
327 private_traits: FxHashSet<hir::HirId>,
330 fn has_doc(attr: &ast::Attribute) -> bool {
331 if !attr.check_name("doc") {
335 if attr.is_value_str() {
339 if let Some(list) = attr.meta_item_list() {
341 if meta.check_name("include") || meta.check_name("hidden") {
351 pub fn new() -> MissingDoc {
353 doc_hidden_stack: vec![false],
354 private_traits: FxHashSet::default(),
358 fn doc_hidden(&self) -> bool {
359 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
362 fn check_missing_docs_attrs(&self,
363 cx: &LateContext<'_, '_>,
364 id: Option<hir::HirId>,
365 attrs: &[ast::Attribute],
367 desc: &'static str) {
368 // If we're building a test harness, then warning about
369 // documentation is probably not really relevant right now.
370 if cx.sess().opts.test {
374 // `#[doc(hidden)]` disables missing_docs check.
375 if self.doc_hidden() {
379 // Only check publicly-visible items, using the result from the privacy pass.
380 // It's an option so the crate root can also use this function (it doesn't
382 if let Some(id) = id {
383 let node_id = cx.tcx.hir().hir_to_node_id(id);
384 if !cx.access_levels.is_exported(node_id) {
389 let has_doc = attrs.iter().any(|a| has_doc(a));
391 cx.span_lint(MISSING_DOCS,
392 cx.tcx.sess.source_map().def_span(sp),
393 &format!("missing documentation for {}", desc));
398 impl LintPass for MissingDoc {
399 fn name(&self) -> &'static str {
403 fn get_lints(&self) -> LintArray {
404 lint_array!(MISSING_DOCS)
408 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
409 fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) {
410 let doc_hidden = self.doc_hidden() ||
411 attrs.iter().any(|attr| {
412 attr.check_name("doc") &&
413 match attr.meta_item_list() {
415 Some(l) => attr::list_contains_name(&l, "hidden"),
418 self.doc_hidden_stack.push(doc_hidden);
421 fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) {
422 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
425 fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate) {
426 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
428 for macro_def in &krate.exported_macros {
429 let has_doc = macro_def.attrs.iter().any(|a| has_doc(a));
431 cx.span_lint(MISSING_DOCS,
432 cx.tcx.sess.source_map().def_span(macro_def.span),
433 "missing documentation for macro");
438 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
439 let desc = match it.node {
440 hir::ItemKind::Fn(..) => "a function",
441 hir::ItemKind::Mod(..) => "a module",
442 hir::ItemKind::Enum(..) => "an enum",
443 hir::ItemKind::Struct(..) => "a struct",
444 hir::ItemKind::Union(..) => "a union",
445 hir::ItemKind::Trait(.., ref trait_item_refs) => {
446 // Issue #11592, traits are always considered exported, even when private.
447 if let hir::VisibilityKind::Inherited = it.vis.node {
448 self.private_traits.insert(it.hir_id);
449 for trait_item_ref in trait_item_refs {
450 self.private_traits.insert(trait_item_ref.id.hir_id);
456 hir::ItemKind::Ty(..) => "a type alias",
457 hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
458 // If the trait is private, add the impl items to private_traits so they don't get
459 // reported for missing docs.
460 let real_trait = trait_ref.path.def.def_id();
461 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(real_trait) {
462 match cx.tcx.hir().find_by_hir_id(hir_id) {
463 Some(Node::Item(item)) => {
464 if let hir::VisibilityKind::Inherited = item.vis.node {
465 for impl_item_ref in impl_item_refs {
466 self.private_traits.insert(impl_item_ref.id.hir_id);
475 hir::ItemKind::Const(..) => "a constant",
476 hir::ItemKind::Static(..) => "a static",
480 self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, desc);
483 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem) {
484 if self.private_traits.contains(&trait_item.hir_id) {
488 let desc = match trait_item.node {
489 hir::TraitItemKind::Const(..) => "an associated constant",
490 hir::TraitItemKind::Method(..) => "a trait method",
491 hir::TraitItemKind::Type(..) => "an associated type",
494 self.check_missing_docs_attrs(cx,
495 Some(trait_item.hir_id),
501 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
502 // If the method is an impl for a trait, don't doc.
503 if method_context(cx, impl_item.hir_id) == MethodLateContext::TraitImpl {
507 let desc = match impl_item.node {
508 hir::ImplItemKind::Const(..) => "an associated constant",
509 hir::ImplItemKind::Method(..) => "a method",
510 hir::ImplItemKind::Type(_) => "an associated type",
511 hir::ImplItemKind::Existential(_) => "an associated existential type",
513 self.check_missing_docs_attrs(cx,
514 Some(impl_item.hir_id),
520 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField) {
521 if !sf.is_positional() {
522 self.check_missing_docs_attrs(cx,
530 fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant, _: &hir::Generics) {
531 self.check_missing_docs_attrs(cx,
532 Some(v.node.data.hir_id()),
540 pub MISSING_COPY_IMPLEMENTATIONS,
542 "detects potentially-forgotten implementations of `Copy`"
545 #[derive(Copy, Clone)]
546 pub struct MissingCopyImplementations;
548 impl LintPass for MissingCopyImplementations {
549 fn name(&self) -> &'static str {
550 "MissingCopyImplementations"
553 fn get_lints(&self) -> LintArray {
554 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
558 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
559 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
560 let node_id = cx.tcx.hir().hir_to_node_id(item.hir_id);
561 if !cx.access_levels.is_reachable(node_id) {
564 let (def, ty) = match item.node {
565 hir::ItemKind::Struct(_, ref ast_generics) => {
566 if !ast_generics.params.is_empty() {
569 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id_from_hir_id(item.hir_id));
570 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
572 hir::ItemKind::Union(_, ref ast_generics) => {
573 if !ast_generics.params.is_empty() {
576 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id_from_hir_id(item.hir_id));
577 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
579 hir::ItemKind::Enum(_, ref ast_generics) => {
580 if !ast_generics.params.is_empty() {
583 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id_from_hir_id(item.hir_id));
584 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
588 if def.has_dtor(cx.tcx) {
591 let param_env = ty::ParamEnv::empty();
592 if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span) {
595 if param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
596 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
598 "type could implement `Copy`; consider adding `impl \
605 MISSING_DEBUG_IMPLEMENTATIONS,
607 "detects missing implementations of fmt::Debug"
610 pub struct MissingDebugImplementations {
611 impling_types: Option<HirIdSet>,
614 impl MissingDebugImplementations {
615 pub fn new() -> MissingDebugImplementations {
616 MissingDebugImplementations { impling_types: None }
620 impl LintPass for MissingDebugImplementations {
621 fn name(&self) -> &'static str {
622 "MissingDebugImplementations"
625 fn get_lints(&self) -> LintArray {
626 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
630 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
631 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
632 let node_id = cx.tcx.hir().hir_to_node_id(item.hir_id);
633 if !cx.access_levels.is_reachable(node_id) {
638 hir::ItemKind::Struct(..) |
639 hir::ItemKind::Union(..) |
640 hir::ItemKind::Enum(..) => {}
644 let debug = match cx.tcx.lang_items().debug_trait() {
645 Some(debug) => debug,
649 if self.impling_types.is_none() {
650 let mut impls = HirIdSet::default();
651 cx.tcx.for_each_impl(debug, |d| {
652 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
653 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
654 impls.insert(hir_id);
659 self.impling_types = Some(impls);
660 debug!("{:?}", self.impling_types);
663 if !self.impling_types.as_ref().unwrap().contains(&item.hir_id) {
664 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
666 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
667 or a manual implementation")
673 pub ANONYMOUS_PARAMETERS,
675 "detects anonymous parameters"
678 /// Checks for use of anonymous parameters (RFC 1685).
679 #[derive(Copy, Clone)]
680 pub struct AnonymousParameters;
682 impl LintPass for AnonymousParameters {
683 fn name(&self) -> &'static str {
684 "AnonymousParameters"
687 fn get_lints(&self) -> LintArray {
688 lint_array!(ANONYMOUS_PARAMETERS)
692 impl EarlyLintPass for AnonymousParameters {
693 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::TraitItem) {
695 ast::TraitItemKind::Method(ref sig, _) => {
696 for arg in sig.decl.inputs.iter() {
698 ast::PatKind::Ident(_, ident, None) => {
699 if ident.name == keywords::Invalid.name() {
703 .span_to_snippet(arg.ty.span);
705 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
706 (snip, Applicability::MachineApplicable)
708 ("<type>".to_owned(), Applicability::HasPlaceholders)
712 ANONYMOUS_PARAMETERS,
714 "anonymous parameters are deprecated and will be \
715 removed in the next edition."
718 "Try naming the parameter or explicitly \
720 format!("_: {}", ty_snip),
734 /// Check for use of attributes which have been deprecated.
736 pub struct DeprecatedAttr {
737 // This is not free to compute, so we want to keep it around, rather than
738 // compute it for every attribute.
739 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeTemplate, AttributeGate)>,
742 impl DeprecatedAttr {
743 pub fn new() -> DeprecatedAttr {
745 depr_attrs: deprecated_attributes(),
750 impl LintPass for DeprecatedAttr {
751 fn name(&self) -> &'static str {
755 fn get_lints(&self) -> LintArray {
760 impl EarlyLintPass for DeprecatedAttr {
761 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
762 for &&(n, _, _, ref g) in &self.depr_attrs {
763 if attr.name() == n {
764 if let &AttributeGate::Gated(Stability::Deprecated(link, suggestion),
768 let msg = format!("use of deprecated attribute `{}`: {}. See {}",
770 let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
771 err.span_suggestion_short(
773 suggestion.unwrap_or("remove this attribute"),
775 Applicability::MachineApplicable
786 pub UNUSED_DOC_COMMENTS,
788 "detects doc comments that aren't used by rustdoc"
791 #[derive(Copy, Clone)]
792 pub struct UnusedDocComment;
794 impl LintPass for UnusedDocComment {
795 fn name(&self) -> &'static str {
799 fn get_lints(&self) -> LintArray {
800 lint_array![UNUSED_DOC_COMMENTS]
804 impl UnusedDocComment {
805 fn warn_if_doc<'a, 'tcx,
806 I: Iterator<Item=&'a ast::Attribute>,
807 C: LintContext<'tcx>>(&self, mut attrs: I, cx: &C) {
808 if let Some(attr) = attrs.find(|a| a.is_value_str() && a.check_name("doc")) {
809 cx.struct_span_lint(UNUSED_DOC_COMMENTS, attr.span, "doc comment not used by rustdoc")
815 impl EarlyLintPass for UnusedDocComment {
816 fn check_local(&mut self, cx: &EarlyContext<'_>, decl: &ast::Local) {
817 self.warn_if_doc(decl.attrs.iter(), cx);
820 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
821 self.warn_if_doc(arm.attrs.iter(), cx);
824 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
825 self.warn_if_doc(expr.attrs.iter(), cx);
832 "compiler plugin used as ordinary library in non-plugin crate"
835 #[derive(Copy, Clone)]
836 pub struct PluginAsLibrary;
838 impl LintPass for PluginAsLibrary {
839 fn name(&self) -> &'static str {
843 fn get_lints(&self) -> LintArray {
844 lint_array![PLUGIN_AS_LIBRARY]
848 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
849 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
850 if cx.tcx.plugin_registrar_fn(LOCAL_CRATE).is_some() {
851 // We're compiling a plugin; it's fine to link other plugins.
856 hir::ItemKind::ExternCrate(..) => (),
860 let def_id = cx.tcx.hir().local_def_id_from_hir_id(it.hir_id);
861 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
862 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
864 // Probably means we aren't linking the crate for some reason.
866 // Not sure if / when this could happen.
872 cx.span_lint(PLUGIN_AS_LIBRARY,
874 "compiler plugin used as an ordinary library");
880 NO_MANGLE_CONST_ITEMS,
882 "const items will not have their symbols exported"
886 NO_MANGLE_GENERIC_ITEMS,
888 "generic items must be mangled"
891 #[derive(Copy, Clone)]
892 pub struct InvalidNoMangleItems;
894 impl LintPass for InvalidNoMangleItems {
895 fn name(&self) -> &'static str {
896 "InvalidNoMangleItems"
899 fn get_lints(&self) -> LintArray {
900 lint_array!(NO_MANGLE_CONST_ITEMS,
901 NO_MANGLE_GENERIC_ITEMS)
905 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
906 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
908 hir::ItemKind::Fn(.., ref generics, _) => {
909 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
910 for param in &generics.params {
912 GenericParamKind::Lifetime { .. } => {}
913 GenericParamKind::Type { .. } |
914 GenericParamKind::Const { .. } => {
915 let mut err = cx.struct_span_lint(
916 NO_MANGLE_GENERIC_ITEMS,
918 "functions generic over types or consts must be mangled",
920 err.span_suggestion_short(
922 "remove this attribute",
924 // Use of `#[no_mangle]` suggests FFI intent; correct
925 // fix may be to monomorphize source by hand
926 Applicability::MaybeIncorrect
935 hir::ItemKind::Const(..) => {
936 if attr::contains_name(&it.attrs, "no_mangle") {
937 // Const items do not refer to a particular location in memory, and therefore
938 // don't have anything to attach a symbol to
939 let msg = "const items should never be #[no_mangle]";
940 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
942 // account for "pub const" (#45562)
943 let start = cx.tcx.sess.source_map().span_to_snippet(it.span)
944 .map(|snippet| snippet.find("const").unwrap_or(0))
945 .unwrap_or(0) as u32;
946 // `const` is 5 chars
947 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
950 "try a static value",
951 "pub static".to_owned(),
952 Applicability::MachineApplicable
962 #[derive(Clone, Copy)]
963 pub struct MutableTransmutes;
968 "mutating transmuted &mut T from &T may cause undefined behavior"
971 impl LintPass for MutableTransmutes {
972 fn name(&self) -> &'static str {
976 fn get_lints(&self) -> LintArray {
977 lint_array!(MUTABLE_TRANSMUTES)
981 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
982 fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr) {
983 use rustc_target::spec::abi::Abi::RustIntrinsic;
985 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
986 consider instead using an UnsafeCell";
987 match get_transmute_from_to(cx, expr) {
988 Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
989 if to_mt == hir::Mutability::MutMutable &&
990 from_mt == hir::Mutability::MutImmutable {
991 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
997 fn get_transmute_from_to<'a, 'tcx>
998 (cx: &LateContext<'a, 'tcx>,
1000 -> Option<(&'tcx ty::TyKind<'tcx>, &'tcx ty::TyKind<'tcx>)> {
1001 let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
1002 cx.tables.qpath_def(qpath, expr.hir_id)
1006 if let Def::Fn(did) = def {
1007 if !def_id_is_transmute(cx, did) {
1010 let sig = cx.tables.node_type(expr.hir_id).fn_sig(cx.tcx);
1011 let from = sig.inputs().skip_binder()[0];
1012 let to = *sig.output().skip_binder();
1013 return Some((&from.sty, &to.sty));
1018 fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
1019 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1020 cx.tcx.item_name(def_id) == "transmute"
1025 /// Forbids using the `#[feature(...)]` attribute
1026 #[derive(Copy, Clone)]
1027 pub struct UnstableFeatures;
1032 "enabling unstable features (deprecated. do not use)"
1035 impl LintPass for UnstableFeatures {
1036 fn name(&self) -> &'static str {
1040 fn get_lints(&self) -> LintArray {
1041 lint_array!(UNSTABLE_FEATURES)
1045 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1046 fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) {
1047 if attr.check_name("feature") {
1048 if let Some(items) = attr.meta_item_list() {
1050 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1057 /// Lint for unions that contain fields with possibly non-trivial destructors.
1058 pub struct UnionsWithDropFields;
1061 UNIONS_WITH_DROP_FIELDS,
1063 "use of unions that contain fields with possibly non-trivial drop code"
1066 impl LintPass for UnionsWithDropFields {
1067 fn name(&self) -> &'static str {
1068 "UnionsWithDropFields"
1071 fn get_lints(&self) -> LintArray {
1072 lint_array!(UNIONS_WITH_DROP_FIELDS)
1076 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1077 fn check_item(&mut self, ctx: &LateContext<'_, '_>, item: &hir::Item) {
1078 if let hir::ItemKind::Union(ref vdata, _) = item.node {
1079 for field in vdata.fields() {
1080 let field_ty = ctx.tcx.type_of(
1081 ctx.tcx.hir().local_def_id_from_hir_id(field.hir_id));
1082 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1083 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1085 "union contains a field with possibly non-trivial drop code, \
1086 drop code of union fields is ignored when dropping the union");
1094 /// Lint for items marked `pub` that aren't reachable from other crates.
1095 #[derive(Copy, Clone)]
1096 pub struct UnreachablePub;
1099 pub UNREACHABLE_PUB,
1101 "`pub` items not reachable from crate root"
1104 impl LintPass for UnreachablePub {
1105 fn name(&self) -> &'static str {
1109 fn get_lints(&self) -> LintArray {
1110 lint_array!(UNREACHABLE_PUB)
1114 impl UnreachablePub {
1115 fn perform_lint(&self, cx: &LateContext<'_, '_>, what: &str, id: hir::HirId,
1116 vis: &hir::Visibility, span: Span, exportable: bool) {
1117 let mut applicability = Applicability::MachineApplicable;
1118 let node_id = cx.tcx.hir().hir_to_node_id(id);
1120 hir::VisibilityKind::Public if !cx.access_levels.is_reachable(node_id) => {
1121 if span.ctxt().outer().expn_info().is_some() {
1122 applicability = Applicability::MaybeIncorrect;
1124 let def_span = cx.tcx.sess.source_map().def_span(span);
1125 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1126 &format!("unreachable `pub` {}", what));
1127 let replacement = if cx.tcx.features().crate_visibility_modifier {
1133 err.span_suggestion(
1135 "consider restricting its visibility",
1140 err.help("or consider exporting it for use by other crates");
1150 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1151 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1152 self.perform_lint(cx, "item", item.hir_id, &item.vis, item.span, true);
1155 fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, foreign_item: &hir::ForeignItem) {
1156 self.perform_lint(cx, "item", foreign_item.hir_id, &foreign_item.vis,
1157 foreign_item.span, true);
1160 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) {
1161 self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false);
1164 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
1165 self.perform_lint(cx, "item", impl_item.hir_id, &impl_item.vis, impl_item.span, false);
1169 /// Lint for trait and lifetime bounds in type aliases being mostly ignored.
1170 /// They are relevant when using associated types, but otherwise neither checked
1171 /// at definition site nor enforced at use site.
1173 pub struct TypeAliasBounds;
1178 "bounds in type aliases are not enforced"
1181 impl LintPass for TypeAliasBounds {
1182 fn name(&self) -> &'static str {
1186 fn get_lints(&self) -> LintArray {
1187 lint_array!(TYPE_ALIAS_BOUNDS)
1191 impl TypeAliasBounds {
1192 fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1194 hir::QPath::TypeRelative(ref ty, _) => {
1195 // If this is a type variable, we found a `T::Assoc`.
1197 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1199 Def::TyParam(_) => true,
1206 hir::QPath::Resolved(..) => false,
1210 fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder<'_>) {
1211 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1212 // bound. Let's see if this type does that.
1214 // We use a HIR visitor to walk the type.
1215 use rustc::hir::intravisit::{self, Visitor};
1216 struct WalkAssocTypes<'a, 'db> where 'db: 'a {
1217 err: &'a mut DiagnosticBuilder<'db>
1219 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1220 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1222 intravisit::NestedVisitorMap::None
1225 fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: hir::HirId, span: Span) {
1226 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1227 self.err.span_help(span,
1228 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1229 associated types in type aliases");
1231 intravisit::walk_qpath(self, qpath, id, span)
1235 // Let's go for a walk!
1236 let mut visitor = WalkAssocTypes { err };
1237 visitor.visit_ty(ty);
1241 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1242 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1243 let (ty, type_alias_generics) = match item.node {
1244 hir::ItemKind::Ty(ref ty, ref generics) => (&*ty, generics),
1247 let mut suggested_changing_assoc_types = false;
1248 // There must not be a where clause
1249 if !type_alias_generics.where_clause.predicates.is_empty() {
1250 let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1251 .map(|pred| pred.span()).collect();
1252 let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1253 "where clauses are not enforced in type aliases");
1254 err.help("the clause will not be checked when the type alias is used, \
1255 and should be removed");
1256 if !suggested_changing_assoc_types {
1257 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1258 suggested_changing_assoc_types = true;
1262 // The parameters must not have bounds
1263 for param in type_alias_generics.params.iter() {
1264 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1265 if !spans.is_empty() {
1266 let mut err = cx.struct_span_lint(
1269 "bounds on generic parameters are not enforced in type aliases",
1271 err.help("the bound will not be checked when the type alias is used, \
1272 and should be removed");
1273 if !suggested_changing_assoc_types {
1274 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1275 suggested_changing_assoc_types = true;
1283 /// Lint constants that are erroneous.
1284 /// Without this lint, we might not get any diagnostic if the constant is
1285 /// unused within this crate, even though downstream crates can't use it
1286 /// without producing an error.
1287 pub struct UnusedBrokenConst;
1289 impl LintPass for UnusedBrokenConst {
1290 fn name(&self) -> &'static str {
1294 fn get_lints(&self) -> LintArray {
1298 fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) {
1299 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
1300 let is_static = cx.tcx.is_static(def_id).is_some();
1301 let param_env = if is_static {
1302 // Use the same param_env as `codegen_static_initializer`, to reuse the cache.
1303 ty::ParamEnv::reveal_all()
1305 cx.tcx.param_env(def_id)
1307 let cid = ::rustc::mir::interpret::GlobalId {
1308 instance: ty::Instance::mono(cx.tcx, def_id),
1311 // trigger the query once for all constants since that will already report the errors
1312 let _ = cx.tcx.const_eval(param_env.and(cid));
1315 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1316 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1318 hir::ItemKind::Const(_, body_id) => {
1319 check_const(cx, body_id);
1321 hir::ItemKind::Static(_, _, body_id) => {
1322 check_const(cx, body_id);
1329 /// Lint for trait and lifetime bounds that don't depend on type parameters
1330 /// which either do nothing, or stop the item from being used.
1331 pub struct TrivialConstraints;
1336 "these bounds don't depend on an type parameters"
1339 impl LintPass for TrivialConstraints {
1340 fn name(&self) -> &'static str {
1341 "TrivialConstraints"
1344 fn get_lints(&self) -> LintArray {
1345 lint_array!(TRIVIAL_BOUNDS)
1349 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1352 cx: &LateContext<'a, 'tcx>,
1353 item: &'tcx hir::Item,
1355 use rustc::ty::fold::TypeFoldable;
1356 use rustc::ty::Predicate::*;
1359 if cx.tcx.features().trivial_bounds {
1360 let def_id = cx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1361 let predicates = cx.tcx.predicates_of(def_id);
1362 for &(predicate, span) in &predicates.predicates {
1363 let predicate_kind_name = match predicate {
1364 Trait(..) => "Trait",
1366 RegionOutlives(..) => "Lifetime",
1368 // Ignore projections, as they can only be global
1369 // if the trait bound is global
1371 // Ignore bounds that a user can't type
1376 ConstEvaluatable(..) => continue,
1378 if predicate.is_global() {
1382 &format!("{} bound {} does not depend on any type \
1383 or lifetime parameters", predicate_kind_name, predicate),
1392 /// Does nothing as a lint pass, but registers some `Lint`s
1393 /// which are used by other parts of the compiler.
1394 #[derive(Copy, Clone)]
1395 pub struct SoftLints;
1397 impl LintPass for SoftLints {
1398 fn name(&self) -> &'static str {
1402 fn get_lints(&self) -> LintArray {
1406 NON_SHORTHAND_FIELD_PATTERNS,
1409 MISSING_COPY_IMPLEMENTATIONS,
1410 MISSING_DEBUG_IMPLEMENTATIONS,
1411 ANONYMOUS_PARAMETERS,
1412 UNUSED_DOC_COMMENTS,
1414 NO_MANGLE_CONST_ITEMS,
1415 NO_MANGLE_GENERIC_ITEMS,
1418 UNIONS_WITH_DROP_FIELDS,
1427 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1429 "`...` range patterns are deprecated"
1433 pub struct EllipsisInclusiveRangePatterns;
1435 impl LintPass for EllipsisInclusiveRangePatterns {
1436 fn name(&self) -> &'static str {
1437 "EllipsisInclusiveRangePatterns"
1440 fn get_lints(&self) -> LintArray {
1441 lint_array!(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS)
1445 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1446 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat, visit_subpats: &mut bool) {
1447 use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot};
1449 /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1450 /// corresponding to the ellipsis.
1451 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(&P<Expr>, &P<Expr>, Span)> {
1453 PatKind::Range(a, b, Spanned { span, node: RangeEnd::Included(DotDotDot), .. }) => {
1460 let (parenthesise, endpoints) = match &pat.node {
1461 PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)),
1462 _ => (false, matches_ellipsis_pat(pat)),
1465 if let Some((start, end, join)) = endpoints {
1466 let msg = "`...` range patterns are deprecated";
1467 let suggestion = "use `..=` for an inclusive range";
1469 *visit_subpats = false;
1470 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, pat.span, msg);
1471 err.span_suggestion(
1474 format!("&({}..={})", expr_to_string(&start), expr_to_string(&end)),
1475 Applicability::MachineApplicable,
1479 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, join, msg);
1480 err.span_suggestion_short(
1484 Applicability::MachineApplicable,
1493 UNNAMEABLE_TEST_ITEMS,
1495 "detects an item that cannot be named being marked as #[test_case]",
1496 report_in_external_macro: true
1499 pub struct UnnameableTestItems {
1500 boundary: hir::HirId, // HirId of the item under which things are not nameable
1501 items_nameable: bool,
1504 impl UnnameableTestItems {
1505 pub fn new() -> Self {
1507 boundary: hir::DUMMY_HIR_ID,
1508 items_nameable: true
1513 impl LintPass for UnnameableTestItems {
1514 fn name(&self) -> &'static str {
1515 "UnnameableTestItems"
1518 fn get_lints(&self) -> LintArray {
1519 lint_array!(UNNAMEABLE_TEST_ITEMS)
1523 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
1524 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1525 if self.items_nameable {
1526 if let hir::ItemKind::Mod(..) = it.node {}
1528 self.items_nameable = false;
1529 self.boundary = it.hir_id;
1534 if let Some(attr) = attr::find_by_name(&it.attrs, "rustc_test_marker") {
1535 cx.struct_span_lint(
1536 UNNAMEABLE_TEST_ITEMS,
1538 "cannot test inner items",
1543 fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item) {
1544 if !self.items_nameable && self.boundary == it.hir_id {
1545 self.items_nameable = true;
1553 "detects edition keywords being used as an identifier"
1556 /// Check for uses of edition keywords used as an identifier.
1557 #[derive(Copy, Clone)]
1558 pub struct KeywordIdents;
1560 impl LintPass for KeywordIdents {
1561 fn name(&self) -> &'static str {
1565 fn get_lints(&self) -> LintArray {
1566 lint_array!(KEYWORD_IDENTS)
1570 impl KeywordIdents {
1571 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) {
1572 for tt in tokens.into_trees() {
1574 TokenTree::Token(span, tok) => match tok.ident() {
1575 // only report non-raw idents
1576 Some((ident, false)) => {
1577 self.check_ident(cx, ast::Ident {
1578 span: span.substitute_dummy(ident.span),
1584 TokenTree::Delimited(_, _, tts) => {
1585 self.check_tokens(cx, tts)
1592 impl EarlyLintPass for KeywordIdents {
1593 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) {
1594 self.check_tokens(cx, mac_def.stream());
1596 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
1597 self.check_tokens(cx, mac.node.tts.clone().into());
1599 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: ast::Ident) {
1600 let ident_str = &ident.as_str()[..];
1601 let cur_edition = cx.sess.edition();
1602 let is_raw_ident = |ident: ast::Ident| {
1603 cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span)
1605 let next_edition = match cur_edition {
1606 Edition::Edition2015 => {
1608 "async" | "try" | "dyn" => Edition::Edition2018,
1609 // Only issue warnings for `await` if the `async_await`
1610 // feature isn't being used. Otherwise, users need
1611 // to keep using `await` for the macro exposed by std.
1612 "await" if !cx.sess.features_untracked().async_await => Edition::Edition2018,
1617 // There are no new keywords yet for the 2018 edition and beyond.
1618 // However, `await` is a "false" keyword in the 2018 edition,
1619 // and can only be used if the `async_await` feature is enabled.
1620 // Otherwise, we emit an error.
1622 if "await" == ident_str
1623 && !cx.sess.features_untracked().async_await
1624 && !is_raw_ident(ident)
1626 let mut err = struct_span_err!(
1630 "`await` is a keyword in the {} edition", cur_edition,
1632 err.span_suggestion(
1634 "you can use a raw identifier to stay compatible",
1635 "r#await".to_string(),
1636 Applicability::MachineApplicable,
1644 // don't lint `r#foo`
1645 if is_raw_ident(ident) {
1649 let mut lint = cx.struct_span_lint(
1652 &format!("`{}` is a keyword in the {} edition",
1656 lint.span_suggestion(
1658 "you can use a raw identifier to stay compatible",
1659 format!("r#{}", ident.as_str()),
1660 Applicability::MachineApplicable,
1667 pub struct ExplicitOutlivesRequirements;
1669 impl LintPass for ExplicitOutlivesRequirements {
1670 fn name(&self) -> &'static str {
1671 "ExplicitOutlivesRequirements"
1674 fn get_lints(&self) -> LintArray {
1675 lint_array![EXPLICIT_OUTLIVES_REQUIREMENTS]
1679 impl ExplicitOutlivesRequirements {
1680 fn collect_outlives_bound_spans(
1682 cx: &LateContext<'_, '_>,
1685 bounds: &hir::GenericBounds,
1687 ) -> Vec<(usize, Span)> {
1688 // For lack of a more elegant strategy for comparing the `ty::Predicate`s
1689 // returned by this query with the params/bounds grabbed from the HIR—and
1690 // with some regrets—we're going to covert the param/lifetime names to
1692 let inferred_outlives = cx.tcx.inferred_outlives_of(item_def_id);
1694 let ty_lt_names = inferred_outlives.iter().filter_map(|pred| {
1695 let binder = match pred {
1696 ty::Predicate::TypeOutlives(binder) => binder,
1697 _ => { return None; }
1699 let ty_outlives_pred = binder.skip_binder();
1700 let ty_name = match ty_outlives_pred.0.sty {
1701 ty::Param(param) => param.name.to_string(),
1702 _ => { return None; }
1704 let lt_name = match ty_outlives_pred.1 {
1705 ty::RegionKind::ReEarlyBound(region) => {
1706 region.name.to_string()
1708 _ => { return None; }
1710 Some((ty_name, lt_name))
1711 }).collect::<Vec<_>>();
1713 let mut bound_spans = Vec::new();
1714 for (i, bound) in bounds.iter().enumerate() {
1715 if let hir::GenericBound::Outlives(lifetime) = bound {
1716 let is_static = match lifetime.name {
1717 hir::LifetimeName::Static => true,
1720 if is_static && !infer_static {
1721 // infer-outlives for 'static is still feature-gated (tracking issue #44493)
1725 let lt_name = &lifetime.name.ident().to_string();
1726 if ty_lt_names.contains(&(param_name.to_owned(), lt_name.to_owned())) {
1727 bound_spans.push((i, bound.span()));
1734 fn consolidate_outlives_bound_spans(
1737 bounds: &hir::GenericBounds,
1738 bound_spans: Vec<(usize, Span)>
1740 if bounds.is_empty() {
1743 if bound_spans.len() == bounds.len() {
1744 let (_, last_bound_span) = bound_spans[bound_spans.len()-1];
1745 // If all bounds are inferable, we want to delete the colon, so
1746 // start from just after the parameter (span passed as argument)
1747 vec![lo.to(last_bound_span)]
1749 let mut merged = Vec::new();
1750 let mut last_merged_i = None;
1752 let mut from_start = true;
1753 for (i, bound_span) in bound_spans {
1754 match last_merged_i {
1755 // If the first bound is inferable, our span should also eat the trailing `+`
1757 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
1758 last_merged_i = Some(0);
1760 // If consecutive bounds are inferable, merge their spans
1761 Some(h) if i == h+1 => {
1762 if let Some(tail) = merged.last_mut() {
1763 // Also eat the trailing `+` if the first
1764 // more-than-one bound is inferable
1765 let to_span = if from_start && i < bounds.len() {
1766 bounds[i+1].span().shrink_to_lo()
1770 *tail = tail.to(to_span);
1771 last_merged_i = Some(i);
1773 bug!("another bound-span visited earlier");
1777 // When we find a non-inferable bound, subsequent inferable bounds
1778 // won't be consecutive from the start (and we'll eat the leading
1779 // `+` rather than the trailing one)
1781 merged.push(bounds[i-1].span().shrink_to_hi().to(bound_span));
1782 last_merged_i = Some(i);
1791 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitOutlivesRequirements {
1792 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
1793 let infer_static = cx.tcx.features().infer_static_outlives_requirements;
1794 let def_id = cx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1795 if let hir::ItemKind::Struct(_, ref generics) = item.node {
1796 let mut bound_count = 0;
1797 let mut lint_spans = Vec::new();
1799 for param in &generics.params {
1800 let param_name = match param.kind {
1801 hir::GenericParamKind::Lifetime { .. } => continue,
1802 hir::GenericParamKind::Type { .. } => {
1804 hir::ParamName::Fresh(_) => continue,
1805 hir::ParamName::Error => continue,
1806 hir::ParamName::Plain(name) => name.to_string(),
1809 hir::GenericParamKind::Const { .. } => continue,
1811 let bound_spans = self.collect_outlives_bound_spans(
1812 cx, def_id, ¶m_name, ¶m.bounds, infer_static
1814 bound_count += bound_spans.len();
1816 self.consolidate_outlives_bound_spans(
1817 param.span.shrink_to_hi(), ¶m.bounds, bound_spans
1822 let mut where_lint_spans = Vec::new();
1823 let mut dropped_predicate_count = 0;
1824 let num_predicates = generics.where_clause.predicates.len();
1825 for (i, where_predicate) in generics.where_clause.predicates.iter().enumerate() {
1826 if let hir::WherePredicate::BoundPredicate(predicate) = where_predicate {
1827 let param_name = match predicate.bounded_ty.node {
1828 hir::TyKind::Path(ref qpath) => {
1829 if let hir::QPath::Resolved(None, ty_param_path) = qpath {
1830 ty_param_path.segments[0].ident.to_string()
1837 let bound_spans = self.collect_outlives_bound_spans(
1838 cx, def_id, ¶m_name, &predicate.bounds, infer_static
1840 bound_count += bound_spans.len();
1842 let drop_predicate = bound_spans.len() == predicate.bounds.len();
1844 dropped_predicate_count += 1;
1847 // If all the bounds on a predicate were inferable and there are
1848 // further predicates, we want to eat the trailing comma
1849 if drop_predicate && i + 1 < num_predicates {
1850 let next_predicate_span = generics.where_clause.predicates[i+1].span();
1851 where_lint_spans.push(
1852 predicate.span.to(next_predicate_span.shrink_to_lo())
1855 where_lint_spans.extend(
1856 self.consolidate_outlives_bound_spans(
1857 predicate.span.shrink_to_lo(),
1866 // If all predicates are inferable, drop the entire clause
1867 // (including the `where`)
1868 if num_predicates > 0 && dropped_predicate_count == num_predicates {
1869 let full_where_span = generics.span.shrink_to_hi()
1870 .to(generics.where_clause.span()
1871 .expect("span of (nonempty) where clause should exist"));
1876 lint_spans.extend(where_lint_spans);
1879 if !lint_spans.is_empty() {
1880 let mut err = cx.struct_span_lint(
1881 EXPLICIT_OUTLIVES_REQUIREMENTS,
1883 "outlives requirements can be inferred"
1885 err.multipart_suggestion(
1886 if bound_count == 1 {
1889 "remove these bounds"
1891 lint_spans.into_iter().map(|span| (span, "".to_owned())).collect::<Vec<_>>(),
1892 Applicability::MachineApplicable