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::VisibilityKind::Inherited {
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::VisibilityKind::Inherited {
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 if let Some(def) = cx.tables.type_dependent_defs().get(hir_id) {
1008 let def_id = def.def_id();
1009 let substs = cx.tables.node_substs(hir_id);
1010 if method_call_refers_to_method(cx, method, def_id, substs, id) {
1014 cx.tcx.sess.delay_span_bug(expr.span,
1015 "no type-dependent def for method call");
1019 // Check for calls to methods via explicit paths (e.g. `T::method()`).
1021 hir::ExprCall(ref callee, _) => {
1022 let def = if let hir::ExprPath(ref qpath) = callee.node {
1023 cx.tables.qpath_def(qpath, callee.hir_id)
1028 Def::Method(def_id) => {
1029 let substs = cx.tables.node_substs(callee.hir_id);
1030 method_call_refers_to_method(cx, method, def_id, substs, id)
1039 // Check if the method call to the method with the ID `callee_id`
1040 // and instantiated with `callee_substs` refers to method `method`.
1041 fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
1042 method: &ty::AssociatedItem,
1044 callee_substs: &Substs<'tcx>,
1045 expr_id: ast::NodeId)
1048 let callee_item = tcx.associated_item(callee_id);
1050 match callee_item.container {
1051 // This is an inherent method, so the `def_id` refers
1052 // directly to the method definition.
1053 ty::ImplContainer(_) => callee_id == method.def_id,
1055 // A trait method, from any number of possible sources.
1056 // Attempt to select a concrete impl before checking.
1057 ty::TraitContainer(trait_def_id) => {
1058 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
1059 let trait_ref = ty::Binder::bind(trait_ref);
1060 let span = tcx.hir.span(expr_id);
1062 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
1064 trait_ref.to_poly_trait_predicate());
1066 tcx.infer_ctxt().enter(|infcx| {
1067 let mut selcx = traits::SelectionContext::new(&infcx);
1068 match selcx.select(&obligation) {
1069 // The method comes from a `T: Trait` bound.
1070 // If `T` is `Self`, then this call is inside
1071 // a default method definition.
1072 Ok(Some(traits::VtableParam(_))) => {
1073 let on_self = trait_ref.self_ty().is_self();
1074 // We can only be recurring in a default
1075 // method if we're being called literally
1076 // on the `Self` type.
1077 on_self && callee_id == method.def_id
1080 // The `impl` is known, so we check that with a
1082 Ok(Some(traits::VtableImpl(vtable_impl))) => {
1083 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1084 // It matches if it comes from the same impl,
1085 // and has the same method name.
1086 container == method.container &&
1087 callee_item.ident.name == method.ident.name
1090 // There's no way to know if this call is
1091 // recursive, so we assume it's not.
1104 "compiler plugin used as ordinary library in non-plugin crate"
1107 #[derive(Copy, Clone)]
1108 pub struct PluginAsLibrary;
1110 impl LintPass for PluginAsLibrary {
1111 fn get_lints(&self) -> LintArray {
1112 lint_array![PLUGIN_AS_LIBRARY]
1116 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1117 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1118 if cx.sess().plugin_registrar_fn.get().is_some() {
1119 // We're compiling a plugin; it's fine to link other plugins.
1124 hir::ItemExternCrate(..) => (),
1128 let def_id = cx.tcx.hir.local_def_id(it.id);
1129 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
1130 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
1132 // Probably means we aren't linking the crate for some reason.
1134 // Not sure if / when this could happen.
1140 cx.span_lint(PLUGIN_AS_LIBRARY,
1142 "compiler plugin used as an ordinary library");
1148 PRIVATE_NO_MANGLE_FNS,
1150 "functions marked #[no_mangle] should be exported"
1154 PRIVATE_NO_MANGLE_STATICS,
1156 "statics marked #[no_mangle] should be exported"
1160 NO_MANGLE_CONST_ITEMS,
1162 "const items will not have their symbols exported"
1166 NO_MANGLE_GENERIC_ITEMS,
1168 "generic items must be mangled"
1171 #[derive(Copy, Clone)]
1172 pub struct InvalidNoMangleItems;
1174 impl LintPass for InvalidNoMangleItems {
1175 fn get_lints(&self) -> LintArray {
1176 lint_array!(PRIVATE_NO_MANGLE_FNS,
1177 PRIVATE_NO_MANGLE_STATICS,
1178 NO_MANGLE_CONST_ITEMS,
1179 NO_MANGLE_GENERIC_ITEMS)
1183 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1184 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1185 let suggest_export = |vis: &hir::Visibility, err: &mut DiagnosticBuilder| {
1186 let suggestion = match vis.node {
1187 hir::VisibilityKind::Inherited => {
1188 // inherited visibility is empty span at item start; need an extra space
1189 Some("pub ".to_owned())
1191 hir::VisibilityKind::Restricted { .. } |
1192 hir::VisibilityKind::Crate(_) => {
1193 Some("pub".to_owned())
1195 hir::VisibilityKind::Public => {
1196 err.help("try exporting the item with a `pub use` statement");
1200 if let Some(replacement) = suggestion {
1201 err.span_suggestion(vis.span, "try making it public", replacement);
1206 hir::ItemFn(.., ref generics, _) => {
1207 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
1208 if attr::contains_name(&it.attrs, "linkage") {
1211 if !cx.access_levels.is_reachable(it.id) {
1212 let msg = "function is marked #[no_mangle], but not exported";
1213 let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg);
1214 suggest_export(&it.vis, &mut err);
1217 for param in &generics.params {
1219 GenericParamKind::Lifetime { .. } => {}
1220 GenericParamKind::Type { .. } => {
1221 let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
1223 "functions generic over \
1224 types must be mangled");
1225 err.span_suggestion_short(no_mangle_attr.span,
1226 "remove this attribute",
1235 hir::ItemStatic(..) => {
1236 if attr::contains_name(&it.attrs, "no_mangle") &&
1237 !cx.access_levels.is_reachable(it.id) {
1238 let msg = "static is marked #[no_mangle], but not exported";
1239 let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, msg);
1240 suggest_export(&it.vis, &mut err);
1244 hir::ItemConst(..) => {
1245 if attr::contains_name(&it.attrs, "no_mangle") {
1246 // Const items do not refer to a particular location in memory, and therefore
1247 // don't have anything to attach a symbol to
1248 let msg = "const items should never be #[no_mangle]";
1249 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1251 // account for "pub const" (#45562)
1252 let start = cx.tcx.sess.codemap().span_to_snippet(it.span)
1253 .map(|snippet| snippet.find("const").unwrap_or(0))
1254 .unwrap_or(0) as u32;
1255 // `const` is 5 chars
1256 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
1257 err.span_suggestion(const_span,
1258 "try a static value",
1259 "pub static".to_owned());
1268 #[derive(Clone, Copy)]
1269 pub struct MutableTransmutes;
1274 "mutating transmuted &mut T from &T may cause undefined behavior"
1277 impl LintPass for MutableTransmutes {
1278 fn get_lints(&self) -> LintArray {
1279 lint_array!(MUTABLE_TRANSMUTES)
1283 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1284 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1285 use rustc_target::spec::abi::Abi::RustIntrinsic;
1287 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1288 consider instead using an UnsafeCell";
1289 match get_transmute_from_to(cx, expr) {
1290 Some((&ty::TyRef(_, _, from_mt), &ty::TyRef(_, _, to_mt))) => {
1291 if to_mt == hir::Mutability::MutMutable &&
1292 from_mt == hir::Mutability::MutImmutable {
1293 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1299 fn get_transmute_from_to<'a, 'tcx>
1300 (cx: &LateContext<'a, 'tcx>,
1302 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1303 let def = if let hir::ExprPath(ref qpath) = expr.node {
1304 cx.tables.qpath_def(qpath, expr.hir_id)
1308 if let Def::Fn(did) = def {
1309 if !def_id_is_transmute(cx, did) {
1312 let sig = cx.tables.node_id_to_type(expr.hir_id).fn_sig(cx.tcx);
1313 let from = sig.inputs().skip_binder()[0];
1314 let to = *sig.output().skip_binder();
1315 return Some((&from.sty, &to.sty));
1320 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1321 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1322 cx.tcx.item_name(def_id) == "transmute"
1327 /// Forbids using the `#[feature(...)]` attribute
1328 #[derive(Copy, Clone)]
1329 pub struct UnstableFeatures;
1334 "enabling unstable features (deprecated. do not use)"
1337 impl LintPass for UnstableFeatures {
1338 fn get_lints(&self) -> LintArray {
1339 lint_array!(UNSTABLE_FEATURES)
1343 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1344 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1345 if attr.check_name("feature") {
1346 if let Some(items) = attr.meta_item_list() {
1348 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1355 /// Lint for unions that contain fields with possibly non-trivial destructors.
1356 pub struct UnionsWithDropFields;
1359 UNIONS_WITH_DROP_FIELDS,
1361 "use of unions that contain fields with possibly non-trivial drop code"
1364 impl LintPass for UnionsWithDropFields {
1365 fn get_lints(&self) -> LintArray {
1366 lint_array!(UNIONS_WITH_DROP_FIELDS)
1370 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1371 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1372 if let hir::ItemUnion(ref vdata, _) = item.node {
1373 for field in vdata.fields() {
1374 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1375 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1376 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1378 "union contains a field with possibly non-trivial drop code, \
1379 drop code of union fields is ignored when dropping the union");
1387 /// Lint for items marked `pub` that aren't reachable from other crates
1388 pub struct UnreachablePub;
1391 pub UNREACHABLE_PUB,
1393 "`pub` items not reachable from crate root"
1396 impl LintPass for UnreachablePub {
1397 fn get_lints(&self) -> LintArray {
1398 lint_array!(UNREACHABLE_PUB)
1402 impl UnreachablePub {
1403 fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId,
1404 vis: &hir::Visibility, span: Span, exportable: bool) {
1405 let mut applicability = Applicability::MachineApplicable;
1407 hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
1408 if span.ctxt().outer().expn_info().is_some() {
1409 applicability = Applicability::MaybeIncorrect;
1411 let def_span = cx.tcx.sess.codemap().def_span(span);
1412 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1413 &format!("unreachable `pub` {}", what));
1414 let replacement = if cx.tcx.features().crate_visibility_modifier {
1420 err.span_suggestion_with_applicability(vis.span,
1421 "consider restricting its visibility",
1425 err.help("or consider exporting it for use by other crates");
1435 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1436 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1437 self.perform_lint(cx, "item", item.id, &item.vis, item.span, true);
1440 fn check_foreign_item(&mut self, cx: &LateContext, foreign_item: &hir::ForeignItem) {
1441 self.perform_lint(cx, "item", foreign_item.id, &foreign_item.vis,
1442 foreign_item.span, true);
1445 fn check_struct_field(&mut self, cx: &LateContext, field: &hir::StructField) {
1446 self.perform_lint(cx, "field", field.id, &field.vis, field.span, false);
1449 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
1450 self.perform_lint(cx, "item", impl_item.id, &impl_item.vis, impl_item.span, false);
1454 /// Lint for trait and lifetime bounds in type aliases being mostly ignored:
1455 /// They are relevant when using associated types, but otherwise neither checked
1456 /// at definition site nor enforced at use site.
1458 pub struct TypeAliasBounds;
1463 "bounds in type aliases are not enforced"
1466 impl LintPass for TypeAliasBounds {
1467 fn get_lints(&self) -> LintArray {
1468 lint_array!(TYPE_ALIAS_BOUNDS)
1472 impl TypeAliasBounds {
1473 fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1475 hir::QPath::TypeRelative(ref ty, _) => {
1476 // If this is a type variable, we found a `T::Assoc`.
1478 hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
1480 Def::TyParam(_) => true,
1487 hir::QPath::Resolved(..) => false,
1491 fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder) {
1492 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1493 // bound. Let's see if this type does that.
1495 // We use a HIR visitor to walk the type.
1496 use rustc::hir::intravisit::{self, Visitor};
1497 use syntax::ast::NodeId;
1498 struct WalkAssocTypes<'a, 'db> where 'db: 'a {
1499 err: &'a mut DiagnosticBuilder<'db>
1501 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1502 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1504 intravisit::NestedVisitorMap::None
1507 fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: NodeId, span: Span) {
1508 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1509 self.err.span_help(span,
1510 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1511 associated types in type aliases");
1513 intravisit::walk_qpath(self, qpath, id, span)
1517 // Let's go for a walk!
1518 let mut visitor = WalkAssocTypes { err };
1519 visitor.visit_ty(ty);
1523 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1524 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1525 let (ty, type_alias_generics) = match item.node {
1526 hir::ItemTy(ref ty, ref generics) => (&*ty, generics),
1529 let mut suggested_changing_assoc_types = false;
1530 // There must not be a where clause
1531 if !type_alias_generics.where_clause.predicates.is_empty() {
1532 let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1533 .map(|pred| pred.span()).collect();
1534 let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1535 "where clauses are not enforced in type aliases");
1536 err.help("the clause will not be checked when the type alias is used, \
1537 and should be removed");
1538 if !suggested_changing_assoc_types {
1539 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1540 suggested_changing_assoc_types = true;
1544 // The parameters must not have bounds
1545 for param in type_alias_generics.params.iter() {
1546 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1547 if !spans.is_empty() {
1548 let mut err = cx.struct_span_lint(
1551 "bounds on generic parameters are not enforced in type aliases",
1553 err.help("the bound will not be checked when the type alias is used, \
1554 and should be removed");
1555 if !suggested_changing_assoc_types {
1556 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1557 suggested_changing_assoc_types = true;
1565 /// Lint constants that are erroneous.
1566 /// Without this lint, we might not get any diagnostic if the constant is
1567 /// unused within this crate, even though downstream crates can't use it
1568 /// without producing an error.
1569 pub struct UnusedBrokenConst;
1571 impl LintPass for UnusedBrokenConst {
1572 fn get_lints(&self) -> LintArray {
1577 fn check_const(cx: &LateContext, body_id: hir::BodyId, what: &str) {
1578 let def_id = cx.tcx.hir.body_owner_def_id(body_id);
1579 let param_env = cx.tcx.param_env(def_id);
1580 let cid = ::rustc::mir::interpret::GlobalId {
1581 instance: ty::Instance::mono(cx.tcx, def_id),
1584 if let Err(err) = cx.tcx.const_eval(param_env.and(cid)) {
1585 let span = cx.tcx.def_span(def_id);
1588 &format!("this {} cannot be used", what),
1589 cx.current_lint_root(),
1594 struct UnusedBrokenConstVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
1596 impl<'a, 'tcx, 'v> hir::intravisit::Visitor<'v> for UnusedBrokenConstVisitor<'a, 'tcx> {
1597 fn visit_nested_body(&mut self, id: hir::BodyId) {
1598 check_const(self.0, id, "array length");
1600 fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1601 hir::intravisit::NestedVisitorMap::None
1605 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1606 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1608 hir::ItemConst(_, body_id) => {
1609 check_const(cx, body_id, "constant");
1611 hir::ItemTy(ref ty, _) => hir::intravisit::walk_ty(
1612 &mut UnusedBrokenConstVisitor(cx),
1620 /// Lint for trait and lifetime bounds that don't depend on type parameters
1621 /// which either do nothing, or stop the item from being used.
1622 pub struct TrivialConstraints;
1627 "these bounds don't depend on an type parameters"
1630 impl LintPass for TrivialConstraints {
1631 fn get_lints(&self) -> LintArray {
1632 lint_array!(TRIVIAL_BOUNDS)
1636 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1639 cx: &LateContext<'a, 'tcx>,
1640 item: &'tcx hir::Item,
1642 use rustc::ty::fold::TypeFoldable;
1643 use rustc::ty::Predicate::*;
1646 if cx.tcx.features().trivial_bounds {
1647 let def_id = cx.tcx.hir.local_def_id(item.id);
1648 let predicates = cx.tcx.predicates_of(def_id);
1649 for predicate in &predicates.predicates {
1650 let predicate_kind_name = match *predicate {
1651 Trait(..) => "Trait",
1653 RegionOutlives(..) => "Lifetime",
1655 // Ignore projections, as they can only be global
1656 // if the trait bound is global
1658 // Ignore bounds that a user can't type
1663 ConstEvaluatable(..) => continue,
1665 if predicate.is_global() {
1669 &format!("{} bound {} does not depend on any type \
1670 or lifetime parameters", predicate_kind_name, predicate),
1679 /// Does nothing as a lint pass, but registers some `Lint`s
1680 /// which are used by other parts of the compiler.
1681 #[derive(Copy, Clone)]
1682 pub struct SoftLints;
1684 impl LintPass for SoftLints {
1685 fn get_lints(&self) -> LintArray {
1689 NON_SHORTHAND_FIELD_PATTERNS,
1692 MISSING_COPY_IMPLEMENTATIONS,
1693 MISSING_DEBUG_IMPLEMENTATIONS,
1694 ANONYMOUS_PARAMETERS,
1695 UNUSED_DOC_COMMENTS,
1696 UNCONDITIONAL_RECURSION,
1698 PRIVATE_NO_MANGLE_FNS,
1699 PRIVATE_NO_MANGLE_STATICS,
1700 NO_MANGLE_CONST_ITEMS,
1701 NO_MANGLE_GENERIC_ITEMS,
1704 UNIONS_WITH_DROP_FIELDS,
1714 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1716 "`...` range patterns are deprecated"
1720 pub struct EllipsisInclusiveRangePatterns;
1722 impl LintPass for EllipsisInclusiveRangePatterns {
1723 fn get_lints(&self) -> LintArray {
1724 lint_array!(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS)
1728 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1729 fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
1730 use self::ast::{PatKind, RangeEnd, RangeSyntax};
1732 if let PatKind::Range(
1733 _, _, Spanned { span, node: RangeEnd::Included(RangeSyntax::DotDotDot) }
1735 let msg = "`...` range patterns are deprecated";
1736 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, span, msg);
1737 err.span_suggestion_short_with_applicability(
1738 span, "use `..=` for an inclusive range", "..=".to_owned(),
1739 // FIXME: outstanding problem with precedence in ref patterns:
1740 // https://github.com/rust-lang/rust/issues/51043#issuecomment-392252285
1741 Applicability::MaybeIncorrect