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;
43 use rustc::util::nodemap::FxHashSet;
45 use syntax::tokenstream::{TokenTree, TokenStream};
48 use syntax::source_map::Spanned;
49 use syntax::edition::Edition;
50 use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
51 use syntax_pos::{BytePos, Span, SyntaxContext};
52 use syntax::symbol::keywords;
53 use syntax::errors::{Applicability, DiagnosticBuilder};
55 use rustc::hir::{self, GenericParamKind, PatKind};
56 use rustc::hir::intravisit::FnKind;
58 use bad_style::{MethodLateContext, method_context};
60 // hardwired lints from librustc
61 pub use lint::builtin::*;
66 "suggest using `loop { }` instead of `while true { }`"
69 #[derive(Copy, Clone)]
72 impl LintPass for WhileTrue {
73 fn get_lints(&self) -> LintArray {
74 lint_array!(WHILE_TRUE)
78 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
79 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
80 if let hir::ExprKind::While(ref cond, ..) = e.node {
81 if let hir::ExprKind::Lit(ref lit) = cond.node {
82 if let ast::LitKind::Bool(true) = lit.node {
83 if lit.span.ctxt() == SyntaxContext::empty() {
84 let msg = "denote infinite loops with `loop { ... }`";
85 let condition_span = cx.tcx.sess.source_map().def_span(e.span);
86 let mut err = cx.struct_span_lint(WHILE_TRUE, condition_span, msg);
87 err.span_suggestion_short_with_applicability(
91 Applicability::MachineApplicable
104 "use of owned (Box type) heap memory"
107 #[derive(Copy, Clone)]
108 pub struct BoxPointers;
111 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
112 for leaf_ty in ty.walk() {
113 if leaf_ty.is_box() {
114 let m = format!("type uses owned (Box type) pointers: {}", ty);
115 cx.span_lint(BOX_POINTERS, span, &m);
121 impl LintPass for BoxPointers {
122 fn get_lints(&self) -> LintArray {
123 lint_array!(BOX_POINTERS)
127 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
128 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
130 hir::ItemKind::Fn(..) |
131 hir::ItemKind::Ty(..) |
132 hir::ItemKind::Enum(..) |
133 hir::ItemKind::Struct(..) |
134 hir::ItemKind::Union(..) => {
135 let def_id = cx.tcx.hir.local_def_id(it.id);
136 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
141 // If it's a struct, we also have to check the fields' types
143 hir::ItemKind::Struct(ref struct_def, _) |
144 hir::ItemKind::Union(ref struct_def, _) => {
145 for struct_field in struct_def.fields() {
146 let def_id = cx.tcx.hir.local_def_id(struct_field.id);
147 self.check_heap_type(cx, struct_field.span,
148 cx.tcx.type_of(def_id));
155 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
156 let ty = cx.tables.node_id_to_type(e.hir_id);
157 self.check_heap_type(cx, e.span, ty);
162 NON_SHORTHAND_FIELD_PATTERNS,
164 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
167 #[derive(Copy, Clone)]
168 pub struct NonShorthandFieldPatterns;
170 impl LintPass for NonShorthandFieldPatterns {
171 fn get_lints(&self) -> LintArray {
172 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
176 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
177 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
178 if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node {
179 let variant = cx.tables.pat_ty(pat).ty_adt_def()
180 .expect("struct pattern type is not an ADT")
181 .variant_of_def(cx.tables.qpath_def(qpath, pat.hir_id));
182 for fieldpat in field_pats {
183 if fieldpat.node.is_shorthand {
186 if fieldpat.span.ctxt().outer().expn_info().is_some() {
187 // Don't lint if this is a macro expansion: macro authors
188 // shouldn't have to worry about this kind of style issue
192 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
193 if cx.tcx.find_field_index(ident, &variant) ==
194 Some(cx.tcx.field_index(fieldpat.node.id, cx.tables)) {
195 let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
197 &format!("the `{}:` in this pattern is redundant", ident));
198 let subspan = cx.tcx.sess.source_map().span_through_char(fieldpat.span,
200 err.span_suggestion_short_with_applicability(
204 Applicability::MachineApplicable
217 "usage of `unsafe` code"
220 #[derive(Copy, Clone)]
221 pub struct UnsafeCode;
223 impl LintPass for UnsafeCode {
224 fn get_lints(&self) -> LintArray {
225 lint_array!(UNSAFE_CODE)
230 fn report_unsafe(&self, cx: &LateContext, span: Span, desc: &'static str) {
231 // This comes from a macro that has #[allow_internal_unsafe].
232 if span.allows_unsafe() {
236 cx.span_lint(UNSAFE_CODE, span, desc);
240 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
241 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
242 if let hir::ExprKind::Block(ref blk, _) = e.node {
243 // Don't warn about generated blocks, that'll just pollute the output.
244 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
245 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
250 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
252 hir::ItemKind::Trait(_, hir::Unsafety::Unsafe, ..) => {
253 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
256 hir::ItemKind::Impl(hir::Unsafety::Unsafe, ..) => {
257 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
264 fn check_fn(&mut self,
272 FnKind::ItemFn(_, _, hir::FnHeader { unsafety: hir::Unsafety::Unsafe, .. }, ..) => {
273 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
276 FnKind::Method(_, sig, ..) => {
277 if sig.header.unsafety == hir::Unsafety::Unsafe {
278 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
286 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
287 if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
288 if sig.header.unsafety == hir::Unsafety::Unsafe {
289 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
298 "detects missing documentation for public members",
299 report_in_external_macro: true
302 pub struct MissingDoc {
303 /// Stack of whether #[doc(hidden)] is set
304 /// at each level which has lint attributes.
305 doc_hidden_stack: Vec<bool>,
307 /// Private traits or trait items that leaked through. Don't check their methods.
308 private_traits: HashSet<ast::NodeId>,
312 pub fn new() -> MissingDoc {
314 doc_hidden_stack: vec![false],
315 private_traits: HashSet::new(),
319 fn doc_hidden(&self) -> bool {
320 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
323 fn check_missing_docs_attrs(&self,
325 id: Option<ast::NodeId>,
326 attrs: &[ast::Attribute],
328 desc: &'static str) {
329 // If we're building a test harness, then warning about
330 // documentation is probably not really relevant right now.
331 if cx.sess().opts.test {
335 // `#[doc(hidden)]` disables missing_docs check.
336 if self.doc_hidden() {
340 // Only check publicly-visible items, using the result from the privacy pass.
341 // It's an option so the crate root can also use this function (it doesn't
343 if let Some(id) = id {
344 if !cx.access_levels.is_exported(id) {
349 fn has_doc(attr: &ast::Attribute) -> bool {
350 if !attr.check_name("doc") {
354 if attr.is_value_str() {
358 if let Some(list) = attr.meta_item_list() {
360 if meta.check_name("include") {
369 let has_doc = attrs.iter().any(|a| has_doc(a));
371 cx.span_lint(MISSING_DOCS,
372 cx.tcx.sess.source_map().def_span(sp),
373 &format!("missing documentation for {}", desc));
378 impl LintPass for MissingDoc {
379 fn get_lints(&self) -> LintArray {
380 lint_array!(MISSING_DOCS)
384 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
385 fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
386 let doc_hidden = self.doc_hidden() ||
387 attrs.iter().any(|attr| {
388 attr.check_name("doc") &&
389 match attr.meta_item_list() {
391 Some(l) => attr::list_contains_name(&l, "hidden"),
394 self.doc_hidden_stack.push(doc_hidden);
397 fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
398 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
401 fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
402 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
405 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
406 let desc = match it.node {
407 hir::ItemKind::Fn(..) => "a function",
408 hir::ItemKind::Mod(..) => "a module",
409 hir::ItemKind::Enum(..) => "an enum",
410 hir::ItemKind::Struct(..) => "a struct",
411 hir::ItemKind::Union(..) => "a union",
412 hir::ItemKind::Trait(.., ref trait_item_refs) => {
413 // Issue #11592, traits are always considered exported, even when private.
414 if let hir::VisibilityKind::Inherited = it.vis.node {
415 self.private_traits.insert(it.id);
416 for trait_item_ref in trait_item_refs {
417 self.private_traits.insert(trait_item_ref.id.node_id);
423 hir::ItemKind::Ty(..) => "a type alias",
424 hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
425 // If the trait is private, add the impl items to private_traits so they don't get
426 // reported for missing docs.
427 let real_trait = trait_ref.path.def.def_id();
428 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
429 match cx.tcx.hir.find(node_id) {
430 Some(hir_map::NodeItem(item)) => {
431 if let hir::VisibilityKind::Inherited = item.vis.node {
432 for impl_item_ref in impl_item_refs {
433 self.private_traits.insert(impl_item_ref.id.node_id);
442 hir::ItemKind::Const(..) => "a constant",
443 hir::ItemKind::Static(..) => "a static",
447 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
450 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
451 if self.private_traits.contains(&trait_item.id) {
455 let desc = match trait_item.node {
456 hir::TraitItemKind::Const(..) => "an associated constant",
457 hir::TraitItemKind::Method(..) => "a trait method",
458 hir::TraitItemKind::Type(..) => "an associated type",
461 self.check_missing_docs_attrs(cx,
468 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
469 // If the method is an impl for a trait, don't doc.
470 if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
474 let desc = match impl_item.node {
475 hir::ImplItemKind::Const(..) => "an associated constant",
476 hir::ImplItemKind::Method(..) => "a method",
477 hir::ImplItemKind::Type(_) => "an associated type",
478 hir::ImplItemKind::Existential(_) => "an associated existential type",
480 self.check_missing_docs_attrs(cx,
487 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
488 if !sf.is_positional() {
489 self.check_missing_docs_attrs(cx,
497 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
498 self.check_missing_docs_attrs(cx,
499 Some(v.node.data.id()),
507 pub MISSING_COPY_IMPLEMENTATIONS,
509 "detects potentially-forgotten implementations of `Copy`"
512 #[derive(Copy, Clone)]
513 pub struct MissingCopyImplementations;
515 impl LintPass for MissingCopyImplementations {
516 fn get_lints(&self) -> LintArray {
517 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
521 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
522 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
523 if !cx.access_levels.is_reachable(item.id) {
526 let (def, ty) = match item.node {
527 hir::ItemKind::Struct(_, ref ast_generics) => {
528 if !ast_generics.params.is_empty() {
531 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
532 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
534 hir::ItemKind::Union(_, ref ast_generics) => {
535 if !ast_generics.params.is_empty() {
538 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
539 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
541 hir::ItemKind::Enum(_, ref ast_generics) => {
542 if !ast_generics.params.is_empty() {
545 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
546 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
550 if def.has_dtor(cx.tcx) {
553 let param_env = ty::ParamEnv::empty();
554 if !ty.moves_by_default(cx.tcx, param_env, item.span) {
557 if param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
558 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
560 "type could implement `Copy`; consider adding `impl \
567 MISSING_DEBUG_IMPLEMENTATIONS,
569 "detects missing implementations of fmt::Debug"
572 pub struct MissingDebugImplementations {
573 impling_types: Option<NodeSet>,
576 impl MissingDebugImplementations {
577 pub fn new() -> MissingDebugImplementations {
578 MissingDebugImplementations { impling_types: None }
582 impl LintPass for MissingDebugImplementations {
583 fn get_lints(&self) -> LintArray {
584 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
588 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
589 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
590 if !cx.access_levels.is_reachable(item.id) {
595 hir::ItemKind::Struct(..) |
596 hir::ItemKind::Union(..) |
597 hir::ItemKind::Enum(..) => {}
601 let debug = match cx.tcx.lang_items().debug_trait() {
602 Some(debug) => debug,
606 if self.impling_types.is_none() {
607 let mut impls = NodeSet();
608 cx.tcx.for_each_impl(debug, |d| {
609 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
610 if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def.did) {
611 impls.insert(node_id);
616 self.impling_types = Some(impls);
617 debug!("{:?}", self.impling_types);
620 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
621 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
623 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
624 or a manual implementation")
630 pub ANONYMOUS_PARAMETERS,
632 "detects anonymous parameters",
633 Edition::Edition2018 => Warn
636 /// Checks for use of anonymous parameters (RFC 1685)
638 pub struct AnonymousParameters;
640 impl LintPass for AnonymousParameters {
641 fn get_lints(&self) -> LintArray {
642 lint_array!(ANONYMOUS_PARAMETERS)
646 impl EarlyLintPass for AnonymousParameters {
647 fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
649 ast::TraitItemKind::Method(ref sig, _) => {
650 for arg in sig.decl.inputs.iter() {
652 ast::PatKind::Ident(_, ident, None) => {
653 if ident.name == keywords::Invalid.name() {
657 .span_to_snippet(arg.ty.span);
659 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
660 (snip, Applicability::MachineApplicable)
662 ("<type>".to_owned(), Applicability::HasPlaceholders)
666 ANONYMOUS_PARAMETERS,
668 "anonymous parameters are deprecated and will be \
669 removed in the next edition."
670 ).span_suggestion_with_applicability(
672 "Try naming the parameter or explicitly \
674 format!("_: {}", ty_snip),
688 /// Checks for incorrect use use of `repr` attributes.
692 impl LintPass for BadRepr {
693 fn get_lints(&self) -> LintArray {
698 impl EarlyLintPass for BadRepr {
699 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
700 if attr.name() == "repr" {
701 let list = attr.meta_item_list();
703 let repr_str = |lit: &str| { format!("#[repr({})]", lit) };
705 // Emit warnings with `repr` either has a literal assignment (`#[repr = "C"]`) or
706 // no hints (``#[repr]`)
707 let has_hints = list.as_ref().map(|ref list| !list.is_empty()).unwrap_or(false);
709 let mut suggested = false;
710 let mut warn = if let Some(ref lit) = attr.value_str() {
711 // avoid warning about empty `repr` on `#[repr = "foo"]`
712 let mut warn = cx.struct_span_lint(
715 "`repr` attribute isn't configurable with a literal",
717 match lit.to_string().as_ref() {
718 | "C" | "packed" | "rust" | "transparent"
719 | "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
720 | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" => {
721 // if the literal could have been a valid `repr` arg,
722 // suggest the correct syntax
723 warn.span_suggestion_with_applicability(
725 "give `repr` a hint",
726 repr_str(&lit.as_str()),
727 Applicability::MachineApplicable
731 _ => { // the literal wasn't a valid `repr` arg
732 warn.span_label(attr.span, "needs a hint");
737 let mut warn = cx.struct_span_lint(
740 "`repr` attribute must have a hint",
742 warn.span_label(attr.span, "needs a hint");
747 "valid hints include `{}`, `{}`, `{}` and `{}`",
751 repr_str("transparent"),
753 warn.note("for more information, visit \
754 <https://doc.rust-lang.org/reference/type-layout.html>");
762 /// Checks for use of attributes which have been deprecated.
764 pub struct DeprecatedAttr {
765 // This is not free to compute, so we want to keep it around, rather than
766 // compute it for every attribute.
767 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
770 impl DeprecatedAttr {
771 pub fn new() -> DeprecatedAttr {
773 depr_attrs: deprecated_attributes(),
778 impl LintPass for DeprecatedAttr {
779 fn get_lints(&self) -> LintArray {
784 impl EarlyLintPass for DeprecatedAttr {
785 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
786 for &&(n, _, ref g) in &self.depr_attrs {
787 if attr.name() == n {
788 if let &AttributeGate::Gated(Stability::Deprecated(link),
792 let msg = format!("use of deprecated attribute `{}`: {}. See {}",
794 let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
795 err.span_suggestion_short_with_applicability(
797 "remove this attribute",
799 Applicability::MachineApplicable
810 pub UNUSED_DOC_COMMENTS,
812 "detects doc comments that aren't used by rustdoc"
815 #[derive(Copy, Clone)]
816 pub struct UnusedDocComment;
818 impl LintPass for UnusedDocComment {
819 fn get_lints(&self) -> LintArray {
820 lint_array![UNUSED_DOC_COMMENTS]
824 impl UnusedDocComment {
825 fn warn_if_doc<'a, 'tcx,
826 I: Iterator<Item=&'a ast::Attribute>,
827 C: LintContext<'tcx>>(&self, mut attrs: I, cx: &C) {
828 if let Some(attr) = attrs.find(|a| a.is_value_str() && a.check_name("doc")) {
829 cx.struct_span_lint(UNUSED_DOC_COMMENTS, attr.span, "doc comment not used by rustdoc")
835 impl EarlyLintPass for UnusedDocComment {
836 fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) {
837 self.warn_if_doc(decl.attrs.iter(), cx);
840 fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) {
841 self.warn_if_doc(arm.attrs.iter(), cx);
844 fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
845 self.warn_if_doc(expr.attrs.iter(), cx);
850 pub UNCONDITIONAL_RECURSION,
852 "functions that cannot return without calling themselves"
855 #[derive(Copy, Clone)]
856 pub struct UnconditionalRecursion;
859 impl LintPass for UnconditionalRecursion {
860 fn get_lints(&self) -> LintArray {
861 lint_array![UNCONDITIONAL_RECURSION]
865 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
866 fn check_fn(&mut self,
873 let method = match fn_kind {
874 FnKind::ItemFn(..) => None,
875 FnKind::Method(..) => {
876 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
878 // closures can't recur, so they don't matter.
879 FnKind::Closure(_) => return,
882 // Walk through this function (say `f`) looking to see if
883 // every possible path references itself, i.e. the function is
884 // called recursively unconditionally. This is done by trying
885 // to find a path from the entry node to the exit node that
886 // *doesn't* call `f` by traversing from the entry while
887 // pretending that calls of `f` are sinks (i.e. ignoring any
888 // exit edges from them).
890 // NB. this has an edge case with non-returning statements,
891 // like `loop {}` or `panic!()`: control flow never reaches
892 // the exit node through these, so one can have a function
893 // that never actually calls itself but is still picked up by
896 // fn f(cond: bool) {
897 // if !cond { panic!() } // could come from `assert!(cond)`
901 // In general, functions of that form may be able to call
902 // itself a finite number of times and then diverge. The lint
903 // considers this to be an error for two reasons, (a) it is
904 // easier to implement, and (b) it seems rare to actually want
905 // to have behaviour like the above, rather than
906 // e.g. accidentally recurring after an assert.
908 let cfg = cfg::CFG::new(cx.tcx, &body);
910 let mut work_queue = vec![cfg.entry];
911 let mut reached_exit_without_self_call = false;
912 let mut self_call_spans = vec![];
913 let mut visited = HashSet::new();
915 while let Some(idx) = work_queue.pop() {
918 reached_exit_without_self_call = true;
922 let cfg_id = idx.node_id();
923 if visited.contains(&cfg_id) {
927 visited.insert(cfg_id);
929 // is this a recursive call?
930 let local_id = cfg.graph.node_data(idx).id();
931 if local_id != hir::DUMMY_ITEM_LOCAL_ID {
932 let node_id = cx.tcx.hir.hir_to_node_id(hir::HirId {
933 owner: body.value.hir_id.owner,
936 let self_recursive = match method {
937 Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
938 None => expr_refers_to_this_fn(cx, id, node_id),
941 self_call_spans.push(cx.tcx.hir.span(node_id));
942 // this is a self call, so we shouldn't explore past
943 // this node in the CFG.
948 // add the successors of this node to explore the graph further.
949 for (_, edge) in cfg.graph.outgoing_edges(idx) {
950 let target_idx = edge.target();
951 let target_cfg_id = target_idx.node_id();
952 if !visited.contains(&target_cfg_id) {
953 work_queue.push(target_idx)
958 // Check the number of self calls because a function that
959 // doesn't return (e.g. calls a `-> !` function or `loop { /*
960 // no break */ }`) shouldn't be linted unless it actually
962 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
963 let sp = cx.tcx.sess.source_map().def_span(sp);
964 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
966 "function cannot return without recurring");
967 db.span_label(sp, "cannot return without recurring");
968 // offer some help to the programmer.
969 for call in &self_call_spans {
970 db.span_label(*call, "recursive call site");
972 db.help("a `loop` may express intention better if this is on purpose");
979 // Functions for identifying if the given Expr NodeId `id`
980 // represents a call to the function `fn_id`/method `method`.
982 fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
983 match cx.tcx.hir.get(id) {
984 hir_map::NodeExpr(&hir::Expr { node: hir::ExprKind::Call(ref callee, _), .. }) => {
985 let def = if let hir::ExprKind::Path(ref qpath) = callee.node {
986 cx.tables.qpath_def(qpath, callee.hir_id)
991 Def::Local(..) | Def::Upvar(..) => false,
992 _ => def.def_id() == cx.tcx.hir.local_def_id(fn_id)
999 // Check if the expression `id` performs a call to `method`.
1000 fn expr_refers_to_this_method(cx: &LateContext,
1001 method: &ty::AssociatedItem,
1004 use rustc::ty::adjustment::*;
1006 // Ignore non-expressions.
1007 let expr = if let hir_map::NodeExpr(e) = cx.tcx.hir.get(id) {
1013 // Check for overloaded autoderef method calls.
1014 let mut source = cx.tables.expr_ty(expr);
1015 for adjustment in cx.tables.expr_adjustments(expr) {
1016 if let Adjust::Deref(Some(deref)) = adjustment.kind {
1017 let (def_id, substs) = deref.method_call(cx.tcx, source);
1018 if method_call_refers_to_method(cx, method, def_id, substs, id) {
1022 source = adjustment.target;
1025 // Check for method calls and overloaded operators.
1026 if cx.tables.is_method_call(expr) {
1027 let hir_id = cx.tcx.hir.definitions().node_to_hir_id(id);
1028 if let Some(def) = cx.tables.type_dependent_defs().get(hir_id) {
1029 let def_id = def.def_id();
1030 let substs = cx.tables.node_substs(hir_id);
1031 if method_call_refers_to_method(cx, method, def_id, substs, id) {
1035 cx.tcx.sess.delay_span_bug(expr.span,
1036 "no type-dependent def for method call");
1040 // Check for calls to methods via explicit paths (e.g. `T::method()`).
1042 hir::ExprKind::Call(ref callee, _) => {
1043 let def = if let hir::ExprKind::Path(ref qpath) = callee.node {
1044 cx.tables.qpath_def(qpath, callee.hir_id)
1049 Def::Method(def_id) => {
1050 let substs = cx.tables.node_substs(callee.hir_id);
1051 method_call_refers_to_method(cx, method, def_id, substs, id)
1060 // Check if the method call to the method with the ID `callee_id`
1061 // and instantiated with `callee_substs` refers to method `method`.
1062 fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
1063 method: &ty::AssociatedItem,
1065 callee_substs: &Substs<'tcx>,
1066 expr_id: ast::NodeId)
1069 let callee_item = tcx.associated_item(callee_id);
1071 match callee_item.container {
1072 // This is an inherent method, so the `def_id` refers
1073 // directly to the method definition.
1074 ty::ImplContainer(_) => callee_id == method.def_id,
1076 // A trait method, from any number of possible sources.
1077 // Attempt to select a concrete impl before checking.
1078 ty::TraitContainer(trait_def_id) => {
1079 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
1080 let trait_ref = ty::Binder::bind(trait_ref);
1081 let span = tcx.hir.span(expr_id);
1083 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
1085 trait_ref.to_poly_trait_predicate());
1087 tcx.infer_ctxt().enter(|infcx| {
1088 let mut selcx = traits::SelectionContext::new(&infcx);
1089 match selcx.select(&obligation) {
1090 // The method comes from a `T: Trait` bound.
1091 // If `T` is `Self`, then this call is inside
1092 // a default method definition.
1093 Ok(Some(traits::VtableParam(_))) => {
1094 let on_self = trait_ref.self_ty().is_self();
1095 // We can only be recurring in a default
1096 // method if we're being called literally
1097 // on the `Self` type.
1098 on_self && callee_id == method.def_id
1101 // The `impl` is known, so we check that with a
1103 Ok(Some(traits::VtableImpl(vtable_impl))) => {
1104 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1105 // It matches if it comes from the same impl,
1106 // and has the same method name.
1107 container == method.container &&
1108 callee_item.ident.name == method.ident.name
1111 // There's no way to know if this call is
1112 // recursive, so we assume it's not.
1125 "compiler plugin used as ordinary library in non-plugin crate"
1128 #[derive(Copy, Clone)]
1129 pub struct PluginAsLibrary;
1131 impl LintPass for PluginAsLibrary {
1132 fn get_lints(&self) -> LintArray {
1133 lint_array![PLUGIN_AS_LIBRARY]
1137 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1138 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1139 if cx.sess().plugin_registrar_fn.get().is_some() {
1140 // We're compiling a plugin; it's fine to link other plugins.
1145 hir::ItemKind::ExternCrate(..) => (),
1149 let def_id = cx.tcx.hir.local_def_id(it.id);
1150 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
1151 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
1153 // Probably means we aren't linking the crate for some reason.
1155 // Not sure if / when this could happen.
1161 cx.span_lint(PLUGIN_AS_LIBRARY,
1163 "compiler plugin used as an ordinary library");
1169 PRIVATE_NO_MANGLE_FNS,
1171 "functions marked #[no_mangle] should be exported"
1175 PRIVATE_NO_MANGLE_STATICS,
1177 "statics marked #[no_mangle] should be exported"
1181 NO_MANGLE_CONST_ITEMS,
1183 "const items will not have their symbols exported"
1187 NO_MANGLE_GENERIC_ITEMS,
1189 "generic items must be mangled"
1192 #[derive(Copy, Clone)]
1193 pub struct InvalidNoMangleItems;
1195 impl LintPass for InvalidNoMangleItems {
1196 fn get_lints(&self) -> LintArray {
1197 lint_array!(PRIVATE_NO_MANGLE_FNS,
1198 PRIVATE_NO_MANGLE_STATICS,
1199 NO_MANGLE_CONST_ITEMS,
1200 NO_MANGLE_GENERIC_ITEMS)
1204 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1205 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1206 let suggest_export = |vis: &hir::Visibility, err: &mut DiagnosticBuilder| {
1207 let suggestion = match vis.node {
1208 hir::VisibilityKind::Inherited => {
1209 // inherited visibility is empty span at item start; need an extra space
1210 Some("pub ".to_owned())
1212 hir::VisibilityKind::Restricted { .. } |
1213 hir::VisibilityKind::Crate(_) => {
1214 Some("pub".to_owned())
1216 hir::VisibilityKind::Public => {
1217 err.help("try exporting the item with a `pub use` statement");
1221 if let Some(replacement) = suggestion {
1222 err.span_suggestion_with_applicability(
1224 "try making it public",
1226 Applicability::MachineApplicable
1232 hir::ItemKind::Fn(.., ref generics, _) => {
1233 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
1234 if attr::contains_name(&it.attrs, "linkage") {
1237 if !cx.access_levels.is_reachable(it.id) {
1238 let msg = "function is marked #[no_mangle], but not exported";
1239 let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg);
1240 suggest_export(&it.vis, &mut err);
1243 for param in &generics.params {
1245 GenericParamKind::Lifetime { .. } => {}
1246 GenericParamKind::Type { .. } => {
1247 let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
1249 "functions generic over \
1250 types must be mangled");
1251 err.span_suggestion_short_with_applicability(
1252 no_mangle_attr.span,
1253 "remove this attribute",
1255 // Use of `#[no_mangle]` suggests FFI intent; correct
1256 // fix may be to monomorphize source by hand
1257 Applicability::MaybeIncorrect
1266 hir::ItemKind::Static(..) => {
1267 if attr::contains_name(&it.attrs, "no_mangle") &&
1268 !cx.access_levels.is_reachable(it.id) {
1269 let msg = "static is marked #[no_mangle], but not exported";
1270 let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, msg);
1271 suggest_export(&it.vis, &mut err);
1275 hir::ItemKind::Const(..) => {
1276 if attr::contains_name(&it.attrs, "no_mangle") {
1277 // Const items do not refer to a particular location in memory, and therefore
1278 // don't have anything to attach a symbol to
1279 let msg = "const items should never be #[no_mangle]";
1280 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1282 // account for "pub const" (#45562)
1283 let start = cx.tcx.sess.source_map().span_to_snippet(it.span)
1284 .map(|snippet| snippet.find("const").unwrap_or(0))
1285 .unwrap_or(0) as u32;
1286 // `const` is 5 chars
1287 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
1288 err.span_suggestion_with_applicability(
1290 "try a static value",
1291 "pub static".to_owned(),
1292 Applicability::MachineApplicable
1302 #[derive(Clone, Copy)]
1303 pub struct MutableTransmutes;
1308 "mutating transmuted &mut T from &T may cause undefined behavior"
1311 impl LintPass for MutableTransmutes {
1312 fn get_lints(&self) -> LintArray {
1313 lint_array!(MUTABLE_TRANSMUTES)
1317 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1318 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1319 use rustc_target::spec::abi::Abi::RustIntrinsic;
1321 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1322 consider instead using an UnsafeCell";
1323 match get_transmute_from_to(cx, expr) {
1324 Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
1325 if to_mt == hir::Mutability::MutMutable &&
1326 from_mt == hir::Mutability::MutImmutable {
1327 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1333 fn get_transmute_from_to<'a, 'tcx>
1334 (cx: &LateContext<'a, 'tcx>,
1336 -> Option<(&'tcx ty::TyKind<'tcx>, &'tcx ty::TyKind<'tcx>)> {
1337 let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
1338 cx.tables.qpath_def(qpath, expr.hir_id)
1342 if let Def::Fn(did) = def {
1343 if !def_id_is_transmute(cx, did) {
1346 let sig = cx.tables.node_id_to_type(expr.hir_id).fn_sig(cx.tcx);
1347 let from = sig.inputs().skip_binder()[0];
1348 let to = *sig.output().skip_binder();
1349 return Some((&from.sty, &to.sty));
1354 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1355 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1356 cx.tcx.item_name(def_id) == "transmute"
1361 /// Forbids using the `#[feature(...)]` attribute
1362 #[derive(Copy, Clone)]
1363 pub struct UnstableFeatures;
1368 "enabling unstable features (deprecated. do not use)"
1371 impl LintPass for UnstableFeatures {
1372 fn get_lints(&self) -> LintArray {
1373 lint_array!(UNSTABLE_FEATURES)
1377 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1378 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1379 if attr.check_name("feature") {
1380 if let Some(items) = attr.meta_item_list() {
1382 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1389 /// Lint for unions that contain fields with possibly non-trivial destructors.
1390 pub struct UnionsWithDropFields;
1393 UNIONS_WITH_DROP_FIELDS,
1395 "use of unions that contain fields with possibly non-trivial drop code"
1398 impl LintPass for UnionsWithDropFields {
1399 fn get_lints(&self) -> LintArray {
1400 lint_array!(UNIONS_WITH_DROP_FIELDS)
1404 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1405 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1406 if let hir::ItemKind::Union(ref vdata, _) = item.node {
1407 for field in vdata.fields() {
1408 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1409 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1410 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1412 "union contains a field with possibly non-trivial drop code, \
1413 drop code of union fields is ignored when dropping the union");
1421 /// Lint for items marked `pub` that aren't reachable from other crates
1422 pub struct UnreachablePub;
1425 pub UNREACHABLE_PUB,
1427 "`pub` items not reachable from crate root"
1430 impl LintPass for UnreachablePub {
1431 fn get_lints(&self) -> LintArray {
1432 lint_array!(UNREACHABLE_PUB)
1436 impl UnreachablePub {
1437 fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId,
1438 vis: &hir::Visibility, span: Span, exportable: bool) {
1439 let mut applicability = Applicability::MachineApplicable;
1441 hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
1442 if span.ctxt().outer().expn_info().is_some() {
1443 applicability = Applicability::MaybeIncorrect;
1445 let def_span = cx.tcx.sess.source_map().def_span(span);
1446 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1447 &format!("unreachable `pub` {}", what));
1448 let replacement = if cx.tcx.features().crate_visibility_modifier {
1454 err.span_suggestion_with_applicability(vis.span,
1455 "consider restricting its visibility",
1459 err.help("or consider exporting it for use by other crates");
1469 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1470 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1471 self.perform_lint(cx, "item", item.id, &item.vis, item.span, true);
1474 fn check_foreign_item(&mut self, cx: &LateContext, foreign_item: &hir::ForeignItem) {
1475 self.perform_lint(cx, "item", foreign_item.id, &foreign_item.vis,
1476 foreign_item.span, true);
1479 fn check_struct_field(&mut self, cx: &LateContext, field: &hir::StructField) {
1480 self.perform_lint(cx, "field", field.id, &field.vis, field.span, false);
1483 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
1484 self.perform_lint(cx, "item", impl_item.id, &impl_item.vis, impl_item.span, false);
1488 /// Lint for trait and lifetime bounds in type aliases being mostly ignored:
1489 /// They are relevant when using associated types, but otherwise neither checked
1490 /// at definition site nor enforced at use site.
1492 pub struct TypeAliasBounds;
1497 "bounds in type aliases are not enforced"
1500 impl LintPass for TypeAliasBounds {
1501 fn get_lints(&self) -> LintArray {
1502 lint_array!(TYPE_ALIAS_BOUNDS)
1506 impl TypeAliasBounds {
1507 fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1509 hir::QPath::TypeRelative(ref ty, _) => {
1510 // If this is a type variable, we found a `T::Assoc`.
1512 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1514 Def::TyParam(_) => true,
1521 hir::QPath::Resolved(..) => false,
1525 fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder) {
1526 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1527 // bound. Let's see if this type does that.
1529 // We use a HIR visitor to walk the type.
1530 use rustc::hir::intravisit::{self, Visitor};
1531 struct WalkAssocTypes<'a, 'db> where 'db: 'a {
1532 err: &'a mut DiagnosticBuilder<'db>
1534 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1535 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1537 intravisit::NestedVisitorMap::None
1540 fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: hir::HirId, span: Span) {
1541 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1542 self.err.span_help(span,
1543 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1544 associated types in type aliases");
1546 intravisit::walk_qpath(self, qpath, id, span)
1550 // Let's go for a walk!
1551 let mut visitor = WalkAssocTypes { err };
1552 visitor.visit_ty(ty);
1556 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1557 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1558 let (ty, type_alias_generics) = match item.node {
1559 hir::ItemKind::Ty(ref ty, ref generics) => (&*ty, generics),
1562 let mut suggested_changing_assoc_types = false;
1563 // There must not be a where clause
1564 if !type_alias_generics.where_clause.predicates.is_empty() {
1565 let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1566 .map(|pred| pred.span()).collect();
1567 let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1568 "where clauses are not enforced in type aliases");
1569 err.help("the clause will not be checked when the type alias is used, \
1570 and should be removed");
1571 if !suggested_changing_assoc_types {
1572 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1573 suggested_changing_assoc_types = true;
1577 // The parameters must not have bounds
1578 for param in type_alias_generics.params.iter() {
1579 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1580 if !spans.is_empty() {
1581 let mut err = cx.struct_span_lint(
1584 "bounds on generic parameters are not enforced in type aliases",
1586 err.help("the bound will not be checked when the type alias is used, \
1587 and should be removed");
1588 if !suggested_changing_assoc_types {
1589 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1590 suggested_changing_assoc_types = true;
1598 /// Lint constants that are erroneous.
1599 /// Without this lint, we might not get any diagnostic if the constant is
1600 /// unused within this crate, even though downstream crates can't use it
1601 /// without producing an error.
1602 pub struct UnusedBrokenConst;
1604 impl LintPass for UnusedBrokenConst {
1605 fn get_lints(&self) -> LintArray {
1610 fn validate_const<'a, 'tcx>(
1611 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1612 constant: &ty::Const<'tcx>,
1613 param_env: ty::ParamEnv<'tcx>,
1614 gid: ::rustc::mir::interpret::GlobalId<'tcx>,
1617 let mut ecx = ::rustc_mir::interpret::mk_eval_cx(tcx, gid.instance, param_env).unwrap();
1619 use rustc_target::abi::LayoutOf;
1620 use rustc_mir::interpret::OpTy;
1622 let op = ecx.const_value_to_op(constant.val)?;
1623 let layout = ecx.layout_of(constant.ty)?;
1624 let place = ecx.allocate_op(OpTy { op, layout })?.into();
1626 let mut todo = vec![(place, Vec::new())];
1627 let mut seen = FxHashSet();
1629 while let Some((place, mut path)) = todo.pop() {
1630 ecx.validate_mplace(
1639 if let Err(err) = result {
1640 let (trace, span) = ecx.generate_stacktrace(None);
1641 let err = ::rustc::mir::interpret::ConstEvalErr {
1646 let err = err.struct_error(
1648 &format!("this {} likely exhibits undefined behavior", what),
1650 if let Some(mut err) = err {
1651 err.note("The rules on what exactly is undefined behavior aren't clear, \
1652 so this check might be overzealous. Please open an issue on the rust compiler \
1653 repository if you believe it should not be considered undefined behavior",
1660 fn check_const(cx: &LateContext, body_id: hir::BodyId, what: &str) {
1661 let def_id = cx.tcx.hir.body_owner_def_id(body_id);
1662 let is_static = cx.tcx.is_static(def_id).is_some();
1663 let param_env = if is_static {
1664 // Use the same param_env as `codegen_static_initializer`, to reuse the cache.
1665 ty::ParamEnv::reveal_all()
1667 cx.tcx.param_env(def_id)
1669 let cid = ::rustc::mir::interpret::GlobalId {
1670 instance: ty::Instance::mono(cx.tcx, def_id),
1673 match cx.tcx.const_eval(param_env.and(cid)) {
1674 Ok(val) => validate_const(cx.tcx, val, param_env, cid, what),
1676 // errors for statics are already reported directly in the query, avoid duplicates
1678 let span = cx.tcx.def_span(def_id);
1681 &format!("this {} cannot be used", what),
1682 cx.current_lint_root(),
1689 struct UnusedBrokenConstVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
1691 impl<'a, 'tcx, 'v> hir::intravisit::Visitor<'v> for UnusedBrokenConstVisitor<'a, 'tcx> {
1692 fn visit_nested_body(&mut self, id: hir::BodyId) {
1693 check_const(self.0, id, "array length");
1695 fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'v> {
1696 hir::intravisit::NestedVisitorMap::None
1700 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1701 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1703 hir::ItemKind::Const(_, body_id) => {
1704 check_const(cx, body_id, "constant");
1706 hir::ItemKind::Static(_, _, body_id) => {
1707 check_const(cx, body_id, "static");
1709 hir::ItemKind::Ty(ref ty, _) => hir::intravisit::walk_ty(
1710 &mut UnusedBrokenConstVisitor(cx),
1718 /// Lint for trait and lifetime bounds that don't depend on type parameters
1719 /// which either do nothing, or stop the item from being used.
1720 pub struct TrivialConstraints;
1725 "these bounds don't depend on an type parameters"
1728 impl LintPass for TrivialConstraints {
1729 fn get_lints(&self) -> LintArray {
1730 lint_array!(TRIVIAL_BOUNDS)
1734 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1737 cx: &LateContext<'a, 'tcx>,
1738 item: &'tcx hir::Item,
1740 use rustc::ty::fold::TypeFoldable;
1741 use rustc::ty::Predicate::*;
1744 if cx.tcx.features().trivial_bounds {
1745 let def_id = cx.tcx.hir.local_def_id(item.id);
1746 let predicates = cx.tcx.predicates_of(def_id);
1747 for predicate in &predicates.predicates {
1748 let predicate_kind_name = match *predicate {
1749 Trait(..) => "Trait",
1751 RegionOutlives(..) => "Lifetime",
1753 // Ignore projections, as they can only be global
1754 // if the trait bound is global
1756 // Ignore bounds that a user can't type
1761 ConstEvaluatable(..) => continue,
1763 if predicate.is_global() {
1767 &format!("{} bound {} does not depend on any type \
1768 or lifetime parameters", predicate_kind_name, predicate),
1777 /// Does nothing as a lint pass, but registers some `Lint`s
1778 /// which are used by other parts of the compiler.
1779 #[derive(Copy, Clone)]
1780 pub struct SoftLints;
1782 impl LintPass for SoftLints {
1783 fn get_lints(&self) -> LintArray {
1787 NON_SHORTHAND_FIELD_PATTERNS,
1790 MISSING_COPY_IMPLEMENTATIONS,
1791 MISSING_DEBUG_IMPLEMENTATIONS,
1792 ANONYMOUS_PARAMETERS,
1793 UNUSED_DOC_COMMENTS,
1794 UNCONDITIONAL_RECURSION,
1796 PRIVATE_NO_MANGLE_FNS,
1797 PRIVATE_NO_MANGLE_STATICS,
1798 NO_MANGLE_CONST_ITEMS,
1799 NO_MANGLE_GENERIC_ITEMS,
1802 UNIONS_WITH_DROP_FIELDS,
1811 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1813 "`...` range patterns are deprecated"
1817 pub struct EllipsisInclusiveRangePatterns;
1819 impl LintPass for EllipsisInclusiveRangePatterns {
1820 fn get_lints(&self) -> LintArray {
1821 lint_array!(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS)
1825 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1826 fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
1827 use self::ast::{PatKind, RangeEnd, RangeSyntax};
1829 if let PatKind::Range(
1830 _, _, Spanned { span, node: RangeEnd::Included(RangeSyntax::DotDotDot) }
1832 let msg = "`...` range patterns are deprecated";
1833 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, span, msg);
1834 err.span_suggestion_short_with_applicability(
1835 span, "use `..=` for an inclusive range", "..=".to_owned(),
1836 // FIXME: outstanding problem with precedence in ref patterns:
1837 // https://github.com/rust-lang/rust/issues/51043#issuecomment-392252285
1838 Applicability::MaybeIncorrect
1846 UNNAMEABLE_TEST_FUNCTIONS,
1848 "detects an function that cannot be named being marked as #[test]"
1851 pub struct UnnameableTestFunctions;
1853 impl LintPass for UnnameableTestFunctions {
1854 fn get_lints(&self) -> LintArray {
1855 lint_array!(UNNAMEABLE_TEST_FUNCTIONS)
1859 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestFunctions {
1860 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1862 hir::ItemKind::Fn(..) => {
1863 for attr in &it.attrs {
1864 if attr.name() == "test" {
1865 let parent = cx.tcx.hir.get_parent(it.id);
1866 match cx.tcx.hir.find(parent) {
1867 Some(hir_map::NodeItem(hir::Item {node: hir::ItemKind::Mod(_), ..})) |
1870 cx.struct_span_lint(
1871 UNNAMEABLE_TEST_FUNCTIONS,
1873 "cannot test inner function",
1889 "detects `async` being used as an identifier"
1892 /// Checks for uses of `async` as an identifier
1894 pub struct Async2018;
1896 impl LintPass for Async2018 {
1897 fn get_lints(&self) -> LintArray {
1898 lint_array!(ASYNC_IDENTS)
1903 fn check_tokens(&mut self, cx: &EarlyContext, tokens: TokenStream) {
1904 for tt in tokens.into_trees() {
1906 TokenTree::Token(span, tok) => match tok.ident() {
1907 // only report non-raw idents
1908 Some((ident, false)) if ident.as_str() == "async" => {
1909 self.report(cx, span.substitute_dummy(ident.span))
1913 TokenTree::Delimited(_, ref delim) => {
1914 self.check_tokens(cx, delim.tts.clone().into())
1919 fn report(&mut self, cx: &EarlyContext, span: Span) {
1920 // don't lint `r#async`
1921 if cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&span) {
1924 let mut lint = cx.struct_span_lint(
1927 "`async` is a keyword in the 2018 edition",
1930 // Don't suggest about raw identifiers if the feature isn't active
1931 lint.span_suggestion_with_applicability(
1933 "you can use a raw identifier to stay compatible",
1934 "r#async".to_string(),
1935 Applicability::MachineApplicable,
1941 impl EarlyLintPass for Async2018 {
1942 fn check_mac_def(&mut self, cx: &EarlyContext, mac_def: &ast::MacroDef, _id: ast::NodeId) {
1943 self.check_tokens(cx, mac_def.stream());
1945 fn check_mac(&mut self, cx: &EarlyContext, mac: &ast::Mac) {
1946 self.check_tokens(cx, mac.node.tts.clone().into());
1948 fn check_ident(&mut self, cx: &EarlyContext, ident: ast::Ident) {
1949 if ident.as_str() == "async" {
1950 self.report(cx, ident.span);