1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Lints in the Rust compiler.
13 //! This contains lints which can feasibly be implemented as their own
14 //! AST visitor. Also see `rustc::lint::builtin`, which contains the
15 //! definitions of lints that are emitted directly inside the main
18 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
19 //! Then add code to emit the new lint in the appropriate circumstances.
20 //! You can do that in an existing `LintPass` if it makes sense, or in a
21 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
22 //! compiler. Only do the latter if the check can't be written cleanly as a
23 //! `LintPass` (also, note that such lints will need to be defined in
24 //! `rustc::lint::builtin`, not here).
26 //! If you define a new `LintPass`, you will also need to add it to the
27 //! `add_builtin!` or `add_builtin_with_new!` invocation in `lib.rs`.
28 //! Use the former for unit-like structs and the latter for structs with
31 use rustc::hir::def::Def;
32 use rustc::hir::def_id::DefId;
34 use rustc::ty::subst::Substs;
35 use rustc::ty::{self, Ty};
37 use rustc::hir::map as hir_map;
38 use util::nodemap::NodeSet;
39 use lint::{LateContext, LintContext, LintArray};
40 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
42 use std::collections::HashSet;
46 use syntax::codemap::Spanned;
47 use syntax::edition::Edition;
48 use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
49 use syntax_pos::{BytePos, Span, SyntaxContext};
50 use syntax::symbol::keywords;
51 use syntax::errors::{Applicability, DiagnosticBuilder};
53 use rustc::hir::{self, GenericParamKind, PatKind};
54 use rustc::hir::intravisit::FnKind;
56 use bad_style::{MethodLateContext, method_context};
58 // hardwired lints from librustc
59 pub use lint::builtin::*;
64 "suggest using `loop { }` instead of `while true { }`"
67 #[derive(Copy, Clone)]
70 impl LintPass for WhileTrue {
71 fn get_lints(&self) -> LintArray {
72 lint_array!(WHILE_TRUE)
76 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
77 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
78 if let hir::ExprWhile(ref cond, ..) = e.node {
79 if let hir::ExprLit(ref lit) = cond.node {
80 if let ast::LitKind::Bool(true) = lit.node {
81 if lit.span.ctxt() == SyntaxContext::empty() {
82 let msg = "denote infinite loops with `loop { ... }`";
83 let condition_span = cx.tcx.sess.codemap().def_span(e.span);
84 let mut err = cx.struct_span_lint(WHILE_TRUE, condition_span, msg);
85 err.span_suggestion_short(condition_span, "use `loop`", "loop".to_owned());
97 "use of owned (Box type) heap memory"
100 #[derive(Copy, Clone)]
101 pub struct BoxPointers;
104 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
105 for leaf_ty in ty.walk() {
106 if leaf_ty.is_box() {
107 let m = format!("type uses owned (Box type) pointers: {}", ty);
108 cx.span_lint(BOX_POINTERS, span, &m);
114 impl LintPass for BoxPointers {
115 fn get_lints(&self) -> LintArray {
116 lint_array!(BOX_POINTERS)
120 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
121 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
126 hir::ItemStruct(..) |
127 hir::ItemUnion(..) => {
128 let def_id = cx.tcx.hir.local_def_id(it.id);
129 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
134 // If it's a struct, we also have to check the fields' types
136 hir::ItemStruct(ref struct_def, _) |
137 hir::ItemUnion(ref struct_def, _) => {
138 for struct_field in struct_def.fields() {
139 let def_id = cx.tcx.hir.local_def_id(struct_field.id);
140 self.check_heap_type(cx, struct_field.span,
141 cx.tcx.type_of(def_id));
148 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
149 let ty = cx.tables.node_id_to_type(e.hir_id);
150 self.check_heap_type(cx, e.span, ty);
155 NON_SHORTHAND_FIELD_PATTERNS,
157 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
160 #[derive(Copy, Clone)]
161 pub struct NonShorthandFieldPatterns;
163 impl LintPass for NonShorthandFieldPatterns {
164 fn get_lints(&self) -> LintArray {
165 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
169 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
170 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
171 if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node {
172 let variant = cx.tables.pat_ty(pat).ty_adt_def()
173 .expect("struct pattern type is not an ADT")
174 .variant_of_def(cx.tables.qpath_def(qpath, pat.hir_id));
175 for fieldpat in field_pats {
176 if fieldpat.node.is_shorthand {
179 if fieldpat.span.ctxt().outer().expn_info().is_some() {
180 // Don't lint if this is a macro expansion: macro authors
181 // shouldn't have to worry about this kind of style issue
185 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
186 if cx.tcx.find_field_index(ident, &variant) ==
187 Some(cx.tcx.field_index(fieldpat.node.id, cx.tables)) {
188 let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
190 &format!("the `{}:` in this pattern is redundant", ident));
191 let subspan = cx.tcx.sess.codemap().span_through_char(fieldpat.span, ':');
192 err.span_suggestion_short(subspan, "remove this", format!("{}", ident));
204 "usage of `unsafe` code"
207 #[derive(Copy, Clone)]
208 pub struct UnsafeCode;
210 impl LintPass for UnsafeCode {
211 fn get_lints(&self) -> LintArray {
212 lint_array!(UNSAFE_CODE)
217 fn report_unsafe(&self, cx: &LateContext, span: Span, desc: &'static str) {
218 // This comes from a macro that has #[allow_internal_unsafe].
219 if span.allows_unsafe() {
223 cx.span_lint(UNSAFE_CODE, span, desc);
227 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
228 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
229 if let hir::ExprBlock(ref blk, _) = e.node {
230 // Don't warn about generated blocks, that'll just pollute the output.
231 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
232 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
237 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
239 hir::ItemTrait(_, hir::Unsafety::Unsafe, ..) => {
240 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
243 hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
244 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
251 fn check_fn(&mut self,
259 FnKind::ItemFn(_, _, hir::FnHeader { unsafety: hir::Unsafety::Unsafe, .. }, ..) => {
260 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
263 FnKind::Method(_, sig, ..) => {
264 if sig.header.unsafety == hir::Unsafety::Unsafe {
265 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
273 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
274 if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
275 if sig.header.unsafety == hir::Unsafety::Unsafe {
276 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
285 "detects missing documentation for public members"
288 pub struct MissingDoc {
289 /// Stack of whether #[doc(hidden)] is set
290 /// at each level which has lint attributes.
291 doc_hidden_stack: Vec<bool>,
293 /// Private traits or trait items that leaked through. Don't check their methods.
294 private_traits: HashSet<ast::NodeId>,
298 pub fn new() -> MissingDoc {
300 doc_hidden_stack: vec![false],
301 private_traits: HashSet::new(),
305 fn doc_hidden(&self) -> bool {
306 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
309 fn check_missing_docs_attrs(&self,
311 id: Option<ast::NodeId>,
312 attrs: &[ast::Attribute],
314 desc: &'static str) {
315 // If we're building a test harness, then warning about
316 // documentation is probably not really relevant right now.
317 if cx.sess().opts.test {
321 // `#[doc(hidden)]` disables missing_docs check.
322 if self.doc_hidden() {
326 // Only check publicly-visible items, using the result from the privacy pass.
327 // It's an option so the crate root can also use this function (it doesn't
329 if let Some(id) = id {
330 if !cx.access_levels.is_exported(id) {
335 fn has_doc(attr: &ast::Attribute) -> bool {
336 if !attr.check_name("doc") {
340 if attr.is_value_str() {
344 if let Some(list) = attr.meta_item_list() {
346 if meta.check_name("include") {
355 let has_doc = attrs.iter().any(|a| has_doc(a));
357 cx.span_lint(MISSING_DOCS,
358 cx.tcx.sess.codemap().def_span(sp),
359 &format!("missing documentation for {}", desc));
364 impl LintPass for MissingDoc {
365 fn get_lints(&self) -> LintArray {
366 lint_array!(MISSING_DOCS)
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("doc") &&
375 match attr.meta_item_list() {
377 Some(l) => attr::list_contains_name(&l, "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");
391 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
392 let desc = match it.node {
393 hir::ItemFn(..) => "a function",
394 hir::ItemMod(..) => "a module",
395 hir::ItemEnum(..) => "an enum",
396 hir::ItemStruct(..) => "a struct",
397 hir::ItemUnion(..) => "a union",
398 hir::ItemTrait(.., ref trait_item_refs) => {
399 // Issue #11592, traits are always considered exported, even when private.
400 if it.vis.node == hir::VisibilityInherited {
401 self.private_traits.insert(it.id);
402 for trait_item_ref in trait_item_refs {
403 self.private_traits.insert(trait_item_ref.id.node_id);
409 hir::ItemTy(..) => "a type alias",
410 hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
411 // If the trait is private, add the impl items to private_traits so they don't get
412 // reported for missing docs.
413 let real_trait = trait_ref.path.def.def_id();
414 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
415 match cx.tcx.hir.find(node_id) {
416 Some(hir_map::NodeItem(item)) => {
417 if item.vis.node == hir::VisibilityInherited {
418 for impl_item_ref in impl_item_refs {
419 self.private_traits.insert(impl_item_ref.id.node_id);
428 hir::ItemConst(..) => "a constant",
429 hir::ItemStatic(..) => "a static",
433 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
436 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
437 if self.private_traits.contains(&trait_item.id) {
441 let desc = match trait_item.node {
442 hir::TraitItemKind::Const(..) => "an associated constant",
443 hir::TraitItemKind::Method(..) => "a trait method",
444 hir::TraitItemKind::Type(..) => "an associated type",
447 self.check_missing_docs_attrs(cx,
454 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
455 // If the method is an impl for a trait, don't doc.
456 if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
460 let desc = match impl_item.node {
461 hir::ImplItemKind::Const(..) => "an associated constant",
462 hir::ImplItemKind::Method(..) => "a method",
463 hir::ImplItemKind::Type(_) => "an associated type",
465 self.check_missing_docs_attrs(cx,
472 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
473 if !sf.is_positional() {
474 self.check_missing_docs_attrs(cx,
482 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
483 self.check_missing_docs_attrs(cx,
484 Some(v.node.data.id()),
492 pub MISSING_COPY_IMPLEMENTATIONS,
494 "detects potentially-forgotten implementations of `Copy`"
497 #[derive(Copy, Clone)]
498 pub struct MissingCopyImplementations;
500 impl LintPass for MissingCopyImplementations {
501 fn get_lints(&self) -> LintArray {
502 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
506 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
507 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
508 if !cx.access_levels.is_reachable(item.id) {
511 let (def, ty) = match item.node {
512 hir::ItemStruct(_, ref ast_generics) => {
513 if !ast_generics.params.is_empty() {
516 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
517 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
519 hir::ItemUnion(_, ref ast_generics) => {
520 if !ast_generics.params.is_empty() {
523 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
524 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
526 hir::ItemEnum(_, ref ast_generics) => {
527 if !ast_generics.params.is_empty() {
530 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
531 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
535 if def.has_dtor(cx.tcx) {
538 let param_env = ty::ParamEnv::empty();
539 if !ty.moves_by_default(cx.tcx, param_env, item.span) {
542 if param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
543 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
545 "type could implement `Copy`; consider adding `impl \
552 MISSING_DEBUG_IMPLEMENTATIONS,
554 "detects missing implementations of fmt::Debug"
557 pub struct MissingDebugImplementations {
558 impling_types: Option<NodeSet>,
561 impl MissingDebugImplementations {
562 pub fn new() -> MissingDebugImplementations {
563 MissingDebugImplementations { impling_types: None }
567 impl LintPass for MissingDebugImplementations {
568 fn get_lints(&self) -> LintArray {
569 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
573 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
574 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
575 if !cx.access_levels.is_reachable(item.id) {
580 hir::ItemStruct(..) |
582 hir::ItemEnum(..) => {}
586 let debug = match cx.tcx.lang_items().debug_trait() {
587 Some(debug) => debug,
591 if self.impling_types.is_none() {
592 let mut impls = NodeSet();
593 cx.tcx.for_each_impl(debug, |d| {
594 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
595 if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
596 impls.insert(node_id);
601 self.impling_types = Some(impls);
602 debug!("{:?}", self.impling_types);
605 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
606 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
608 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
609 or a manual implementation")
615 pub ANONYMOUS_PARAMETERS,
617 "detects anonymous parameters",
618 Edition::Edition2018 => Warn,
621 /// Checks for use of anonymous parameters (RFC 1685)
623 pub struct AnonymousParameters;
625 impl LintPass for AnonymousParameters {
626 fn get_lints(&self) -> LintArray {
627 lint_array!(ANONYMOUS_PARAMETERS)
631 impl EarlyLintPass for AnonymousParameters {
632 fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
634 ast::TraitItemKind::Method(ref sig, _) => {
635 for arg in sig.decl.inputs.iter() {
637 ast::PatKind::Ident(_, ident, None) => {
638 if ident.name == keywords::Invalid.name() {
642 .span_to_snippet(arg.ty.span);
644 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
645 (snip, Applicability::MachineApplicable)
647 ("<type>".to_owned(), Applicability::HasPlaceholders)
651 ANONYMOUS_PARAMETERS,
653 "anonymous parameters are deprecated and will be \
654 removed in the next edition."
655 ).span_suggestion_with_applicability(
657 "Try naming the parameter or explicitly \
659 format!("_: {}", ty_snip),
673 /// Checks for incorrect use use of `repr` attributes.
677 impl LintPass for BadRepr {
678 fn get_lints(&self) -> LintArray {
683 impl EarlyLintPass for BadRepr {
684 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
685 if attr.name() == "repr" {
686 let list = attr.meta_item_list();
688 let repr_str = |lit: &str| { format!("#[repr({})]", lit) };
690 // Emit warnings with `repr` either has a literal assignment (`#[repr = "C"]`) or
691 // no hints (``#[repr]`)
692 let has_hints = list.as_ref().map(|ref list| !list.is_empty()).unwrap_or(false);
694 let mut suggested = false;
695 let mut warn = if let Some(ref lit) = attr.value_str() {
696 // avoid warning about empty `repr` on `#[repr = "foo"]`
697 let mut warn = cx.struct_span_lint(
700 "`repr` attribute isn't configurable with a literal",
702 match format!("{}", lit).as_ref() {
703 | "C" | "packed" | "rust" | "transparent"
704 | "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
705 | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" => {
706 // if the literal could have been a valid `repr` arg,
707 // suggest the correct syntax
708 warn.span_suggestion(
710 "give `repr` a hint",
711 repr_str(&lit.as_str()),
715 _ => { // the literal wasn't a valid `repr` arg
716 warn.span_label(attr.span, "needs a hint");
721 let mut warn = cx.struct_span_lint(
724 "`repr` attribute must have a hint",
726 warn.span_label(attr.span, "needs a hint");
731 "valid hints include `{}`, `{}`, `{}` and `{}`",
735 repr_str("transparent"),
737 warn.note("for more information, visit \
738 <https://doc.rust-lang.org/reference/type-layout.html>");
746 /// Checks for use of attributes which have been deprecated.
748 pub struct DeprecatedAttr {
749 // This is not free to compute, so we want to keep it around, rather than
750 // compute it for every attribute.
751 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
754 impl DeprecatedAttr {
755 pub fn new() -> DeprecatedAttr {
757 depr_attrs: deprecated_attributes(),
762 impl LintPass for DeprecatedAttr {
763 fn get_lints(&self) -> LintArray {
768 impl EarlyLintPass for DeprecatedAttr {
769 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
770 for &&(n, _, ref g) in &self.depr_attrs {
771 if attr.name() == n {
772 if let &AttributeGate::Gated(Stability::Deprecated(link),
776 let msg = format!("use of deprecated attribute `{}`: {}. See {}",
778 let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
779 err.span_suggestion_short(attr.span, "remove this attribute", "".to_owned());
789 pub UNUSED_DOC_COMMENTS,
791 "detects doc comments that aren't used by rustdoc"
794 #[derive(Copy, Clone)]
795 pub struct UnusedDocComment;
797 impl LintPass for UnusedDocComment {
798 fn get_lints(&self) -> LintArray {
799 lint_array![UNUSED_DOC_COMMENTS]
803 impl UnusedDocComment {
804 fn warn_if_doc<'a, 'tcx,
805 I: Iterator<Item=&'a ast::Attribute>,
806 C: LintContext<'tcx>>(&self, mut attrs: I, cx: &C) {
807 if let Some(attr) = attrs.find(|a| a.is_value_str() && a.check_name("doc")) {
808 cx.struct_span_lint(UNUSED_DOC_COMMENTS, attr.span, "doc comment not used by rustdoc")
814 impl EarlyLintPass for UnusedDocComment {
815 fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) {
816 self.warn_if_doc(decl.attrs.iter(), cx);
819 fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) {
820 self.warn_if_doc(arm.attrs.iter(), cx);
823 fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
824 self.warn_if_doc(expr.attrs.iter(), cx);
829 pub UNCONDITIONAL_RECURSION,
831 "functions that cannot return without calling themselves"
834 #[derive(Copy, Clone)]
835 pub struct UnconditionalRecursion;
838 impl LintPass for UnconditionalRecursion {
839 fn get_lints(&self) -> LintArray {
840 lint_array![UNCONDITIONAL_RECURSION]
844 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
845 fn check_fn(&mut self,
852 let method = match fn_kind {
853 FnKind::ItemFn(..) => None,
854 FnKind::Method(..) => {
855 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
857 // closures can't recur, so they don't matter.
858 FnKind::Closure(_) => return,
861 // Walk through this function (say `f`) looking to see if
862 // every possible path references itself, i.e. the function is
863 // called recursively unconditionally. This is done by trying
864 // to find a path from the entry node to the exit node that
865 // *doesn't* call `f` by traversing from the entry while
866 // pretending that calls of `f` are sinks (i.e. ignoring any
867 // exit edges from them).
869 // NB. this has an edge case with non-returning statements,
870 // like `loop {}` or `panic!()`: control flow never reaches
871 // the exit node through these, so one can have a function
872 // that never actually calls itselfs but is still picked up by
875 // fn f(cond: bool) {
876 // if !cond { panic!() } // could come from `assert!(cond)`
880 // In general, functions of that form may be able to call
881 // itself a finite number of times and then diverge. The lint
882 // considers this to be an error for two reasons, (a) it is
883 // easier to implement, and (b) it seems rare to actually want
884 // to have behaviour like the above, rather than
885 // e.g. accidentally recurring after an assert.
887 let cfg = cfg::CFG::new(cx.tcx, &body);
889 let mut work_queue = vec![cfg.entry];
890 let mut reached_exit_without_self_call = false;
891 let mut self_call_spans = vec![];
892 let mut visited = HashSet::new();
894 while let Some(idx) = work_queue.pop() {
897 reached_exit_without_self_call = true;
901 let cfg_id = idx.node_id();
902 if visited.contains(&cfg_id) {
906 visited.insert(cfg_id);
908 // is this a recursive call?
909 let local_id = cfg.graph.node_data(idx).id();
910 if local_id != hir::DUMMY_ITEM_LOCAL_ID {
911 let node_id = cx.tcx.hir.hir_to_node_id(hir::HirId {
912 owner: body.value.hir_id.owner,
915 let self_recursive = match method {
916 Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
917 None => expr_refers_to_this_fn(cx, id, node_id),
920 self_call_spans.push(cx.tcx.hir.span(node_id));
921 // this is a self call, so we shouldn't explore past
922 // this node in the CFG.
927 // add the successors of this node to explore the graph further.
928 for (_, edge) in cfg.graph.outgoing_edges(idx) {
929 let target_idx = edge.target();
930 let target_cfg_id = target_idx.node_id();
931 if !visited.contains(&target_cfg_id) {
932 work_queue.push(target_idx)
937 // Check the number of self calls because a function that
938 // doesn't return (e.g. calls a `-> !` function or `loop { /*
939 // no break */ }`) shouldn't be linted unless it actually
941 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
942 let sp = cx.tcx.sess.codemap().def_span(sp);
943 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
945 "function cannot return without recurring");
946 db.span_label(sp, "cannot return without recurring");
947 // offer some help to the programmer.
948 for call in &self_call_spans {
949 db.span_label(*call, "recursive call site");
951 db.help("a `loop` may express intention better if this is on purpose");
958 // Functions for identifying if the given Expr NodeId `id`
959 // represents a call to the function `fn_id`/method `method`.
961 fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
962 match cx.tcx.hir.get(id) {
963 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
964 let def = if let hir::ExprPath(ref qpath) = callee.node {
965 cx.tables.qpath_def(qpath, callee.hir_id)
970 Def::Local(..) | Def::Upvar(..) => false,
971 _ => def.def_id() == cx.tcx.hir.local_def_id(fn_id)
978 // Check if the expression `id` performs a call to `method`.
979 fn expr_refers_to_this_method(cx: &LateContext,
980 method: &ty::AssociatedItem,
983 use rustc::ty::adjustment::*;
985 // Ignore non-expressions.
986 let expr = if let hir_map::NodeExpr(e) = cx.tcx.hir.get(id) {
992 // Check for overloaded autoderef method calls.
993 let mut source = cx.tables.expr_ty(expr);
994 for adjustment in cx.tables.expr_adjustments(expr) {
995 if let Adjust::Deref(Some(deref)) = adjustment.kind {
996 let (def_id, substs) = deref.method_call(cx.tcx, source);
997 if method_call_refers_to_method(cx, method, def_id, substs, id) {
1001 source = adjustment.target;
1004 // Check for method calls and overloaded operators.
1005 if cx.tables.is_method_call(expr) {
1006 let hir_id = cx.tcx.hir.definitions().node_to_hir_id(id);
1007 let def_id = cx.tables.type_dependent_defs()[hir_id].def_id();
1008 let substs = cx.tables.node_substs(hir_id);
1009 if method_call_refers_to_method(cx, method, def_id, substs, id) {
1014 // Check for calls to methods via explicit paths (e.g. `T::method()`).
1016 hir::ExprCall(ref callee, _) => {
1017 let def = if let hir::ExprPath(ref qpath) = callee.node {
1018 cx.tables.qpath_def(qpath, callee.hir_id)
1023 Def::Method(def_id) => {
1024 let substs = cx.tables.node_substs(callee.hir_id);
1025 method_call_refers_to_method(cx, method, def_id, substs, id)
1034 // Check if the method call to the method with the ID `callee_id`
1035 // and instantiated with `callee_substs` refers to method `method`.
1036 fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
1037 method: &ty::AssociatedItem,
1039 callee_substs: &Substs<'tcx>,
1040 expr_id: ast::NodeId)
1043 let callee_item = tcx.associated_item(callee_id);
1045 match callee_item.container {
1046 // This is an inherent method, so the `def_id` refers
1047 // directly to the method definition.
1048 ty::ImplContainer(_) => callee_id == method.def_id,
1050 // A trait method, from any number of possible sources.
1051 // Attempt to select a concrete impl before checking.
1052 ty::TraitContainer(trait_def_id) => {
1053 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
1054 let trait_ref = ty::Binder::bind(trait_ref);
1055 let span = tcx.hir.span(expr_id);
1057 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
1059 trait_ref.to_poly_trait_predicate());
1061 tcx.infer_ctxt().enter(|infcx| {
1062 let mut selcx = traits::SelectionContext::new(&infcx);
1063 match selcx.select(&obligation) {
1064 // The method comes from a `T: Trait` bound.
1065 // If `T` is `Self`, then this call is inside
1066 // a default method definition.
1067 Ok(Some(traits::VtableParam(_))) => {
1068 let on_self = trait_ref.self_ty().is_self();
1069 // We can only be recurring in a default
1070 // method if we're being called literally
1071 // on the `Self` type.
1072 on_self && callee_id == method.def_id
1075 // The `impl` is known, so we check that with a
1077 Ok(Some(traits::VtableImpl(vtable_impl))) => {
1078 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1079 // It matches if it comes from the same impl,
1080 // and has the same method name.
1081 container == method.container &&
1082 callee_item.ident.name == method.ident.name
1085 // There's no way to know if this call is
1086 // recursive, so we assume it's not.
1099 "compiler plugin used as ordinary library in non-plugin crate"
1102 #[derive(Copy, Clone)]
1103 pub struct PluginAsLibrary;
1105 impl LintPass for PluginAsLibrary {
1106 fn get_lints(&self) -> LintArray {
1107 lint_array![PLUGIN_AS_LIBRARY]
1111 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1112 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1113 if cx.sess().plugin_registrar_fn.get().is_some() {
1114 // We're compiling a plugin; it's fine to link other plugins.
1119 hir::ItemExternCrate(..) => (),
1123 let def_id = cx.tcx.hir.local_def_id(it.id);
1124 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
1125 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
1127 // Probably means we aren't linking the crate for some reason.
1129 // Not sure if / when this could happen.
1135 cx.span_lint(PLUGIN_AS_LIBRARY,
1137 "compiler plugin used as an ordinary library");
1143 PRIVATE_NO_MANGLE_FNS,
1145 "functions marked #[no_mangle] should be exported"
1149 PRIVATE_NO_MANGLE_STATICS,
1151 "statics marked #[no_mangle] should be exported"
1155 NO_MANGLE_CONST_ITEMS,
1157 "const items will not have their symbols exported"
1161 NO_MANGLE_GENERIC_ITEMS,
1163 "generic items must be mangled"
1166 #[derive(Copy, Clone)]
1167 pub struct InvalidNoMangleItems;
1169 impl LintPass for InvalidNoMangleItems {
1170 fn get_lints(&self) -> LintArray {
1171 lint_array!(PRIVATE_NO_MANGLE_FNS,
1172 PRIVATE_NO_MANGLE_STATICS,
1173 NO_MANGLE_CONST_ITEMS,
1174 NO_MANGLE_GENERIC_ITEMS)
1178 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1179 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1181 hir::ItemFn(.., ref generics, _) => {
1182 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
1183 if attr::contains_name(&it.attrs, "linkage") {
1186 if !cx.access_levels.is_reachable(it.id) {
1187 let msg = "function is marked #[no_mangle], but not exported";
1188 let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg);
1189 let insertion_span = it.span.shrink_to_lo();
1190 if it.vis.node == hir::VisibilityInherited {
1191 err.span_suggestion(insertion_span,
1192 "try making it public",
1197 for param in &generics.params {
1199 GenericParamKind::Lifetime { .. } => {}
1200 GenericParamKind::Type { .. } => {
1201 let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
1203 "functions generic over \
1204 types must be mangled");
1205 err.span_suggestion_short(no_mangle_attr.span,
1206 "remove this attribute",
1215 hir::ItemStatic(..) => {
1216 if attr::contains_name(&it.attrs, "no_mangle") &&
1217 !cx.access_levels.is_reachable(it.id) {
1218 let msg = "static is marked #[no_mangle], but not exported";
1219 let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, msg);
1220 let insertion_span = it.span.shrink_to_lo();
1221 if it.vis.node == hir::VisibilityInherited {
1222 err.span_suggestion(insertion_span,
1223 "try making it public",
1229 hir::ItemConst(..) => {
1230 if attr::contains_name(&it.attrs, "no_mangle") {
1231 // Const items do not refer to a particular location in memory, and therefore
1232 // don't have anything to attach a symbol to
1233 let msg = "const items should never be #[no_mangle]";
1234 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1236 // account for "pub const" (#45562)
1237 let start = cx.tcx.sess.codemap().span_to_snippet(it.span)
1238 .map(|snippet| snippet.find("const").unwrap_or(0))
1239 .unwrap_or(0) as u32;
1240 // `const` is 5 chars
1241 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
1242 err.span_suggestion(const_span,
1243 "try a static value",
1244 "pub static".to_owned());
1253 #[derive(Clone, Copy)]
1254 pub struct MutableTransmutes;
1259 "mutating transmuted &mut T from &T may cause undefined behavior"
1262 impl LintPass for MutableTransmutes {
1263 fn get_lints(&self) -> LintArray {
1264 lint_array!(MUTABLE_TRANSMUTES)
1268 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1269 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1270 use rustc_target::spec::abi::Abi::RustIntrinsic;
1272 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1273 consider instead using an UnsafeCell";
1274 match get_transmute_from_to(cx, expr) {
1275 Some((&ty::TyRef(_, _, from_mt), &ty::TyRef(_, _, to_mt))) => {
1276 if to_mt == hir::Mutability::MutMutable &&
1277 from_mt == hir::Mutability::MutImmutable {
1278 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1284 fn get_transmute_from_to<'a, 'tcx>
1285 (cx: &LateContext<'a, 'tcx>,
1287 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1288 let def = if let hir::ExprPath(ref qpath) = expr.node {
1289 cx.tables.qpath_def(qpath, expr.hir_id)
1293 if let Def::Fn(did) = def {
1294 if !def_id_is_transmute(cx, did) {
1297 let sig = cx.tables.node_id_to_type(expr.hir_id).fn_sig(cx.tcx);
1298 let from = sig.inputs().skip_binder()[0];
1299 let to = *sig.output().skip_binder();
1300 return Some((&from.sty, &to.sty));
1305 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1306 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1307 cx.tcx.item_name(def_id) == "transmute"
1312 /// Forbids using the `#[feature(...)]` attribute
1313 #[derive(Copy, Clone)]
1314 pub struct UnstableFeatures;
1319 "enabling unstable features (deprecated. do not use)"
1322 impl LintPass for UnstableFeatures {
1323 fn get_lints(&self) -> LintArray {
1324 lint_array!(UNSTABLE_FEATURES)
1328 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1329 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1330 if attr.check_name("feature") {
1331 if let Some(items) = attr.meta_item_list() {
1333 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1340 /// Lint for unions that contain fields with possibly non-trivial destructors.
1341 pub struct UnionsWithDropFields;
1344 UNIONS_WITH_DROP_FIELDS,
1346 "use of unions that contain fields with possibly non-trivial drop code"
1349 impl LintPass for UnionsWithDropFields {
1350 fn get_lints(&self) -> LintArray {
1351 lint_array!(UNIONS_WITH_DROP_FIELDS)
1355 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1356 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1357 if let hir::ItemUnion(ref vdata, _) = item.node {
1358 for field in vdata.fields() {
1359 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1360 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1361 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1363 "union contains a field with possibly non-trivial drop code, \
1364 drop code of union fields is ignored when dropping the union");
1372 /// Lint for items marked `pub` that aren't reachable from other crates
1373 pub struct UnreachablePub;
1376 pub UNREACHABLE_PUB,
1378 "`pub` items not reachable from crate root"
1381 impl LintPass for UnreachablePub {
1382 fn get_lints(&self) -> LintArray {
1383 lint_array!(UNREACHABLE_PUB)
1387 impl UnreachablePub {
1388 fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId,
1389 vis: &hir::Visibility, span: Span, exportable: bool,
1390 mut applicability: Applicability) {
1391 if !cx.access_levels.is_reachable(id) && vis.node.is_pub() {
1392 if span.ctxt().outer().expn_info().is_some() {
1393 applicability = Applicability::MaybeIncorrect;
1395 let def_span = cx.tcx.sess.codemap().def_span(span);
1396 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1397 &format!("unreachable `pub` {}", what));
1398 // We are presuming that visibility is token at start of
1399 // declaration (can be macro variable rather than literal `pub`)
1400 let pub_span = cx.tcx.sess.codemap().span_until_char(def_span, ' ');
1401 let replacement = if cx.tcx.features().crate_visibility_modifier {
1406 err.span_suggestion_with_applicability(pub_span,
1407 "consider restricting its visibility",
1411 err.help("or consider exporting it for use by other crates");
1419 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1420 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1421 let applicability = match item.node {
1422 // suggestion span-manipulation is inadequate for `pub use
1423 // module::{item}` (Issue #50455)
1424 hir::ItemUse(..) => Applicability::MaybeIncorrect,
1425 _ => Applicability::MachineApplicable,
1427 self.perform_lint(cx, "item", item.id, &item.vis, item.span, true, applicability);
1430 fn check_foreign_item(&mut self, cx: &LateContext, foreign_item: &hir::ForeignItem) {
1431 self.perform_lint(cx, "item", foreign_item.id, &foreign_item.vis,
1432 foreign_item.span, true, Applicability::MachineApplicable);
1435 fn check_struct_field(&mut self, cx: &LateContext, field: &hir::StructField) {
1436 self.perform_lint(cx, "field", field.id, &field.vis, field.span, false,
1437 Applicability::MachineApplicable);
1440 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
1441 self.perform_lint(cx, "item", impl_item.id, &impl_item.vis, impl_item.span, false,
1442 Applicability::MachineApplicable);
1446 /// Lint for trait and lifetime bounds in type aliases being mostly ignored:
1447 /// They are relevant when using associated types, but otherwise neither checked
1448 /// at definition site nor enforced at use site.
1450 pub struct TypeAliasBounds;
1455 "bounds in type aliases are not enforced"
1458 impl LintPass for TypeAliasBounds {
1459 fn get_lints(&self) -> LintArray {
1460 lint_array!(TYPE_ALIAS_BOUNDS)
1464 impl TypeAliasBounds {
1465 fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1467 hir::QPath::TypeRelative(ref ty, _) => {
1468 // If this is a type variable, we found a `T::Assoc`.
1470 hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
1472 Def::TyParam(_) => true,
1479 hir::QPath::Resolved(..) => false,
1483 fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder) {
1484 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1485 // bound. Let's see if this type does that.
1487 // We use a HIR visitor to walk the type.
1488 use rustc::hir::intravisit::{self, Visitor};
1489 use syntax::ast::NodeId;
1490 struct WalkAssocTypes<'a, 'db> where 'db: 'a {
1491 err: &'a mut DiagnosticBuilder<'db>
1493 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1494 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1496 intravisit::NestedVisitorMap::None
1499 fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: NodeId, span: Span) {
1500 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1501 self.err.span_help(span,
1502 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1503 associated types in type aliases");
1505 intravisit::walk_qpath(self, qpath, id, span)
1509 // Let's go for a walk!
1510 let mut visitor = WalkAssocTypes { err };
1511 visitor.visit_ty(ty);
1515 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1516 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1517 let (ty, type_alias_generics) = match item.node {
1518 hir::ItemTy(ref ty, ref generics) => (&*ty, generics),
1521 let mut suggested_changing_assoc_types = false;
1522 // There must not be a where clause
1523 if !type_alias_generics.where_clause.predicates.is_empty() {
1524 let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1525 .map(|pred| pred.span()).collect();
1526 let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1527 "where clauses are not enforced in type aliases");
1528 err.help("the clause will not be checked when the type alias is used, \
1529 and should be removed");
1530 if !suggested_changing_assoc_types {
1531 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1532 suggested_changing_assoc_types = true;
1536 // The parameters must not have bounds
1537 for param in type_alias_generics.params.iter() {
1538 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1539 if !spans.is_empty() {
1540 let mut err = cx.struct_span_lint(
1543 "bounds on generic parameters are not enforced in type aliases",
1545 err.help("the bound will not be checked when the type alias is used, \
1546 and should be removed");
1547 if !suggested_changing_assoc_types {
1548 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1549 suggested_changing_assoc_types = true;
1557 /// Lint constants that are erroneous.
1558 /// Without this lint, we might not get any diagnostic if the constant is
1559 /// unused within this crate, even though downstream crates can't use it
1560 /// without producing an error.
1561 pub struct UnusedBrokenConst;
1563 impl LintPass for UnusedBrokenConst {
1564 fn get_lints(&self) -> LintArray {
1569 fn check_const(cx: &LateContext, body_id: hir::BodyId, what: &str) {
1570 let def_id = cx.tcx.hir.body_owner_def_id(body_id);
1571 let param_env = cx.tcx.param_env(def_id);
1572 let cid = ::rustc::mir::interpret::GlobalId {
1573 instance: ty::Instance::mono(cx.tcx, def_id),
1576 if let Err(err) = cx.tcx.const_eval(param_env.and(cid)) {
1577 let span = cx.tcx.def_span(def_id);
1580 &format!("this {} cannot be used", what),
1581 cx.current_lint_root(),
1586 struct UnusedBrokenConstVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
1588 impl<'a, 'tcx, 'v> hir::intravisit::Visitor<'v> for UnusedBrokenConstVisitor<'a, 'tcx> {
1589 fn visit_nested_body(&mut self, id: hir::BodyId) {
1590 check_const(self.0, id, "array length");
1592 fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1593 hir::intravisit::NestedVisitorMap::None
1597 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1598 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1600 hir::ItemConst(_, body_id) => {
1601 check_const(cx, body_id, "constant");
1603 hir::ItemTy(ref ty, _) => hir::intravisit::walk_ty(
1604 &mut UnusedBrokenConstVisitor(cx),
1612 /// Lint for trait and lifetime bounds that don't depend on type parameters
1613 /// which either do nothing, or stop the item from being used.
1614 pub struct TrivialConstraints;
1619 "these bounds don't depend on an type parameters"
1622 impl LintPass for TrivialConstraints {
1623 fn get_lints(&self) -> LintArray {
1624 lint_array!(TRIVIAL_BOUNDS)
1628 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1631 cx: &LateContext<'a, 'tcx>,
1632 item: &'tcx hir::Item,
1634 use rustc::ty::fold::TypeFoldable;
1635 use rustc::ty::Predicate::*;
1638 if cx.tcx.features().trivial_bounds {
1639 let def_id = cx.tcx.hir.local_def_id(item.id);
1640 let predicates = cx.tcx.predicates_of(def_id);
1641 for predicate in &predicates.predicates {
1642 let predicate_kind_name = match *predicate {
1643 Trait(..) => "Trait",
1645 RegionOutlives(..) => "Lifetime",
1647 // Ignore projections, as they can only be global
1648 // if the trait bound is global
1650 // Ignore bounds that a user can't type
1655 ConstEvaluatable(..) => continue,
1657 if predicate.is_global() {
1661 &format!("{} bound {} does not depend on any type \
1662 or lifetime parameters", predicate_kind_name, predicate),
1671 /// Does nothing as a lint pass, but registers some `Lint`s
1672 /// which are used by other parts of the compiler.
1673 #[derive(Copy, Clone)]
1674 pub struct SoftLints;
1676 impl LintPass for SoftLints {
1677 fn get_lints(&self) -> LintArray {
1681 NON_SHORTHAND_FIELD_PATTERNS,
1684 MISSING_COPY_IMPLEMENTATIONS,
1685 MISSING_DEBUG_IMPLEMENTATIONS,
1686 ANONYMOUS_PARAMETERS,
1687 UNUSED_DOC_COMMENTS,
1688 UNCONDITIONAL_RECURSION,
1690 PRIVATE_NO_MANGLE_FNS,
1691 PRIVATE_NO_MANGLE_STATICS,
1692 NO_MANGLE_CONST_ITEMS,
1693 NO_MANGLE_GENERIC_ITEMS,
1696 UNIONS_WITH_DROP_FIELDS,
1706 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1708 "`...` range patterns are deprecated"
1712 pub struct EllipsisInclusiveRangePatterns;
1714 impl LintPass for EllipsisInclusiveRangePatterns {
1715 fn get_lints(&self) -> LintArray {
1716 lint_array!(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS)
1720 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1721 fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
1722 use self::ast::{PatKind, RangeEnd, RangeSyntax};
1724 if let PatKind::Range(
1725 _, _, Spanned { span, node: RangeEnd::Included(RangeSyntax::DotDotDot) }
1727 let msg = "`...` range patterns are deprecated";
1728 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, span, msg);
1729 err.span_suggestion_short_with_applicability(
1730 span, "use `..=` for an inclusive range", "..=".to_owned(),
1731 // FIXME: outstanding problem with precedence in ref patterns:
1732 // https://github.com/rust-lang/rust/issues/51043#issuecomment-392252285
1733 Applicability::MaybeIncorrect