1 //! Lints in the Rust compiler.
3 //! This contains lints which can feasibly be implemented as their own
4 //! AST visitor. Also see `rustc::lint::builtin`, which contains the
5 //! definitions of lints that are emitted directly inside the main
8 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
9 //! Then add code to emit the new lint in the appropriate circumstances.
10 //! You can do that in an existing `LintPass` if it makes sense, or in a
11 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
12 //! compiler. Only do the latter if the check can't be written cleanly as a
13 //! `LintPass` (also, note that such lints will need to be defined in
14 //! `rustc::lint::builtin`, not here).
16 //! If you define a new `EarlyLintPass`, you will also need to add it to the
17 //! `add_early_builtin!` or `add_early_builtin_with_new!` invocation in
18 //! `lib.rs`. Use the former for unit-like structs and the latter for structs
19 //! with a `pub fn new()`.
21 //! If you define a new `LateLintPass`, you will also need to add it to the
22 //! `late_lint_methods!` invocation in `lib.rs`.
26 use lint::{EarlyContext, EarlyLintPass, LateLintPass, LintPass};
27 use lint::{LateContext, LintArray, LintContext};
28 use rustc::hir::map::Map;
30 use rustc::lint::FutureIncompatibleInfo;
31 use rustc::traits::misc::can_type_implement_copy;
32 use rustc::ty::{self, layout::VariantIdx, Ty, TyCtxt};
33 use rustc_data_structures::fx::FxHashSet;
34 use rustc_errors::{Applicability, DiagnosticBuilder};
35 use rustc_feature::Stability;
36 use rustc_feature::{deprecated_attributes, AttributeGate, AttributeTemplate, AttributeType};
38 use rustc_hir::def::{DefKind, Res};
39 use rustc_hir::def_id::DefId;
40 use rustc_hir::{GenericParamKind, PatKind};
41 use rustc_hir::{HirIdSet, Node};
42 use rustc_span::edition::Edition;
43 use rustc_span::source_map::Spanned;
44 use rustc_span::symbol::{kw, sym, Symbol};
45 use rustc_span::{BytePos, Span};
46 use syntax::ast::{self, Expr};
47 use syntax::attr::{self, HasAttrs};
48 use syntax::print::pprust::{self, expr_to_string};
50 use syntax::tokenstream::{TokenStream, TokenTree};
51 use syntax::visit::FnKind;
53 use crate::nonstandard_style::{method_context, MethodLateContext};
57 // hardwired lints from librustc
58 pub use lint::builtin::*;
63 "suggest using `loop { }` instead of `while true { }`"
66 declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
68 /// Traverse through any amount of parenthesis and return the first non-parens expression.
69 fn pierce_parens(mut expr: &ast::Expr) -> &ast::Expr {
70 while let ast::ExprKind::Paren(sub) = &expr.kind {
76 impl EarlyLintPass for WhileTrue {
77 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
78 if let ast::ExprKind::While(cond, ..) = &e.kind {
79 if let ast::ExprKind::Lit(ref lit) = pierce_parens(cond).kind {
80 if let ast::LitKind::Bool(true) = lit.kind {
81 if !lit.span.from_expansion() {
82 let msg = "denote infinite loops with `loop { ... }`";
83 let condition_span = cx.sess.source_map().def_span(e.span);
84 cx.struct_span_lint(WHILE_TRUE, condition_span, msg)
85 .span_suggestion_short(
89 Applicability::MachineApplicable,
102 "use of owned (Box type) heap memory"
105 declare_lint_pass!(BoxPointers => [BOX_POINTERS]);
108 fn check_heap_type(&self, cx: &LateContext<'_, '_>, span: Span, ty: Ty<'_>) {
109 for leaf_ty in ty.walk() {
110 if leaf_ty.is_box() {
111 let m = format!("type uses owned (Box type) pointers: {}", ty);
112 cx.span_lint(BOX_POINTERS, span, &m);
118 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
119 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
121 hir::ItemKind::Fn(..)
122 | hir::ItemKind::TyAlias(..)
123 | hir::ItemKind::Enum(..)
124 | hir::ItemKind::Struct(..)
125 | hir::ItemKind::Union(..) => {
126 let def_id = cx.tcx.hir().local_def_id(it.hir_id);
127 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
132 // If it's a struct, we also have to check the fields' types
134 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
135 for struct_field in struct_def.fields() {
136 let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id);
137 self.check_heap_type(cx, struct_field.span, cx.tcx.type_of(def_id));
144 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
145 let ty = cx.tables.node_type(e.hir_id);
146 self.check_heap_type(cx, e.span, ty);
151 NON_SHORTHAND_FIELD_PATTERNS,
153 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
156 declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
158 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
159 fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>) {
160 if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
165 .expect("struct pattern type is not an ADT")
166 .variant_of_res(cx.tables.qpath_res(qpath, pat.hir_id));
167 for fieldpat in field_pats {
168 if fieldpat.is_shorthand {
171 if fieldpat.span.from_expansion() {
172 // Don't lint if this is a macro expansion: macro authors
173 // shouldn't have to worry about this kind of style issue
177 if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind {
178 if cx.tcx.find_field_index(ident, &variant)
179 == Some(cx.tcx.field_index(fieldpat.hir_id, cx.tables))
181 let mut err = cx.struct_span_lint(
182 NON_SHORTHAND_FIELD_PATTERNS,
184 &format!("the `{}:` in this pattern is redundant", ident),
186 let binding = match binding_annot {
187 hir::BindingAnnotation::Unannotated => None,
188 hir::BindingAnnotation::Mutable => Some("mut"),
189 hir::BindingAnnotation::Ref => Some("ref"),
190 hir::BindingAnnotation::RefMut => Some("ref mut"),
192 let ident = if let Some(binding) = binding {
193 format!("{} {}", binding, ident)
199 "use shorthand field pattern",
201 Applicability::MachineApplicable,
214 "usage of `unsafe` code"
217 declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
220 fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) {
221 // This comes from a macro that has `#[allow_internal_unsafe]`.
222 if span.allows_unsafe() {
226 cx.span_lint(UNSAFE_CODE, span, desc);
230 impl EarlyLintPass for UnsafeCode {
231 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
232 if attr.check_name(sym::allow_internal_unsafe) {
236 "`allow_internal_unsafe` allows defining \
237 macros using unsafe without triggering \
238 the `unsafe_code` lint at their call site",
243 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
244 if let ast::ExprKind::Block(ref blk, _) = e.kind {
245 // Don't warn about generated blocks; that'll just pollute the output.
246 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
247 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
252 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
254 ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => {
255 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
258 ast::ItemKind::Impl(ast::Unsafety::Unsafe, ..) => {
259 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
268 cx: &EarlyContext<'_>,
275 FnKind::ItemFn(_, ast::FnHeader { unsafety: ast::Unsafety::Unsafe, .. }, ..) => {
276 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
279 FnKind::Method(_, sig, ..) => {
280 if sig.header.unsafety == ast::Unsafety::Unsafe {
281 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
289 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, item: &ast::AssocItem) {
290 if let ast::AssocItemKind::Fn(ref sig, None) = item.kind {
291 if sig.header.unsafety == ast::Unsafety::Unsafe {
292 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
301 "detects missing documentation for public members",
302 report_in_external_macro
305 pub struct MissingDoc {
306 /// Stack of whether `#[doc(hidden)]` is set at each level which has lint attributes.
307 doc_hidden_stack: Vec<bool>,
309 /// Private traits or trait items that leaked through. Don't check their methods.
310 private_traits: FxHashSet<hir::HirId>,
313 impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
315 fn has_doc(attr: &ast::Attribute) -> bool {
316 if attr.is_doc_comment() {
320 if !attr.check_name(sym::doc) {
324 if attr.is_value_str() {
328 if let Some(list) = attr.meta_item_list() {
330 if meta.check_name(sym::include) || meta.check_name(sym::hidden) {
340 pub fn new() -> MissingDoc {
341 MissingDoc { doc_hidden_stack: vec![false], private_traits: FxHashSet::default() }
344 fn doc_hidden(&self) -> bool {
345 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
348 fn check_missing_docs_attrs(
350 cx: &LateContext<'_, '_>,
351 id: Option<hir::HirId>,
352 attrs: &[ast::Attribute],
356 // If we're building a test harness, then warning about
357 // documentation is probably not really relevant right now.
358 if cx.sess().opts.test {
362 // `#[doc(hidden)]` disables missing_docs check.
363 if self.doc_hidden() {
367 // Only check publicly-visible items, using the result from the privacy pass.
368 // It's an option so the crate root can also use this function (it doesn't
370 if let Some(id) = id {
371 if !cx.access_levels.is_exported(id) {
376 let has_doc = attrs.iter().any(|a| has_doc(a));
380 cx.tcx.sess.source_map().def_span(sp),
381 &format!("missing documentation for {}", desc),
387 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
388 fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) {
389 let doc_hidden = self.doc_hidden()
390 || attrs.iter().any(|attr| {
391 attr.check_name(sym::doc)
392 && match attr.meta_item_list() {
394 Some(l) => attr::list_contains_name(&l, sym::hidden),
397 self.doc_hidden_stack.push(doc_hidden);
400 fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) {
401 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
404 fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate<'_>) {
405 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
407 for macro_def in krate.exported_macros {
408 let has_doc = macro_def.attrs.iter().any(|a| has_doc(a));
412 cx.tcx.sess.source_map().def_span(macro_def.span),
413 "missing documentation for macro",
419 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
420 let desc = match it.kind {
421 hir::ItemKind::Fn(..) => "a function",
422 hir::ItemKind::Mod(..) => "a module",
423 hir::ItemKind::Enum(..) => "an enum",
424 hir::ItemKind::Struct(..) => "a struct",
425 hir::ItemKind::Union(..) => "a union",
426 hir::ItemKind::Trait(.., trait_item_refs) => {
427 // Issue #11592: traits are always considered exported, even when private.
428 if let hir::VisibilityKind::Inherited = it.vis.node {
429 self.private_traits.insert(it.hir_id);
430 for trait_item_ref in trait_item_refs {
431 self.private_traits.insert(trait_item_ref.id.hir_id);
437 hir::ItemKind::TyAlias(..) => "a type alias",
438 hir::ItemKind::Impl(.., Some(ref trait_ref), _, impl_item_refs) => {
439 // If the trait is private, add the impl items to `private_traits` so they don't get
440 // reported for missing docs.
441 let real_trait = trait_ref.path.res.def_id();
442 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(real_trait) {
443 match cx.tcx.hir().find(hir_id) {
444 Some(Node::Item(item)) => {
445 if let hir::VisibilityKind::Inherited = item.vis.node {
446 for impl_item_ref in impl_item_refs {
447 self.private_traits.insert(impl_item_ref.id.hir_id);
456 hir::ItemKind::Const(..) => "a constant",
457 hir::ItemKind::Static(..) => "a static",
461 self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, desc);
464 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem<'_>) {
465 if self.private_traits.contains(&trait_item.hir_id) {
469 let desc = match trait_item.kind {
470 hir::TraitItemKind::Const(..) => "an associated constant",
471 hir::TraitItemKind::Method(..) => "a trait method",
472 hir::TraitItemKind::Type(..) => "an associated type",
475 self.check_missing_docs_attrs(
477 Some(trait_item.hir_id),
484 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem<'_>) {
485 // If the method is an impl for a trait, don't doc.
486 if method_context(cx, impl_item.hir_id) == MethodLateContext::TraitImpl {
490 let desc = match impl_item.kind {
491 hir::ImplItemKind::Const(..) => "an associated constant",
492 hir::ImplItemKind::Method(..) => "a method",
493 hir::ImplItemKind::TyAlias(_) => "an associated type",
494 hir::ImplItemKind::OpaqueTy(_) => "an associated `impl Trait` type",
496 self.check_missing_docs_attrs(
498 Some(impl_item.hir_id),
505 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField<'_>) {
506 if !sf.is_positional() {
507 self.check_missing_docs_attrs(cx, Some(sf.hir_id), &sf.attrs, sf.span, "a struct field")
511 fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant<'_>) {
512 self.check_missing_docs_attrs(cx, Some(v.id), &v.attrs, v.span, "a variant");
517 pub MISSING_COPY_IMPLEMENTATIONS,
519 "detects potentially-forgotten implementations of `Copy`"
522 declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
524 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
525 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
526 if !cx.access_levels.is_reachable(item.hir_id) {
529 let (def, ty) = match item.kind {
530 hir::ItemKind::Struct(_, ref ast_generics) => {
531 if !ast_generics.params.is_empty() {
534 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
535 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
537 hir::ItemKind::Union(_, ref ast_generics) => {
538 if !ast_generics.params.is_empty() {
541 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
542 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
544 hir::ItemKind::Enum(_, ref ast_generics) => {
545 if !ast_generics.params.is_empty() {
548 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
549 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
553 if def.has_dtor(cx.tcx) {
556 let param_env = ty::ParamEnv::empty();
557 if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span) {
560 if can_type_implement_copy(cx.tcx, param_env, ty).is_ok() {
562 MISSING_COPY_IMPLEMENTATIONS,
564 "type could implement `Copy`; consider adding `impl \
572 MISSING_DEBUG_IMPLEMENTATIONS,
574 "detects missing implementations of fmt::Debug"
578 pub struct MissingDebugImplementations {
579 impling_types: Option<HirIdSet>,
582 impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
584 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
585 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
586 if !cx.access_levels.is_reachable(item.hir_id) {
591 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {}
595 let debug = match cx.tcx.get_diagnostic_item(sym::debug_trait) {
596 Some(debug) => debug,
600 if self.impling_types.is_none() {
601 let mut impls = HirIdSet::default();
602 cx.tcx.for_each_impl(debug, |d| {
603 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
604 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
605 impls.insert(hir_id);
610 self.impling_types = Some(impls);
611 debug!("{:?}", self.impling_types);
614 if !self.impling_types.as_ref().unwrap().contains(&item.hir_id) {
616 MISSING_DEBUG_IMPLEMENTATIONS,
618 "type does not implement `fmt::Debug`; consider adding `#[derive(Debug)]` \
619 or a manual implementation",
626 pub ANONYMOUS_PARAMETERS,
628 "detects anonymous parameters",
629 @future_incompatible = FutureIncompatibleInfo {
630 reference: "issue #41686 <https://github.com/rust-lang/rust/issues/41686>",
631 edition: Some(Edition::Edition2018),
636 /// Checks for use of anonymous parameters (RFC 1685).
637 AnonymousParameters => [ANONYMOUS_PARAMETERS]
640 impl EarlyLintPass for AnonymousParameters {
641 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
643 ast::AssocItemKind::Fn(ref sig, _) => {
644 for arg in sig.decl.inputs.iter() {
646 ast::PatKind::Ident(_, ident, None) => {
647 if ident.name == kw::Invalid {
648 let ty_snip = cx.sess.source_map().span_to_snippet(arg.ty.span);
650 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
651 (snip, Applicability::MachineApplicable)
653 ("<type>".to_owned(), Applicability::HasPlaceholders)
657 ANONYMOUS_PARAMETERS,
659 "anonymous parameters are deprecated and will be \
660 removed in the next edition.",
664 "Try naming the parameter or explicitly \
666 format!("_: {}", ty_snip),
681 /// Check for use of attributes which have been deprecated.
683 pub struct DeprecatedAttr {
684 // This is not free to compute, so we want to keep it around, rather than
685 // compute it for every attribute.
686 depr_attrs: Vec<&'static (Symbol, AttributeType, AttributeTemplate, AttributeGate)>,
689 impl_lint_pass!(DeprecatedAttr => []);
691 impl DeprecatedAttr {
692 pub fn new() -> DeprecatedAttr {
693 DeprecatedAttr { depr_attrs: deprecated_attributes() }
697 fn lint_deprecated_attr(
698 cx: &EarlyContext<'_>,
699 attr: &ast::Attribute,
701 suggestion: Option<&str>,
703 cx.struct_span_lint(DEPRECATED, attr.span, &msg)
704 .span_suggestion_short(
706 suggestion.unwrap_or("remove this attribute"),
708 Applicability::MachineApplicable,
713 impl EarlyLintPass for DeprecatedAttr {
714 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
715 for &&(n, _, _, ref g) in &self.depr_attrs {
716 if attr.ident().map(|ident| ident.name) == Some(n) {
717 if let &AttributeGate::Gated(
718 Stability::Deprecated(link, suggestion),
725 format!("use of deprecated attribute `{}`: {}. See {}", name, reason, link);
726 lint_deprecated_attr(cx, attr, &msg, suggestion);
731 if attr.check_name(sym::no_start) || attr.check_name(sym::crate_id) {
732 let path_str = pprust::path_to_string(&attr.get_normal_item().path);
733 let msg = format!("use of deprecated attribute `{}`: no longer used.", path_str);
734 lint_deprecated_attr(cx, attr, &msg, None);
740 pub UNUSED_DOC_COMMENTS,
742 "detects doc comments that aren't used by rustdoc"
745 declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]);
747 impl UnusedDocComment {
750 cx: &EarlyContext<'_>,
753 is_macro_expansion: bool,
754 attrs: &[ast::Attribute],
756 let mut attrs = attrs.into_iter().peekable();
758 // Accumulate a single span for sugared doc comments.
759 let mut sugared_span: Option<Span> = None;
761 while let Some(attr) = attrs.next() {
762 if attr.is_doc_comment() {
764 sugared_span.map_or_else(|| attr.span, |span| span.with_hi(attr.span.hi())),
768 if attrs.peek().map(|next_attr| next_attr.is_doc_comment()).unwrap_or_default() {
772 let span = sugared_span.take().unwrap_or_else(|| attr.span);
774 if attr.is_doc_comment() || attr.check_name(sym::doc) {
775 let mut err = cx.struct_span_lint(UNUSED_DOC_COMMENTS, span, "unused doc comment");
779 format!("rustdoc does not generate documentation for {}", node_kind),
782 if is_macro_expansion {
784 "to document an item produced by a macro, \
785 the macro must produce the documentation as part of its expansion",
795 impl EarlyLintPass for UnusedDocComment {
796 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
797 if let ast::ItemKind::Mac(..) = item.kind {
798 self.warn_if_doc(cx, item.span, "macro expansions", true, &item.attrs);
802 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
803 let (kind, is_macro_expansion) = match stmt.kind {
804 ast::StmtKind::Local(..) => ("statements", false),
805 ast::StmtKind::Item(..) => ("inner items", false),
806 ast::StmtKind::Mac(..) => ("macro expansions", true),
807 // expressions will be reported by `check_expr`.
808 ast::StmtKind::Semi(..) | ast::StmtKind::Expr(..) => return,
811 self.warn_if_doc(cx, stmt.span, kind, is_macro_expansion, stmt.kind.attrs());
814 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
815 let arm_span = arm.pat.span.with_hi(arm.body.span.hi());
816 self.warn_if_doc(cx, arm_span, "match arms", false, &arm.attrs);
819 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
820 self.warn_if_doc(cx, expr.span, "expressions", false, &expr.attrs);
825 NO_MANGLE_CONST_ITEMS,
827 "const items will not have their symbols exported"
831 NO_MANGLE_GENERIC_ITEMS,
833 "generic items must be mangled"
836 declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
838 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
839 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
841 hir::ItemKind::Fn(.., ref generics, _) => {
842 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
843 for param in generics.params {
845 GenericParamKind::Lifetime { .. } => {}
846 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
847 let mut err = cx.struct_span_lint(
848 NO_MANGLE_GENERIC_ITEMS,
850 "functions generic over types or consts must be mangled",
852 err.span_suggestion_short(
854 "remove this attribute",
856 // Use of `#[no_mangle]` suggests FFI intent; correct
857 // fix may be to monomorphize source by hand
858 Applicability::MaybeIncorrect,
867 hir::ItemKind::Const(..) => {
868 if attr::contains_name(&it.attrs, sym::no_mangle) {
869 // Const items do not refer to a particular location in memory, and therefore
870 // don't have anything to attach a symbol to
871 let msg = "const items should never be `#[no_mangle]`";
872 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
874 // account for "pub const" (#45562)
879 .span_to_snippet(it.span)
880 .map(|snippet| snippet.find("const").unwrap_or(0))
881 .unwrap_or(0) as u32;
882 // `const` is 5 chars
883 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
886 "try a static value",
887 "pub static".to_owned(),
888 Applicability::MachineApplicable,
901 "mutating transmuted &mut T from &T may cause undefined behavior"
904 declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
906 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
907 fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
908 use rustc_target::spec::abi::Abi::RustIntrinsic;
910 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
911 consider instead using an UnsafeCell";
912 match get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (&ty1.kind, &ty2.kind)) {
913 Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
914 if to_mt == hir::Mutability::Mut && from_mt == hir::Mutability::Not {
915 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
921 fn get_transmute_from_to<'a, 'tcx>(
922 cx: &LateContext<'a, 'tcx>,
923 expr: &hir::Expr<'_>,
924 ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
925 let def = if let hir::ExprKind::Path(ref qpath) = expr.kind {
926 cx.tables.qpath_res(qpath, expr.hir_id)
930 if let Res::Def(DefKind::Fn, did) = def {
931 if !def_id_is_transmute(cx, did) {
934 let sig = cx.tables.node_type(expr.hir_id).fn_sig(cx.tcx);
935 let from = sig.inputs().skip_binder()[0];
936 let to = *sig.output().skip_binder();
937 return Some((from, to));
942 fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
943 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic
944 && cx.tcx.item_name(def_id) == sym::transmute
952 "enabling unstable features (deprecated. do not use)"
956 /// Forbids using the `#[feature(...)]` attribute
957 UnstableFeatures => [UNSTABLE_FEATURES]
960 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
961 fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) {
962 if attr.check_name(sym::feature) {
963 if let Some(items) = attr.meta_item_list() {
965 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
975 "`pub` items not reachable from crate root"
979 /// Lint for items marked `pub` that aren't reachable from other crates.
980 UnreachablePub => [UNREACHABLE_PUB]
983 impl UnreachablePub {
986 cx: &LateContext<'_, '_>,
989 vis: &hir::Visibility<'_>,
993 let mut applicability = Applicability::MachineApplicable;
995 hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
996 if span.from_expansion() {
997 applicability = Applicability::MaybeIncorrect;
999 let def_span = cx.tcx.sess.source_map().def_span(span);
1000 let mut err = cx.struct_span_lint(
1003 &format!("unreachable `pub` {}", what),
1005 let replacement = if cx.tcx.features().crate_visibility_modifier {
1012 err.span_suggestion(
1014 "consider restricting its visibility",
1019 err.help("or consider exporting it for use by other crates");
1028 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1029 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
1030 self.perform_lint(cx, "item", item.hir_id, &item.vis, item.span, true);
1033 fn check_foreign_item(
1035 cx: &LateContext<'_, '_>,
1036 foreign_item: &hir::ForeignItem<'tcx>,
1041 foreign_item.hir_id,
1048 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField<'_>) {
1049 self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false);
1052 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem<'_>) {
1053 self.perform_lint(cx, "item", impl_item.hir_id, &impl_item.vis, impl_item.span, false);
1060 "bounds in type aliases are not enforced"
1064 /// Lint for trait and lifetime bounds in type aliases being mostly ignored.
1065 /// They are relevant when using associated types, but otherwise neither checked
1066 /// at definition site nor enforced at use site.
1067 TypeAliasBounds => [TYPE_ALIAS_BOUNDS]
1070 impl TypeAliasBounds {
1071 fn is_type_variable_assoc(qpath: &hir::QPath<'_>) -> bool {
1073 hir::QPath::TypeRelative(ref ty, _) => {
1074 // If this is a type variable, we found a `T::Assoc`.
1076 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => match path.res {
1077 Res::Def(DefKind::TyParam, _) => true,
1083 hir::QPath::Resolved(..) => false,
1087 fn suggest_changing_assoc_types(ty: &hir::Ty<'_>, err: &mut DiagnosticBuilder<'_>) {
1088 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1089 // bound. Let's see if this type does that.
1091 // We use a HIR visitor to walk the type.
1092 use rustc_hir::intravisit::{self, Visitor};
1093 struct WalkAssocTypes<'a, 'db> {
1094 err: &'a mut DiagnosticBuilder<'db>,
1096 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1099 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
1100 intravisit::NestedVisitorMap::None
1103 fn visit_qpath(&mut self, qpath: &'v hir::QPath<'v>, id: hir::HirId, span: Span) {
1104 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1107 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1108 associated types in type aliases",
1111 intravisit::walk_qpath(self, qpath, id, span)
1115 // Let's go for a walk!
1116 let mut visitor = WalkAssocTypes { err };
1117 visitor.visit_ty(ty);
1121 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1122 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
1123 let (ty, type_alias_generics) = match item.kind {
1124 hir::ItemKind::TyAlias(ref ty, ref generics) => (&*ty, generics),
1127 let mut suggested_changing_assoc_types = false;
1128 // There must not be a where clause
1129 if !type_alias_generics.where_clause.predicates.is_empty() {
1130 let spans: Vec<_> = type_alias_generics
1134 .map(|pred| pred.span())
1136 let mut err = cx.struct_span_lint(
1139 "where clauses are not enforced in type aliases",
1141 err.span_suggestion(
1142 type_alias_generics.where_clause.span_for_predicates_or_empty_place(),
1143 "the clause will not be checked when the type alias is used, and should be removed",
1145 Applicability::MachineApplicable,
1147 if !suggested_changing_assoc_types {
1148 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1149 suggested_changing_assoc_types = true;
1153 // The parameters must not have bounds
1154 for param in type_alias_generics.params.iter() {
1155 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1156 let suggestion = spans
1159 let start = param.span.between(*sp); // Include the `:` in `T: Bound`.
1160 (start.to(*sp), String::new())
1163 if !spans.is_empty() {
1164 let mut err = cx.struct_span_lint(
1167 "bounds on generic parameters are not enforced in type aliases",
1169 let msg = "the bound will not be checked when the type alias is used, \
1170 and should be removed";
1171 err.multipart_suggestion(&msg, suggestion, Applicability::MachineApplicable);
1172 if !suggested_changing_assoc_types {
1173 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1174 suggested_changing_assoc_types = true;
1183 /// Lint constants that are erroneous.
1184 /// Without this lint, we might not get any diagnostic if the constant is
1185 /// unused within this crate, even though downstream crates can't use it
1186 /// without producing an error.
1187 UnusedBrokenConst => []
1190 fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) {
1191 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
1192 // trigger the query once for all constants since that will already report the errors
1193 // FIXME: Use ensure here
1194 let _ = cx.tcx.const_eval_poly(def_id);
1197 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1198 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
1200 hir::ItemKind::Const(_, body_id) => {
1201 check_const(cx, body_id);
1203 hir::ItemKind::Static(_, _, body_id) => {
1204 check_const(cx, body_id);
1214 "these bounds don't depend on an type parameters"
1218 /// Lint for trait and lifetime bounds that don't depend on type parameters
1219 /// which either do nothing, or stop the item from being used.
1220 TrivialConstraints => [TRIVIAL_BOUNDS]
1223 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1224 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'tcx>) {
1225 use rustc::ty::fold::TypeFoldable;
1226 use rustc::ty::Predicate::*;
1228 if cx.tcx.features().trivial_bounds {
1229 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1230 let predicates = cx.tcx.predicates_of(def_id);
1231 for &(predicate, span) in predicates.predicates {
1232 let predicate_kind_name = match predicate {
1233 Trait(..) => "Trait",
1235 RegionOutlives(..) => "Lifetime",
1237 // Ignore projections, as they can only be global
1238 // if the trait bound is global
1240 // Ignore bounds that a user can't type
1245 ConstEvaluatable(..) => continue,
1247 if predicate.is_global() {
1252 "{} bound {} does not depend on any type \
1253 or lifetime parameters",
1254 predicate_kind_name, predicate
1264 /// Does nothing as a lint pass, but registers some `Lint`s
1265 /// which are used by other parts of the compiler.
1269 NON_SHORTHAND_FIELD_PATTERNS,
1272 MISSING_COPY_IMPLEMENTATIONS,
1273 MISSING_DEBUG_IMPLEMENTATIONS,
1274 ANONYMOUS_PARAMETERS,
1275 UNUSED_DOC_COMMENTS,
1276 NO_MANGLE_CONST_ITEMS,
1277 NO_MANGLE_GENERIC_ITEMS,
1287 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1289 "`...` range patterns are deprecated"
1293 pub struct EllipsisInclusiveRangePatterns {
1294 /// If `Some(_)`, suppress all subsequent pattern
1295 /// warnings for better diagnostics.
1296 node_id: Option<ast::NodeId>,
1299 impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1301 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1302 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1303 if self.node_id.is_some() {
1304 // Don't recursively warn about patterns inside range endpoints.
1308 use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot};
1310 /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1311 /// corresponding to the ellipsis.
1312 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(&P<Expr>, &P<Expr>, Span)> {
1314 PatKind::Range(a, b, Spanned { span, node: RangeEnd::Included(DotDotDot), .. }) => {
1321 let (parenthesise, endpoints) = match &pat.kind {
1322 PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)),
1323 _ => (false, matches_ellipsis_pat(pat)),
1326 if let Some((start, end, join)) = endpoints {
1327 let msg = "`...` range patterns are deprecated";
1328 let suggestion = "use `..=` for an inclusive range";
1330 self.node_id = Some(pat.id);
1331 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, pat.span, msg);
1332 err.span_suggestion(
1335 format!("&({}..={})", expr_to_string(&start), expr_to_string(&end)),
1336 Applicability::MachineApplicable,
1340 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, join, msg);
1341 err.span_suggestion_short(
1345 Applicability::MachineApplicable,
1352 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1353 if let Some(node_id) = self.node_id {
1354 if pat.id == node_id {
1362 UNNAMEABLE_TEST_ITEMS,
1364 "detects an item that cannot be named being marked as `#[test_case]`",
1365 report_in_external_macro
1368 pub struct UnnameableTestItems {
1369 boundary: hir::HirId, // HirId of the item under which things are not nameable
1370 items_nameable: bool,
1373 impl_lint_pass!(UnnameableTestItems => [UNNAMEABLE_TEST_ITEMS]);
1375 impl UnnameableTestItems {
1376 pub fn new() -> Self {
1377 Self { boundary: hir::DUMMY_HIR_ID, items_nameable: true }
1381 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
1382 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
1383 if self.items_nameable {
1384 if let hir::ItemKind::Mod(..) = it.kind {
1386 self.items_nameable = false;
1387 self.boundary = it.hir_id;
1392 if let Some(attr) = attr::find_by_name(&it.attrs, sym::rustc_test_marker) {
1393 cx.struct_span_lint(UNNAMEABLE_TEST_ITEMS, attr.span, "cannot test inner items").emit();
1397 fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
1398 if !self.items_nameable && self.boundary == it.hir_id {
1399 self.items_nameable = true;
1407 "detects edition keywords being used as an identifier",
1408 @future_incompatible = FutureIncompatibleInfo {
1409 reference: "issue #49716 <https://github.com/rust-lang/rust/issues/49716>",
1410 edition: Some(Edition::Edition2018),
1415 /// Check for uses of edition keywords used as an identifier.
1416 KeywordIdents => [KEYWORD_IDENTS]
1419 struct UnderMacro(bool);
1421 impl KeywordIdents {
1422 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) {
1423 for tt in tokens.into_trees() {
1425 // Only report non-raw idents.
1426 TokenTree::Token(token) => {
1427 if let Some((ident, false)) = token.ident() {
1428 self.check_ident_token(cx, UnderMacro(true), ident);
1431 TokenTree::Delimited(_, _, tts) => self.check_tokens(cx, tts),
1436 fn check_ident_token(
1438 cx: &EarlyContext<'_>,
1439 UnderMacro(under_macro): UnderMacro,
1442 let next_edition = match cx.sess.edition() {
1443 Edition::Edition2015 => {
1445 kw::Async | kw::Await | kw::Try => Edition::Edition2018,
1447 // rust-lang/rust#56327: Conservatively do not
1448 // attempt to report occurrences of `dyn` within
1449 // macro definitions or invocations, because `dyn`
1450 // can legitimately occur as a contextual keyword
1451 // in 2015 code denoting its 2018 meaning, and we
1452 // do not want rustfix to inject bugs into working
1453 // code by rewriting such occurrences.
1455 // But if we see `dyn` outside of a macro, we know
1456 // its precise role in the parsed AST and thus are
1457 // assured this is truly an attempt to use it as
1459 kw::Dyn if !under_macro => Edition::Edition2018,
1465 // There are no new keywords yet for the 2018 edition and beyond.
1469 // Don't lint `r#foo`.
1470 if cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span) {
1474 let mut lint = cx.struct_span_lint(
1477 &format!("`{}` is a keyword in the {} edition", ident, next_edition),
1479 lint.span_suggestion(
1481 "you can use a raw identifier to stay compatible",
1482 format!("r#{}", ident),
1483 Applicability::MachineApplicable,
1489 impl EarlyLintPass for KeywordIdents {
1490 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) {
1491 self.check_tokens(cx, mac_def.body.inner_tokens());
1493 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
1494 self.check_tokens(cx, mac.args.inner_tokens());
1496 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: ast::Ident) {
1497 self.check_ident_token(cx, UnderMacro(false), ident);
1501 declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1503 impl ExplicitOutlivesRequirements {
1504 fn lifetimes_outliving_lifetime<'tcx>(
1505 inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)],
1507 ) -> Vec<ty::Region<'tcx>> {
1510 .filter_map(|(pred, _)| match pred {
1511 ty::Predicate::RegionOutlives(outlives) => {
1512 let outlives = outlives.skip_binder();
1514 ty::ReEarlyBound(ebr) if ebr.index == index => Some(outlives.1),
1523 fn lifetimes_outliving_type<'tcx>(
1524 inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)],
1526 ) -> Vec<ty::Region<'tcx>> {
1529 .filter_map(|(pred, _)| match pred {
1530 ty::Predicate::TypeOutlives(outlives) => {
1531 let outlives = outlives.skip_binder();
1532 outlives.0.is_param(index).then_some(outlives.1)
1539 fn collect_outlived_lifetimes<'tcx>(
1541 param: &'tcx hir::GenericParam<'tcx>,
1543 inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)],
1544 ty_generics: &'tcx ty::Generics,
1545 ) -> Vec<ty::Region<'tcx>> {
1546 let index = ty_generics.param_def_id_to_index[&tcx.hir().local_def_id(param.hir_id)];
1549 hir::GenericParamKind::Lifetime { .. } => {
1550 Self::lifetimes_outliving_lifetime(inferred_outlives, index)
1552 hir::GenericParamKind::Type { .. } => {
1553 Self::lifetimes_outliving_type(inferred_outlives, index)
1555 hir::GenericParamKind::Const { .. } => Vec::new(),
1559 fn collect_outlives_bound_spans<'tcx>(
1562 bounds: &hir::GenericBounds<'_>,
1563 inferred_outlives: &[ty::Region<'tcx>],
1565 ) -> Vec<(usize, Span)> {
1566 use rustc::middle::resolve_lifetime::Region;
1571 .filter_map(|(i, bound)| {
1572 if let hir::GenericBound::Outlives(lifetime) = bound {
1573 let is_inferred = match tcx.named_region(lifetime.hir_id) {
1574 Some(Region::Static) if infer_static => inferred_outlives
1576 .any(|r| if let ty::ReStatic = r { true } else { false }),
1577 Some(Region::EarlyBound(index, ..)) => inferred_outlives.iter().any(|r| {
1578 if let ty::ReEarlyBound(ebr) = r { ebr.index == index } else { false }
1582 is_inferred.then_some((i, bound.span()))
1590 fn consolidate_outlives_bound_spans(
1593 bounds: &hir::GenericBounds<'_>,
1594 bound_spans: Vec<(usize, Span)>,
1596 if bounds.is_empty() {
1599 if bound_spans.len() == bounds.len() {
1600 let (_, last_bound_span) = bound_spans[bound_spans.len() - 1];
1601 // If all bounds are inferable, we want to delete the colon, so
1602 // start from just after the parameter (span passed as argument)
1603 vec![lo.to(last_bound_span)]
1605 let mut merged = Vec::new();
1606 let mut last_merged_i = None;
1608 let mut from_start = true;
1609 for (i, bound_span) in bound_spans {
1610 match last_merged_i {
1611 // If the first bound is inferable, our span should also eat the leading `+`.
1613 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
1614 last_merged_i = Some(0);
1616 // If consecutive bounds are inferable, merge their spans
1617 Some(h) if i == h + 1 => {
1618 if let Some(tail) = merged.last_mut() {
1619 // Also eat the trailing `+` if the first
1620 // more-than-one bound is inferable
1621 let to_span = if from_start && i < bounds.len() {
1622 bounds[i + 1].span().shrink_to_lo()
1626 *tail = tail.to(to_span);
1627 last_merged_i = Some(i);
1629 bug!("another bound-span visited earlier");
1633 // When we find a non-inferable bound, subsequent inferable bounds
1634 // won't be consecutive from the start (and we'll eat the leading
1635 // `+` rather than the trailing one)
1637 merged.push(bounds[i - 1].span().shrink_to_hi().to(bound_span));
1638 last_merged_i = Some(i);
1647 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitOutlivesRequirements {
1648 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
1649 use rustc::middle::resolve_lifetime::Region;
1651 let infer_static = cx.tcx.features().infer_static_outlives_requirements;
1652 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1653 if let hir::ItemKind::Struct(_, ref hir_generics)
1654 | hir::ItemKind::Enum(_, ref hir_generics)
1655 | hir::ItemKind::Union(_, ref hir_generics) = item.kind
1657 let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
1658 if inferred_outlives.is_empty() {
1662 let ty_generics = cx.tcx.generics_of(def_id);
1664 let mut bound_count = 0;
1665 let mut lint_spans = Vec::new();
1667 for param in hir_generics.params {
1668 let has_lifetime_bounds = param.bounds.iter().any(|bound| {
1669 if let hir::GenericBound::Outlives(_) = bound { true } else { false }
1671 if !has_lifetime_bounds {
1675 let relevant_lifetimes =
1676 self.collect_outlived_lifetimes(param, cx.tcx, inferred_outlives, ty_generics);
1677 if relevant_lifetimes.is_empty() {
1681 let bound_spans = self.collect_outlives_bound_spans(
1684 &relevant_lifetimes,
1687 bound_count += bound_spans.len();
1688 lint_spans.extend(self.consolidate_outlives_bound_spans(
1689 param.span.shrink_to_hi(),
1695 let mut where_lint_spans = Vec::new();
1696 let mut dropped_predicate_count = 0;
1697 let num_predicates = hir_generics.where_clause.predicates.len();
1698 for (i, where_predicate) in hir_generics.where_clause.predicates.iter().enumerate() {
1699 let (relevant_lifetimes, bounds, span) = match where_predicate {
1700 hir::WherePredicate::RegionPredicate(predicate) => {
1701 if let Some(Region::EarlyBound(index, ..)) =
1702 cx.tcx.named_region(predicate.lifetime.hir_id)
1705 Self::lifetimes_outliving_lifetime(inferred_outlives, index),
1713 hir::WherePredicate::BoundPredicate(predicate) => {
1714 // FIXME we can also infer bounds on associated types,
1715 // and should check for them here.
1716 match predicate.bounded_ty.kind {
1717 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1718 if let Res::Def(DefKind::TyParam, def_id) = path.res {
1719 let index = ty_generics.param_def_id_to_index[&def_id];
1721 Self::lifetimes_outliving_type(inferred_outlives, index),
1736 if relevant_lifetimes.is_empty() {
1740 let bound_spans = self.collect_outlives_bound_spans(
1743 &relevant_lifetimes,
1746 bound_count += bound_spans.len();
1748 let drop_predicate = bound_spans.len() == bounds.len();
1750 dropped_predicate_count += 1;
1753 // If all the bounds on a predicate were inferable and there are
1754 // further predicates, we want to eat the trailing comma.
1755 if drop_predicate && i + 1 < num_predicates {
1756 let next_predicate_span = hir_generics.where_clause.predicates[i + 1].span();
1757 where_lint_spans.push(span.to(next_predicate_span.shrink_to_lo()));
1759 where_lint_spans.extend(self.consolidate_outlives_bound_spans(
1760 span.shrink_to_lo(),
1767 // If all predicates are inferable, drop the entire clause
1768 // (including the `where`)
1769 if num_predicates > 0 && dropped_predicate_count == num_predicates {
1770 let where_span = hir_generics
1773 .expect("span of (nonempty) where clause should exist");
1774 // Extend the where clause back to the closing `>` of the
1775 // generics, except for tuple struct, which have the `where`
1776 // after the fields of the struct.
1777 let full_where_span =
1778 if let hir::ItemKind::Struct(hir::VariantData::Tuple(..), _) = item.kind {
1781 hir_generics.span.shrink_to_hi().to(where_span)
1783 lint_spans.push(full_where_span);
1785 lint_spans.extend(where_lint_spans);
1788 if !lint_spans.is_empty() {
1789 let mut err = cx.struct_span_lint(
1790 EXPLICIT_OUTLIVES_REQUIREMENTS,
1792 "outlives requirements can be inferred",
1794 err.multipart_suggestion(
1795 if bound_count == 1 { "remove this bound" } else { "remove these bounds" },
1796 lint_spans.into_iter().map(|span| (span, "".to_owned())).collect::<Vec<_>>(),
1797 Applicability::MachineApplicable,
1806 pub INCOMPLETE_FEATURES,
1808 "incomplete features that may function improperly in some or all cases"
1812 /// Check for used feature gates in `INCOMPLETE_FEATURES` in `feature_gate.rs`.
1813 IncompleteFeatures => [INCOMPLETE_FEATURES]
1816 impl EarlyLintPass for IncompleteFeatures {
1817 fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
1818 let features = cx.sess.features_untracked();
1820 .declared_lang_features
1822 .map(|(name, span, _)| (name, span))
1823 .chain(features.declared_lib_features.iter().map(|(name, span)| (name, span)))
1824 .filter(|(name, _)| rustc_feature::INCOMPLETE_FEATURES.iter().any(|f| name == &f))
1825 .for_each(|(name, &span)| {
1826 cx.struct_span_lint(
1827 INCOMPLETE_FEATURES,
1830 "the feature `{}` is incomplete and may cause the compiler to crash",
1842 "an invalid value is being created (such as a NULL reference)"
1845 declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
1847 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidValue {
1848 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>) {
1849 #[derive(Debug, Copy, Clone, PartialEq)]
1855 /// Information about why a type cannot be initialized this way.
1856 /// Contains an error message and optionally a span to point at.
1857 type InitError = (String, Option<Span>);
1859 /// Test if this constant is all-0.
1860 fn is_zero(expr: &hir::Expr<'_>) -> bool {
1861 use hir::ExprKind::*;
1862 use syntax::ast::LitKind::*;
1865 if let Int(i, _) = lit.node {
1871 Tup(tup) => tup.iter().all(is_zero),
1876 /// Determine if this expression is a "dangerous initialization".
1877 fn is_dangerous_init(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) -> Option<InitKind> {
1878 // `transmute` is inside an anonymous module (the `extern` block?);
1879 // `Invalid` represents the empty string and matches that.
1880 // FIXME(#66075): use diagnostic items. Somehow, that does not seem to work
1881 // on intrinsics right now.
1882 const TRANSMUTE_PATH: &[Symbol] =
1883 &[sym::core, sym::intrinsics, kw::Invalid, sym::transmute];
1885 if let hir::ExprKind::Call(ref path_expr, ref args) = expr.kind {
1886 // Find calls to `mem::{uninitialized,zeroed}` methods.
1887 if let hir::ExprKind::Path(ref qpath) = path_expr.kind {
1888 let def_id = cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
1890 if cx.tcx.is_diagnostic_item(sym::mem_zeroed, def_id) {
1891 return Some(InitKind::Zeroed);
1892 } else if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, def_id) {
1893 return Some(InitKind::Uninit);
1894 } else if cx.match_def_path(def_id, TRANSMUTE_PATH) {
1895 if is_zero(&args[0]) {
1896 return Some(InitKind::Zeroed);
1900 } else if let hir::ExprKind::MethodCall(_, _, ref args) = expr.kind {
1901 // Find problematic calls to `MaybeUninit::assume_init`.
1902 let def_id = cx.tables.type_dependent_def_id(expr.hir_id)?;
1903 if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) {
1904 // This is a call to *some* method named `assume_init`.
1905 // See if the `self` parameter is one of the dangerous constructors.
1906 if let hir::ExprKind::Call(ref path_expr, _) = args[0].kind {
1907 if let hir::ExprKind::Path(ref qpath) = path_expr.kind {
1909 cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
1911 if cx.tcx.is_diagnostic_item(sym::maybe_uninit_zeroed, def_id) {
1912 return Some(InitKind::Zeroed);
1913 } else if cx.tcx.is_diagnostic_item(sym::maybe_uninit_uninit, def_id) {
1914 return Some(InitKind::Uninit);
1924 /// Return `Some` only if we are sure this type does *not*
1925 /// allow zero initialization.
1926 fn ty_find_init_error<'tcx>(
1930 ) -> Option<InitError> {
1931 use rustc::ty::TyKind::*;
1933 // Primitive types that don't like 0 as a value.
1934 Ref(..) => Some((format!("References must be non-null"), None)),
1935 Adt(..) if ty.is_box() => Some((format!("`Box` must be non-null"), None)),
1936 FnPtr(..) => Some((format!("Function pointers must be non-null"), None)),
1937 Never => Some((format!("The never type (`!`) has no valid value"), None)),
1938 RawPtr(tm) if matches!(tm.ty.kind, Dynamic(..)) =>
1939 // raw ptr to dyn Trait
1941 Some((format!("The vtable of a wide raw pointer must be non-null"), None))
1943 // Primitive types with other constraints.
1944 Bool if init == InitKind::Uninit => {
1945 Some((format!("Booleans must be `true` or `false`"), None))
1947 Char if init == InitKind::Uninit => {
1948 Some((format!("Characters must be a valid unicode codepoint"), None))
1950 // Recurse and checks for some compound types.
1951 Adt(adt_def, substs) if !adt_def.is_union() => {
1952 // First check f this ADT has a layout attribute (like `NonNull` and friends).
1953 use std::ops::Bound;
1954 match tcx.layout_scalar_valid_range(adt_def.did) {
1955 // We exploit here that `layout_scalar_valid_range` will never
1956 // return `Bound::Excluded`. (And we have tests checking that we
1957 // handle the attribute correctly.)
1958 (Bound::Included(lo), _) if lo > 0 => {
1959 return Some((format!("{} must be non-null", ty), None));
1961 (Bound::Included(_), _) | (_, Bound::Included(_))
1962 if init == InitKind::Uninit =>
1965 format!("{} must be initialized inside its custom valid range", ty),
1972 match adt_def.variants.len() {
1973 0 => Some((format!("0-variant enums have no valid value"), None)),
1975 // Struct, or enum with exactly one variant.
1976 // Proceed recursively, check all fields.
1977 let variant = &adt_def.variants[VariantIdx::from_u32(0)];
1978 variant.fields.iter().find_map(|field| {
1979 ty_find_init_error(tcx, field.ty(tcx, substs), init).map(
1982 // Point to this field, should be helpful for figuring
1983 // out where the source of the error is.
1984 let span = tcx.def_span(field.did);
1987 " (in this {} field)",
2000 // Multi-variant enums are tricky: if all but one variant are
2001 // uninhabited, we might actually do layout like for a single-variant
2002 // enum, and then even leaving them uninitialized could be okay.
2003 _ => None, // Conservative fallback for multi-variant enum.
2007 // Proceed recursively, check all fields.
2008 ty.tuple_fields().find_map(|field| ty_find_init_error(tcx, field, init))
2010 // Conservative fallback.
2015 if let Some(init) = is_dangerous_init(cx, expr) {
2016 // This conjures an instance of a type out of nothing,
2017 // using zeroed or uninitialized memory.
2018 // We are extremely conservative with what we warn about.
2019 let conjured_ty = cx.tables.expr_ty(expr);
2020 if let Some((msg, span)) = ty_find_init_error(cx.tcx, conjured_ty, init) {
2021 let mut err = cx.struct_span_lint(
2025 "the type `{}` does not permit {}",
2028 InitKind::Zeroed => "zero-initialization",
2029 InitKind::Uninit => "being left uninitialized",
2033 err.span_label(expr.span, "this code causes undefined behavior when executed");
2036 "help: use `MaybeUninit<T>` instead, \
2037 and only call `assume_init` after initialization is done",
2039 if let Some(span) = span {
2040 err.span_note(span, &msg);