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};
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 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
68 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
69 if let hir::ExprKind::While(ref cond, ..) = e.node {
70 if let hir::ExprKind::Lit(ref lit) = cond.node {
71 if let ast::LitKind::Bool(true) = lit.node {
72 if lit.span.ctxt() == SyntaxContext::empty() {
73 let msg = "denote infinite loops with `loop { ... }`";
74 let condition_span = cx.tcx.sess.source_map().def_span(e.span);
75 let mut err = cx.struct_span_lint(WHILE_TRUE, condition_span, msg);
76 err.span_suggestion_short(
80 Applicability::MachineApplicable
93 "use of owned (Box type) heap memory"
96 declare_lint_pass!(BoxPointers => [BOX_POINTERS]);
99 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext<'_, '_>, span: Span, ty: Ty<'_>) {
100 for leaf_ty in ty.walk() {
101 if leaf_ty.is_box() {
102 let m = format!("type uses owned (Box type) pointers: {}", ty);
103 cx.span_lint(BOX_POINTERS, span, &m);
109 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
110 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
112 hir::ItemKind::Fn(..) |
113 hir::ItemKind::Ty(..) |
114 hir::ItemKind::Enum(..) |
115 hir::ItemKind::Struct(..) |
116 hir::ItemKind::Union(..) => {
117 let def_id = cx.tcx.hir().local_def_id_from_hir_id(it.hir_id);
118 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
123 // If it's a struct, we also have to check the fields' types
125 hir::ItemKind::Struct(ref struct_def, _) |
126 hir::ItemKind::Union(ref struct_def, _) => {
127 for struct_field in struct_def.fields() {
128 let def_id = cx.tcx.hir().local_def_id_from_hir_id(struct_field.hir_id);
129 self.check_heap_type(cx, struct_field.span,
130 cx.tcx.type_of(def_id));
137 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
138 let ty = cx.tables.node_type(e.hir_id);
139 self.check_heap_type(cx, e.span, ty);
144 NON_SHORTHAND_FIELD_PATTERNS,
146 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
149 declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
151 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
152 fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat) {
153 if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node {
154 let variant = cx.tables.pat_ty(pat).ty_adt_def()
155 .expect("struct pattern type is not an ADT")
156 .variant_of_res(cx.tables.qpath_res(qpath, pat.hir_id));
157 for fieldpat in field_pats {
158 if fieldpat.node.is_shorthand {
161 if fieldpat.span.ctxt().outer_expn_info().is_some() {
162 // Don't lint if this is a macro expansion: macro authors
163 // shouldn't have to worry about this kind of style issue
167 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
168 if cx.tcx.find_field_index(ident, &variant) ==
169 Some(cx.tcx.field_index(fieldpat.node.hir_id, cx.tables)) {
170 let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
172 &format!("the `{}:` in this pattern is redundant", ident));
173 let subspan = cx.tcx.sess.source_map().span_through_char(fieldpat.span,
175 err.span_suggestion_short(
179 Applicability::MachineApplicable
192 "usage of `unsafe` code"
195 declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
198 fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) {
199 // This comes from a macro that has `#[allow_internal_unsafe]`.
200 if span.allows_unsafe() {
204 cx.span_lint(UNSAFE_CODE, span, desc);
208 impl EarlyLintPass for UnsafeCode {
209 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
210 if attr.check_name(sym::allow_internal_unsafe) {
211 self.report_unsafe(cx, attr.span, "`allow_internal_unsafe` allows defining \
212 macros using unsafe without triggering \
213 the `unsafe_code` lint at their call site");
217 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
218 if let ast::ExprKind::Block(ref blk, _) = e.node {
219 // Don't warn about generated blocks; that'll just pollute the output.
220 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
221 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
226 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
228 ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => {
229 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
232 ast::ItemKind::Impl(ast::Unsafety::Unsafe, ..) => {
233 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
240 fn check_fn(&mut self,
241 cx: &EarlyContext<'_>,
247 FnKind::ItemFn(_, ast::FnHeader { unsafety: ast::Unsafety::Unsafe, .. }, ..) => {
248 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
251 FnKind::Method(_, sig, ..) => {
252 if sig.header.unsafety == ast::Unsafety::Unsafe {
253 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
261 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, item: &ast::TraitItem) {
262 if let ast::TraitItemKind::Method(ref sig, None) = item.node {
263 if sig.header.unsafety == ast::Unsafety::Unsafe {
264 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
273 "detects missing documentation for public members",
274 report_in_external_macro: true
277 pub struct MissingDoc {
278 /// Stack of whether `#[doc(hidden)]` is set at each level which has lint attributes.
279 doc_hidden_stack: Vec<bool>,
281 /// Private traits or trait items that leaked through. Don't check their methods.
282 private_traits: FxHashSet<hir::HirId>,
285 impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
287 fn has_doc(attr: &ast::Attribute) -> bool {
288 if !attr.check_name(sym::doc) {
292 if attr.is_value_str() {
296 if let Some(list) = attr.meta_item_list() {
298 if meta.check_name(sym::include) || meta.check_name(sym::hidden) {
308 pub fn new() -> MissingDoc {
310 doc_hidden_stack: vec![false],
311 private_traits: FxHashSet::default(),
315 fn doc_hidden(&self) -> bool {
316 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
319 fn check_missing_docs_attrs(&self,
320 cx: &LateContext<'_, '_>,
321 id: Option<hir::HirId>,
322 attrs: &[ast::Attribute],
324 desc: &'static str) {
325 // If we're building a test harness, then warning about
326 // documentation is probably not really relevant right now.
327 if cx.sess().opts.test {
331 // `#[doc(hidden)]` disables missing_docs check.
332 if self.doc_hidden() {
336 // Only check publicly-visible items, using the result from the privacy pass.
337 // It's an option so the crate root can also use this function (it doesn't
339 if let Some(id) = id {
340 if !cx.access_levels.is_exported(id) {
345 let has_doc = attrs.iter().any(|a| has_doc(a));
347 cx.span_lint(MISSING_DOCS,
348 cx.tcx.sess.source_map().def_span(sp),
349 &format!("missing documentation for {}", desc));
354 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
355 fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) {
356 let doc_hidden = self.doc_hidden() ||
357 attrs.iter().any(|attr| {
358 attr.check_name(sym::doc) &&
359 match attr.meta_item_list() {
361 Some(l) => attr::list_contains_name(&l, sym::hidden),
364 self.doc_hidden_stack.push(doc_hidden);
367 fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) {
368 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
371 fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate) {
372 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
374 for macro_def in &krate.exported_macros {
375 let has_doc = macro_def.attrs.iter().any(|a| has_doc(a));
377 cx.span_lint(MISSING_DOCS,
378 cx.tcx.sess.source_map().def_span(macro_def.span),
379 "missing documentation for macro");
384 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
385 let desc = match it.node {
386 hir::ItemKind::Fn(..) => "a function",
387 hir::ItemKind::Mod(..) => "a module",
388 hir::ItemKind::Enum(..) => "an enum",
389 hir::ItemKind::Struct(..) => "a struct",
390 hir::ItemKind::Union(..) => "a union",
391 hir::ItemKind::Trait(.., ref trait_item_refs) => {
392 // Issue #11592: traits are always considered exported, even when private.
393 if let hir::VisibilityKind::Inherited = it.vis.node {
394 self.private_traits.insert(it.hir_id);
395 for trait_item_ref in trait_item_refs {
396 self.private_traits.insert(trait_item_ref.id.hir_id);
402 hir::ItemKind::Ty(..) => "a type alias",
403 hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
404 // If the trait is private, add the impl items to `private_traits` so they don't get
405 // reported for missing docs.
406 let real_trait = trait_ref.path.res.def_id();
407 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(real_trait) {
408 match cx.tcx.hir().find_by_hir_id(hir_id) {
409 Some(Node::Item(item)) => {
410 if let hir::VisibilityKind::Inherited = item.vis.node {
411 for impl_item_ref in impl_item_refs {
412 self.private_traits.insert(impl_item_ref.id.hir_id);
421 hir::ItemKind::Const(..) => "a constant",
422 hir::ItemKind::Static(..) => "a static",
426 self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, desc);
429 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem) {
430 if self.private_traits.contains(&trait_item.hir_id) {
434 let desc = match trait_item.node {
435 hir::TraitItemKind::Const(..) => "an associated constant",
436 hir::TraitItemKind::Method(..) => "a trait method",
437 hir::TraitItemKind::Type(..) => "an associated type",
440 self.check_missing_docs_attrs(cx,
441 Some(trait_item.hir_id),
447 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
448 // If the method is an impl for a trait, don't doc.
449 if method_context(cx, impl_item.hir_id) == MethodLateContext::TraitImpl {
453 let desc = match impl_item.node {
454 hir::ImplItemKind::Const(..) => "an associated constant",
455 hir::ImplItemKind::Method(..) => "a method",
456 hir::ImplItemKind::Type(_) => "an associated type",
457 hir::ImplItemKind::Existential(_) => "an associated existential type",
459 self.check_missing_docs_attrs(cx,
460 Some(impl_item.hir_id),
466 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField) {
467 if !sf.is_positional() {
468 self.check_missing_docs_attrs(cx,
476 fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant, _: &hir::Generics) {
477 self.check_missing_docs_attrs(cx,
486 pub MISSING_COPY_IMPLEMENTATIONS,
488 "detects potentially-forgotten implementations of `Copy`"
491 declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
493 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
494 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
495 if !cx.access_levels.is_reachable(item.hir_id) {
498 let (def, ty) = match item.node {
499 hir::ItemKind::Struct(_, ref ast_generics) => {
500 if !ast_generics.params.is_empty() {
503 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id_from_hir_id(item.hir_id));
504 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
506 hir::ItemKind::Union(_, ref ast_generics) => {
507 if !ast_generics.params.is_empty() {
510 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id_from_hir_id(item.hir_id));
511 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
513 hir::ItemKind::Enum(_, ref ast_generics) => {
514 if !ast_generics.params.is_empty() {
517 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id_from_hir_id(item.hir_id));
518 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
522 if def.has_dtor(cx.tcx) {
525 let param_env = ty::ParamEnv::empty();
526 if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span) {
529 if param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
530 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
532 "type could implement `Copy`; consider adding `impl \
539 MISSING_DEBUG_IMPLEMENTATIONS,
541 "detects missing implementations of fmt::Debug"
545 pub struct MissingDebugImplementations {
546 impling_types: Option<HirIdSet>,
549 impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
551 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
552 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
553 if !cx.access_levels.is_reachable(item.hir_id) {
558 hir::ItemKind::Struct(..) |
559 hir::ItemKind::Union(..) |
560 hir::ItemKind::Enum(..) => {}
564 let debug = match cx.tcx.lang_items().debug_trait() {
565 Some(debug) => debug,
569 if self.impling_types.is_none() {
570 let mut impls = HirIdSet::default();
571 cx.tcx.for_each_impl(debug, |d| {
572 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
573 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
574 impls.insert(hir_id);
579 self.impling_types = Some(impls);
580 debug!("{:?}", self.impling_types);
583 if !self.impling_types.as_ref().unwrap().contains(&item.hir_id) {
584 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
586 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
587 or a manual implementation")
593 pub ANONYMOUS_PARAMETERS,
595 "detects anonymous parameters"
599 /// Checks for use of anonymous parameters (RFC 1685).
600 AnonymousParameters => [ANONYMOUS_PARAMETERS]
603 impl EarlyLintPass for AnonymousParameters {
604 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::TraitItem) {
606 ast::TraitItemKind::Method(ref sig, _) => {
607 for arg in sig.decl.inputs.iter() {
609 ast::PatKind::Ident(_, ident, None) => {
610 if ident.name == kw::Invalid {
614 .span_to_snippet(arg.ty.span);
616 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
617 (snip, Applicability::MachineApplicable)
619 ("<type>".to_owned(), Applicability::HasPlaceholders)
623 ANONYMOUS_PARAMETERS,
625 "anonymous parameters are deprecated and will be \
626 removed in the next edition."
629 "Try naming the parameter or explicitly \
631 format!("_: {}", ty_snip),
645 /// Check for use of attributes which have been deprecated.
647 pub struct DeprecatedAttr {
648 // This is not free to compute, so we want to keep it around, rather than
649 // compute it for every attribute.
650 depr_attrs: Vec<&'static (Symbol, AttributeType, AttributeTemplate, AttributeGate)>,
653 impl_lint_pass!(DeprecatedAttr => []);
655 impl DeprecatedAttr {
656 pub fn new() -> DeprecatedAttr {
658 depr_attrs: deprecated_attributes(),
663 impl EarlyLintPass for DeprecatedAttr {
664 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
665 for &&(n, _, _, ref g) in &self.depr_attrs {
666 if attr.ident().map(|ident| ident.name) == Some(n) {
667 if let &AttributeGate::Gated(Stability::Deprecated(link, suggestion),
671 let msg = format!("use of deprecated attribute `{}`: {}. See {}",
673 let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
674 err.span_suggestion_short(
676 suggestion.unwrap_or("remove this attribute"),
678 Applicability::MachineApplicable
689 pub UNUSED_DOC_COMMENTS,
691 "detects doc comments that aren't used by rustdoc"
694 declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]);
696 impl UnusedDocComment {
699 cx: &EarlyContext<'_>,
702 is_macro_expansion: bool,
703 attrs: &[ast::Attribute]
705 let mut attrs = attrs.into_iter().peekable();
707 // Accumulate a single span for sugared doc comments.
708 let mut sugared_span: Option<Span> = None;
710 while let Some(attr) = attrs.next() {
711 if attr.is_sugared_doc {
713 sugared_span.map_or_else(
715 |span| span.with_hi(attr.span.hi()),
720 if attrs.peek().map(|next_attr| next_attr.is_sugared_doc).unwrap_or_default() {
724 let span = sugared_span.take().unwrap_or_else(|| attr.span);
726 if attr.check_name(sym::doc) {
727 let mut err = cx.struct_span_lint(UNUSED_DOC_COMMENTS, span, "unused doc comment");
731 format!("rustdoc does not generate documentation for {}", node_kind)
734 if is_macro_expansion {
735 err.help("to document an item produced by a macro, \
736 the macro must produce the documentation as part of its expansion");
745 impl EarlyLintPass for UnusedDocComment {
746 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
747 if let ast::ItemKind::Mac(..) = item.node {
748 self.warn_if_doc(cx, item.span, "macro expansions", true, &item.attrs);
752 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
753 let (kind, is_macro_expansion) = match stmt.node {
754 ast::StmtKind::Local(..) => ("statements", false),
755 ast::StmtKind::Item(..) => ("inner items", false),
756 ast::StmtKind::Mac(..) => ("macro expansions", true),
757 // expressions will be reported by `check_expr`.
758 ast::StmtKind::Semi(..) |
759 ast::StmtKind::Expr(..) => return,
762 self.warn_if_doc(cx, stmt.span, kind, is_macro_expansion, stmt.node.attrs());
765 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
766 let arm_span = arm.pats[0].span.with_hi(arm.body.span.hi());
767 self.warn_if_doc(cx, arm_span, "match arms", false, &arm.attrs);
770 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
771 self.warn_if_doc(cx, expr.span, "expressions", false, &expr.attrs);
778 "compiler plugin used as ordinary library in non-plugin crate"
781 declare_lint_pass!(PluginAsLibrary => [PLUGIN_AS_LIBRARY]);
783 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
784 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
785 if cx.tcx.plugin_registrar_fn(LOCAL_CRATE).is_some() {
786 // We're compiling a plugin; it's fine to link other plugins.
791 hir::ItemKind::ExternCrate(..) => (),
795 let def_id = cx.tcx.hir().local_def_id_from_hir_id(it.hir_id);
796 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
797 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
799 // Probably means we aren't linking the crate for some reason.
801 // Not sure if / when this could happen.
807 cx.span_lint(PLUGIN_AS_LIBRARY,
809 "compiler plugin used as an ordinary library");
815 NO_MANGLE_CONST_ITEMS,
817 "const items will not have their symbols exported"
821 NO_MANGLE_GENERIC_ITEMS,
823 "generic items must be mangled"
826 declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
828 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
829 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
831 hir::ItemKind::Fn(.., ref generics, _) => {
832 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
833 for param in &generics.params {
835 GenericParamKind::Lifetime { .. } => {}
836 GenericParamKind::Type { .. } |
837 GenericParamKind::Const { .. } => {
838 let mut err = cx.struct_span_lint(
839 NO_MANGLE_GENERIC_ITEMS,
841 "functions generic over types or consts must be mangled",
843 err.span_suggestion_short(
845 "remove this attribute",
847 // Use of `#[no_mangle]` suggests FFI intent; correct
848 // fix may be to monomorphize source by hand
849 Applicability::MaybeIncorrect
858 hir::ItemKind::Const(..) => {
859 if attr::contains_name(&it.attrs, sym::no_mangle) {
860 // Const items do not refer to a particular location in memory, and therefore
861 // don't have anything to attach a symbol to
862 let msg = "const items should never be #[no_mangle]";
863 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
865 // account for "pub const" (#45562)
866 let start = cx.tcx.sess.source_map().span_to_snippet(it.span)
867 .map(|snippet| snippet.find("const").unwrap_or(0))
868 .unwrap_or(0) as u32;
869 // `const` is 5 chars
870 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
873 "try a static value",
874 "pub static".to_owned(),
875 Applicability::MachineApplicable
888 "mutating transmuted &mut T from &T may cause undefined behavior"
891 declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
893 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
894 fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr) {
895 use rustc_target::spec::abi::Abi::RustIntrinsic;
897 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
898 consider instead using an UnsafeCell";
899 match get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (&ty1.sty, &ty2.sty)) {
900 Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
901 if to_mt == hir::Mutability::MutMutable &&
902 from_mt == hir::Mutability::MutImmutable {
903 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
909 fn get_transmute_from_to<'a, 'tcx>
910 (cx: &LateContext<'a, 'tcx>,
912 -> Option<(Ty<'tcx>, Ty<'tcx>)> {
913 let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
914 cx.tables.qpath_res(qpath, expr.hir_id)
918 if let Res::Def(DefKind::Fn, did) = def {
919 if !def_id_is_transmute(cx, did) {
922 let sig = cx.tables.node_type(expr.hir_id).fn_sig(cx.tcx);
923 let from = sig.inputs().skip_binder()[0];
924 let to = *sig.output().skip_binder();
925 return Some((from, to));
930 fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
931 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
932 cx.tcx.item_name(def_id) == sym::transmute
940 "enabling unstable features (deprecated. do not use)"
944 /// Forbids using the `#[feature(...)]` attribute
945 UnstableFeatures => [UNSTABLE_FEATURES]
948 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
949 fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) {
950 if attr.check_name(sym::feature) {
951 if let Some(items) = attr.meta_item_list() {
953 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
961 UNIONS_WITH_DROP_FIELDS,
963 "use of unions that contain fields with possibly non-trivial drop code"
967 /// Lint for unions that contain fields with possibly non-trivial destructors.
968 UnionsWithDropFields => [UNIONS_WITH_DROP_FIELDS]
971 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
972 fn check_item(&mut self, ctx: &LateContext<'_, '_>, item: &hir::Item) {
973 if let hir::ItemKind::Union(ref vdata, _) = item.node {
974 for field in vdata.fields() {
975 let field_ty = ctx.tcx.type_of(
976 ctx.tcx.hir().local_def_id_from_hir_id(field.hir_id));
977 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
978 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
980 "union contains a field with possibly non-trivial drop code, \
981 drop code of union fields is ignored when dropping the union");
992 "`pub` items not reachable from crate root"
996 /// Lint for items marked `pub` that aren't reachable from other crates.
997 UnreachablePub => [UNREACHABLE_PUB]
1000 impl UnreachablePub {
1001 fn perform_lint(&self, cx: &LateContext<'_, '_>, what: &str, id: hir::HirId,
1002 vis: &hir::Visibility, span: Span, exportable: bool) {
1003 let mut applicability = Applicability::MachineApplicable;
1005 hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
1006 if span.ctxt().outer_expn_info().is_some() {
1007 applicability = Applicability::MaybeIncorrect;
1009 let def_span = cx.tcx.sess.source_map().def_span(span);
1010 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1011 &format!("unreachable `pub` {}", what));
1012 let replacement = if cx.tcx.features().crate_visibility_modifier {
1018 err.span_suggestion(
1020 "consider restricting its visibility",
1025 err.help("or consider exporting it for use by other crates");
1034 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1035 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1036 self.perform_lint(cx, "item", item.hir_id, &item.vis, item.span, true);
1039 fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, foreign_item: &hir::ForeignItem) {
1040 self.perform_lint(cx, "item", foreign_item.hir_id, &foreign_item.vis,
1041 foreign_item.span, true);
1044 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) {
1045 self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false);
1048 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
1049 self.perform_lint(cx, "item", impl_item.hir_id, &impl_item.vis, impl_item.span, false);
1056 "bounds in type aliases are not enforced"
1060 /// Lint for trait and lifetime bounds in type aliases being mostly ignored.
1061 /// They are relevant when using associated types, but otherwise neither checked
1062 /// at definition site nor enforced at use site.
1063 TypeAliasBounds => [TYPE_ALIAS_BOUNDS]
1066 impl TypeAliasBounds {
1067 fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1069 hir::QPath::TypeRelative(ref ty, _) => {
1070 // If this is a type variable, we found a `T::Assoc`.
1072 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1074 Res::Def(DefKind::TyParam, _) => true,
1081 hir::QPath::Resolved(..) => false,
1085 fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder<'_>) {
1086 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1087 // bound. Let's see if this type does that.
1089 // We use a HIR visitor to walk the type.
1090 use rustc::hir::intravisit::{self, Visitor};
1091 struct WalkAssocTypes<'a, 'db> where 'db: 'a {
1092 err: &'a mut DiagnosticBuilder<'db>
1094 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1095 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1097 intravisit::NestedVisitorMap::None
1100 fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: hir::HirId, span: Span) {
1101 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1102 self.err.span_help(span,
1103 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1104 associated types in type aliases");
1106 intravisit::walk_qpath(self, qpath, id, span)
1110 // Let's go for a walk!
1111 let mut visitor = WalkAssocTypes { err };
1112 visitor.visit_ty(ty);
1116 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1117 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1118 let (ty, type_alias_generics) = match item.node {
1119 hir::ItemKind::Ty(ref ty, ref generics) => (&*ty, generics),
1122 let mut suggested_changing_assoc_types = false;
1123 // There must not be a where clause
1124 if !type_alias_generics.where_clause.predicates.is_empty() {
1125 let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1126 .map(|pred| pred.span()).collect();
1127 let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1128 "where clauses are not enforced in type aliases");
1129 err.help("the clause will not be checked when the type alias is used, \
1130 and should be removed");
1131 if !suggested_changing_assoc_types {
1132 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1133 suggested_changing_assoc_types = true;
1137 // The parameters must not have bounds
1138 for param in type_alias_generics.params.iter() {
1139 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1140 if !spans.is_empty() {
1141 let mut err = cx.struct_span_lint(
1144 "bounds on generic parameters are not enforced in type aliases",
1146 err.help("the bound will not be checked when the type alias is used, \
1147 and should be removed");
1148 if !suggested_changing_assoc_types {
1149 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1150 suggested_changing_assoc_types = true;
1159 /// Lint constants that are erroneous.
1160 /// Without this lint, we might not get any diagnostic if the constant is
1161 /// unused within this crate, even though downstream crates can't use it
1162 /// without producing an error.
1163 UnusedBrokenConst => []
1166 fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) {
1167 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
1168 let param_env = if cx.tcx.is_static(def_id) {
1169 // Use the same param_env as `codegen_static_initializer`, to reuse the cache.
1170 ty::ParamEnv::reveal_all()
1172 cx.tcx.param_env(def_id)
1174 let cid = ::rustc::mir::interpret::GlobalId {
1175 instance: ty::Instance::mono(cx.tcx, def_id),
1178 // trigger the query once for all constants since that will already report the errors
1179 // FIXME: Use ensure here
1180 let _ = cx.tcx.const_eval(param_env.and(cid));
1183 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1184 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1186 hir::ItemKind::Const(_, body_id) => {
1187 check_const(cx, body_id);
1189 hir::ItemKind::Static(_, _, body_id) => {
1190 check_const(cx, body_id);
1200 "these bounds don't depend on an type parameters"
1204 /// Lint for trait and lifetime bounds that don't depend on type parameters
1205 /// which either do nothing, or stop the item from being used.
1206 TrivialConstraints => [TRIVIAL_BOUNDS]
1209 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1212 cx: &LateContext<'a, 'tcx>,
1213 item: &'tcx hir::Item,
1215 use rustc::ty::fold::TypeFoldable;
1216 use rustc::ty::Predicate::*;
1218 if cx.tcx.features().trivial_bounds {
1219 let def_id = cx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1220 let predicates = cx.tcx.predicates_of(def_id);
1221 for &(predicate, span) in &predicates.predicates {
1222 let predicate_kind_name = match predicate {
1223 Trait(..) => "Trait",
1225 RegionOutlives(..) => "Lifetime",
1227 // Ignore projections, as they can only be global
1228 // if the trait bound is global
1230 // Ignore bounds that a user can't type
1235 ConstEvaluatable(..) => continue,
1237 if predicate.is_global() {
1241 &format!("{} bound {} does not depend on any type \
1242 or lifetime parameters", predicate_kind_name, predicate),
1251 /// Does nothing as a lint pass, but registers some `Lint`s
1252 /// which are used by other parts of the compiler.
1256 NON_SHORTHAND_FIELD_PATTERNS,
1259 MISSING_COPY_IMPLEMENTATIONS,
1260 MISSING_DEBUG_IMPLEMENTATIONS,
1261 ANONYMOUS_PARAMETERS,
1262 UNUSED_DOC_COMMENTS,
1264 NO_MANGLE_CONST_ITEMS,
1265 NO_MANGLE_GENERIC_ITEMS,
1268 UNIONS_WITH_DROP_FIELDS,
1276 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1278 "`...` range patterns are deprecated"
1282 pub struct EllipsisInclusiveRangePatterns {
1283 /// If `Some(_)`, suppress all subsequent pattern
1284 /// warnings for better diagnostics.
1285 node_id: Option<ast::NodeId>,
1288 impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1290 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1291 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1292 if self.node_id.is_some() {
1293 // Don't recursively warn about patterns inside range endpoints.
1297 use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot};
1299 /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1300 /// corresponding to the ellipsis.
1301 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(&P<Expr>, &P<Expr>, Span)> {
1303 PatKind::Range(a, b, Spanned { span, node: RangeEnd::Included(DotDotDot), .. }) => {
1310 let (parenthesise, endpoints) = match &pat.node {
1311 PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)),
1312 _ => (false, matches_ellipsis_pat(pat)),
1315 if let Some((start, end, join)) = endpoints {
1316 let msg = "`...` range patterns are deprecated";
1317 let suggestion = "use `..=` for an inclusive range";
1319 self.node_id = Some(pat.id);
1320 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, pat.span, msg);
1321 err.span_suggestion(
1324 format!("&({}..={})", expr_to_string(&start), expr_to_string(&end)),
1325 Applicability::MachineApplicable,
1329 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, join, msg);
1330 err.span_suggestion_short(
1334 Applicability::MachineApplicable,
1341 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1342 if let Some(node_id) = self.node_id {
1343 if pat.id == node_id {
1351 UNNAMEABLE_TEST_ITEMS,
1353 "detects an item that cannot be named being marked as #[test_case]",
1354 report_in_external_macro: true
1357 pub struct UnnameableTestItems {
1358 boundary: hir::HirId, // HirId of the item under which things are not nameable
1359 items_nameable: bool,
1362 impl_lint_pass!(UnnameableTestItems => [UNNAMEABLE_TEST_ITEMS]);
1364 impl UnnameableTestItems {
1365 pub fn new() -> Self {
1367 boundary: hir::DUMMY_HIR_ID,
1368 items_nameable: true
1373 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
1374 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1375 if self.items_nameable {
1376 if let hir::ItemKind::Mod(..) = it.node {}
1378 self.items_nameable = false;
1379 self.boundary = it.hir_id;
1384 if let Some(attr) = attr::find_by_name(&it.attrs, sym::rustc_test_marker) {
1385 cx.struct_span_lint(
1386 UNNAMEABLE_TEST_ITEMS,
1388 "cannot test inner items",
1393 fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item) {
1394 if !self.items_nameable && self.boundary == it.hir_id {
1395 self.items_nameable = true;
1403 "detects edition keywords being used as an identifier"
1407 /// Check for uses of edition keywords used as an identifier.
1408 KeywordIdents => [KEYWORD_IDENTS]
1411 struct UnderMacro(bool);
1413 impl KeywordIdents {
1414 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) {
1415 for tt in tokens.into_trees() {
1417 TokenTree::Token(span, tok) => match tok.ident() {
1418 // only report non-raw idents
1419 Some((ident, false)) => {
1420 self.check_ident_token(cx, UnderMacro(true), ast::Ident {
1421 span: span.substitute_dummy(ident.span),
1427 TokenTree::Delimited(_, _, tts) => {
1428 self.check_tokens(cx, tts)
1434 fn check_ident_token(&mut self,
1435 cx: &EarlyContext<'_>,
1436 UnderMacro(under_macro): UnderMacro,
1439 let next_edition = match cx.sess.edition() {
1440 Edition::Edition2015 => {
1442 kw::Async | kw::Await | kw::Try => Edition::Edition2018,
1444 // rust-lang/rust#56327: Conservatively do not
1445 // attempt to report occurrences of `dyn` within
1446 // macro definitions or invocations, because `dyn`
1447 // can legitimately occur as a contextual keyword
1448 // in 2015 code denoting its 2018 meaning, and we
1449 // do not want rustfix to inject bugs into working
1450 // code by rewriting such occurrences.
1452 // But if we see `dyn` outside of a macro, we know
1453 // its precise role in the parsed AST and thus are
1454 // assured this is truly an attempt to use it as
1456 kw::Dyn if !under_macro => Edition::Edition2018,
1462 // There are no new keywords yet for the 2018 edition and beyond.
1466 // Don't lint `r#foo`.
1467 if cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span) {
1471 let mut lint = cx.struct_span_lint(
1474 &format!("`{}` is a keyword in the {} edition",
1478 lint.span_suggestion(
1480 "you can use a raw identifier to stay compatible",
1481 format!("r#{}", ident.as_str()),
1482 Applicability::MachineApplicable,
1488 impl EarlyLintPass for KeywordIdents {
1489 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) {
1490 self.check_tokens(cx, mac_def.stream());
1492 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
1493 self.check_tokens(cx, mac.node.tts.clone().into());
1495 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: ast::Ident) {
1496 self.check_ident_token(cx, UnderMacro(false), ident);
1500 declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1502 impl ExplicitOutlivesRequirements {
1503 fn collect_outlives_bound_spans(
1505 cx: &LateContext<'_, '_>,
1508 bounds: &hir::GenericBounds,
1510 ) -> Vec<(usize, Span)> {
1511 // For lack of a more elegant strategy for comparing the `ty::Predicate`s
1512 // returned by this query with the params/bounds grabbed from the HIR—and
1513 // with some regrets—we're going to covert the param/lifetime names to
1515 let inferred_outlives = cx.tcx.inferred_outlives_of(item_def_id);
1517 let ty_lt_names = inferred_outlives.iter().filter_map(|pred| {
1518 let binder = match pred {
1519 ty::Predicate::TypeOutlives(binder) => binder,
1520 _ => { return None; }
1522 let ty_outlives_pred = binder.skip_binder();
1523 let ty_name = match ty_outlives_pred.0.sty {
1524 ty::Param(param) => param.name.to_string(),
1525 _ => { return None; }
1527 let lt_name = match ty_outlives_pred.1 {
1528 ty::RegionKind::ReEarlyBound(region) => {
1529 region.name.to_string()
1531 _ => { return None; }
1533 Some((ty_name, lt_name))
1534 }).collect::<Vec<_>>();
1536 let mut bound_spans = Vec::new();
1537 for (i, bound) in bounds.iter().enumerate() {
1538 if let hir::GenericBound::Outlives(lifetime) = bound {
1539 let is_static = match lifetime.name {
1540 hir::LifetimeName::Static => true,
1543 if is_static && !infer_static {
1544 // infer-outlives for 'static is still feature-gated (tracking issue #44493)
1548 let lt_name = &lifetime.name.ident().to_string();
1549 if ty_lt_names.contains(&(param_name.to_owned(), lt_name.to_owned())) {
1550 bound_spans.push((i, bound.span()));
1557 fn consolidate_outlives_bound_spans(
1560 bounds: &hir::GenericBounds,
1561 bound_spans: Vec<(usize, Span)>
1563 if bounds.is_empty() {
1566 if bound_spans.len() == bounds.len() {
1567 let (_, last_bound_span) = bound_spans[bound_spans.len()-1];
1568 // If all bounds are inferable, we want to delete the colon, so
1569 // start from just after the parameter (span passed as argument)
1570 vec![lo.to(last_bound_span)]
1572 let mut merged = Vec::new();
1573 let mut last_merged_i = None;
1575 let mut from_start = true;
1576 for (i, bound_span) in bound_spans {
1577 match last_merged_i {
1578 // If the first bound is inferable, our span should also eat the trailing `+`
1580 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
1581 last_merged_i = Some(0);
1583 // If consecutive bounds are inferable, merge their spans
1584 Some(h) if i == h+1 => {
1585 if let Some(tail) = merged.last_mut() {
1586 // Also eat the trailing `+` if the first
1587 // more-than-one bound is inferable
1588 let to_span = if from_start && i < bounds.len() {
1589 bounds[i+1].span().shrink_to_lo()
1593 *tail = tail.to(to_span);
1594 last_merged_i = Some(i);
1596 bug!("another bound-span visited earlier");
1600 // When we find a non-inferable bound, subsequent inferable bounds
1601 // won't be consecutive from the start (and we'll eat the leading
1602 // `+` rather than the trailing one)
1604 merged.push(bounds[i-1].span().shrink_to_hi().to(bound_span));
1605 last_merged_i = Some(i);
1614 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitOutlivesRequirements {
1615 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
1616 let infer_static = cx.tcx.features().infer_static_outlives_requirements;
1617 let def_id = cx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1618 if let hir::ItemKind::Struct(_, ref generics) = item.node {
1619 let mut bound_count = 0;
1620 let mut lint_spans = Vec::new();
1622 for param in &generics.params {
1623 let param_name = match param.kind {
1624 hir::GenericParamKind::Lifetime { .. } => continue,
1625 hir::GenericParamKind::Type { .. } => {
1627 hir::ParamName::Fresh(_) => continue,
1628 hir::ParamName::Error => continue,
1629 hir::ParamName::Plain(name) => name.to_string(),
1632 hir::GenericParamKind::Const { .. } => continue,
1634 let bound_spans = self.collect_outlives_bound_spans(
1635 cx, def_id, ¶m_name, ¶m.bounds, infer_static
1637 bound_count += bound_spans.len();
1639 self.consolidate_outlives_bound_spans(
1640 param.span.shrink_to_hi(), ¶m.bounds, bound_spans
1645 let mut where_lint_spans = Vec::new();
1646 let mut dropped_predicate_count = 0;
1647 let num_predicates = generics.where_clause.predicates.len();
1648 for (i, where_predicate) in generics.where_clause.predicates.iter().enumerate() {
1649 if let hir::WherePredicate::BoundPredicate(predicate) = where_predicate {
1650 let param_name = match predicate.bounded_ty.node {
1651 hir::TyKind::Path(ref qpath) => {
1652 if let hir::QPath::Resolved(None, ty_param_path) = qpath {
1653 ty_param_path.segments[0].ident.to_string()
1660 let bound_spans = self.collect_outlives_bound_spans(
1661 cx, def_id, ¶m_name, &predicate.bounds, infer_static
1663 bound_count += bound_spans.len();
1665 let drop_predicate = bound_spans.len() == predicate.bounds.len();
1667 dropped_predicate_count += 1;
1670 // If all the bounds on a predicate were inferable and there are
1671 // further predicates, we want to eat the trailing comma
1672 if drop_predicate && i + 1 < num_predicates {
1673 let next_predicate_span = generics.where_clause.predicates[i+1].span();
1674 where_lint_spans.push(
1675 predicate.span.to(next_predicate_span.shrink_to_lo())
1678 where_lint_spans.extend(
1679 self.consolidate_outlives_bound_spans(
1680 predicate.span.shrink_to_lo(),
1689 // If all predicates are inferable, drop the entire clause
1690 // (including the `where`)
1691 if num_predicates > 0 && dropped_predicate_count == num_predicates {
1692 let full_where_span = generics.span.shrink_to_hi()
1693 .to(generics.where_clause.span()
1694 .expect("span of (nonempty) where clause should exist"));
1699 lint_spans.extend(where_lint_spans);
1702 if !lint_spans.is_empty() {
1703 let mut err = cx.struct_span_lint(
1704 EXPLICIT_OUTLIVES_REQUIREMENTS,
1706 "outlives requirements can be inferred"
1708 err.multipart_suggestion(
1709 if bound_count == 1 {
1712 "remove these bounds"
1714 lint_spans.into_iter().map(|span| (span, "".to_owned())).collect::<Vec<_>>(),
1715 Applicability::MachineApplicable