1 //! Lints in the Rust compiler.
3 //! This contains lints which can feasibly be implemented as their own
4 //! AST visitor. Also see `rustc::lint::builtin`, which contains the
5 //! definitions of lints that are emitted directly inside the main
8 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
9 //! Then add code to emit the new lint in the appropriate circumstances.
10 //! You can do that in an existing `LintPass` if it makes sense, or in a
11 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
12 //! compiler. Only do the latter if the check can't be written cleanly as a
13 //! `LintPass` (also, note that such lints will need to be defined in
14 //! `rustc::lint::builtin`, not here).
16 //! If you define a new `EarlyLintPass`, you will also need to add it to the
17 //! `add_early_builtin!` or `add_early_builtin_with_new!` invocation in
18 //! `lib.rs`. Use the former for unit-like structs and the latter for structs
19 //! with a `pub fn new()`.
21 //! If you define a new `LateLintPass`, you will also need to add it to the
22 //! `late_lint_methods!` invocation in `lib.rs`.
24 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
25 use rustc::hir::map::Map;
26 use rustc::traits::misc::can_type_implement_copy;
27 use rustc::ty::{self, layout::VariantIdx, Ty, TyCtxt};
28 use rustc_ast_pretty::pprust::{self, expr_to_string};
29 use rustc_data_structures::fx::FxHashSet;
30 use rustc_errors::{Applicability, DiagnosticBuilder};
31 use rustc_feature::Stability;
32 use rustc_feature::{deprecated_attributes, AttributeGate, AttributeTemplate, AttributeType};
34 use rustc_hir::def::{DefKind, Res};
35 use rustc_hir::def_id::DefId;
36 use rustc_hir::{GenericParamKind, PatKind};
37 use rustc_hir::{HirIdSet, Node};
38 use rustc_session::lint::FutureIncompatibleInfo;
39 use rustc_span::edition::Edition;
40 use rustc_span::source_map::Spanned;
41 use rustc_span::symbol::{kw, sym, Symbol};
42 use rustc_span::{BytePos, Span};
43 use syntax::ast::{self, Expr};
44 use syntax::attr::{self, HasAttrs};
45 use syntax::tokenstream::{TokenStream, TokenTree};
46 use syntax::visit::{FnCtxt, FnKind};
48 use crate::nonstandard_style::{method_context, MethodLateContext};
53 // hardwired lints from librustc
54 pub use rustc_session::lint::builtin::*;
59 "suggest using `loop { }` instead of `while true { }`"
62 declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
64 /// Traverse through any amount of parenthesis and return the first non-parens expression.
65 fn pierce_parens(mut expr: &ast::Expr) -> &ast::Expr {
66 while let ast::ExprKind::Paren(sub) = &expr.kind {
72 impl EarlyLintPass for WhileTrue {
73 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
74 if let ast::ExprKind::While(cond, ..) = &e.kind {
75 if let ast::ExprKind::Lit(ref lit) = pierce_parens(cond).kind {
76 if let ast::LitKind::Bool(true) = lit.kind {
77 if !lit.span.from_expansion() {
78 let msg = "denote infinite loops with `loop { ... }`";
79 let condition_span = cx.sess.source_map().def_span(e.span);
80 cx.struct_span_lint(WHILE_TRUE, condition_span, msg)
81 .span_suggestion_short(
85 Applicability::MachineApplicable,
98 "use of owned (Box type) heap memory"
101 declare_lint_pass!(BoxPointers => [BOX_POINTERS]);
104 fn check_heap_type(&self, cx: &LateContext<'_, '_>, span: Span, ty: Ty<'_>) {
105 for leaf_ty in ty.walk() {
106 if leaf_ty.is_box() {
107 let m = format!("type uses owned (Box type) pointers: {}", ty);
108 cx.span_lint(BOX_POINTERS, span, &m);
114 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
115 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
117 hir::ItemKind::Fn(..)
118 | hir::ItemKind::TyAlias(..)
119 | hir::ItemKind::Enum(..)
120 | hir::ItemKind::Struct(..)
121 | hir::ItemKind::Union(..) => {
122 let def_id = cx.tcx.hir().local_def_id(it.hir_id);
123 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
128 // If it's a struct, we also have to check the fields' types
130 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
131 for struct_field in struct_def.fields() {
132 let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id);
133 self.check_heap_type(cx, struct_field.span, cx.tcx.type_of(def_id));
140 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) {
141 let ty = cx.tables.node_type(e.hir_id);
142 self.check_heap_type(cx, e.span, ty);
147 NON_SHORTHAND_FIELD_PATTERNS,
149 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
152 declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
154 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
155 fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>) {
156 if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
161 .expect("struct pattern type is not an ADT")
162 .variant_of_res(cx.tables.qpath_res(qpath, pat.hir_id));
163 for fieldpat in field_pats {
164 if fieldpat.is_shorthand {
167 if fieldpat.span.from_expansion() {
168 // Don't lint if this is a macro expansion: macro authors
169 // shouldn't have to worry about this kind of style issue
173 if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind {
174 if cx.tcx.find_field_index(ident, &variant)
175 == Some(cx.tcx.field_index(fieldpat.hir_id, cx.tables))
177 let mut err = cx.struct_span_lint(
178 NON_SHORTHAND_FIELD_PATTERNS,
180 &format!("the `{}:` in this pattern is redundant", ident),
182 let binding = match binding_annot {
183 hir::BindingAnnotation::Unannotated => None,
184 hir::BindingAnnotation::Mutable => Some("mut"),
185 hir::BindingAnnotation::Ref => Some("ref"),
186 hir::BindingAnnotation::RefMut => Some("ref mut"),
188 let ident = if let Some(binding) = binding {
189 format!("{} {}", binding, ident)
195 "use shorthand field pattern",
197 Applicability::MachineApplicable,
210 "usage of `unsafe` code"
213 declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
216 fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) {
217 // This comes from a macro that has `#[allow_internal_unsafe]`.
218 if span.allows_unsafe() {
222 cx.span_lint(UNSAFE_CODE, span, desc);
226 impl EarlyLintPass for UnsafeCode {
227 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
228 if attr.check_name(sym::allow_internal_unsafe) {
232 "`allow_internal_unsafe` allows defining \
233 macros using unsafe without triggering \
234 the `unsafe_code` lint at their call site",
239 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
240 if let ast::ExprKind::Block(ref blk, _) = e.kind {
241 // Don't warn about generated blocks; that'll just pollute the output.
242 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
243 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
248 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
250 ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => {
251 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
254 ast::ItemKind::Impl { unsafety: ast::Unsafety::Unsafe, .. } => {
255 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
262 fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId) {
266 ast::FnSig { header: ast::FnHeader { unsafety: ast::Unsafety::Unsafe, .. }, .. },
271 let msg = match ctxt {
272 FnCtxt::Foreign => return,
273 FnCtxt::Free => "declaration of an `unsafe` function",
274 FnCtxt::Assoc(_) if body.is_none() => "declaration of an `unsafe` method",
275 FnCtxt::Assoc(_) => "implementation of an `unsafe` method",
277 self.report_unsafe(cx, span, msg);
285 "detects missing documentation for public members",
286 report_in_external_macro
289 pub struct MissingDoc {
290 /// Stack of whether `#[doc(hidden)]` is set at each level which has lint attributes.
291 doc_hidden_stack: Vec<bool>,
293 /// Private traits or trait items that leaked through. Don't check their methods.
294 private_traits: FxHashSet<hir::HirId>,
297 impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
299 fn has_doc(attr: &ast::Attribute) -> bool {
300 if attr.is_doc_comment() {
304 if !attr.check_name(sym::doc) {
308 if attr.is_value_str() {
312 if let Some(list) = attr.meta_item_list() {
314 if meta.check_name(sym::include) || meta.check_name(sym::hidden) {
324 pub fn new() -> MissingDoc {
325 MissingDoc { doc_hidden_stack: vec![false], private_traits: FxHashSet::default() }
328 fn doc_hidden(&self) -> bool {
329 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
332 fn check_missing_docs_attrs(
334 cx: &LateContext<'_, '_>,
335 id: Option<hir::HirId>,
336 attrs: &[ast::Attribute],
340 // If we're building a test harness, then warning about
341 // documentation is probably not really relevant right now.
342 if cx.sess().opts.test {
346 // `#[doc(hidden)]` disables missing_docs check.
347 if self.doc_hidden() {
351 // Only check publicly-visible items, using the result from the privacy pass.
352 // It's an option so the crate root can also use this function (it doesn't
354 if let Some(id) = id {
355 if !cx.access_levels.is_exported(id) {
360 let has_doc = attrs.iter().any(|a| has_doc(a));
364 cx.tcx.sess.source_map().def_span(sp),
365 &format!("missing documentation for {}", desc),
371 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
372 fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) {
373 let doc_hidden = self.doc_hidden()
374 || attrs.iter().any(|attr| {
375 attr.check_name(sym::doc)
376 && match attr.meta_item_list() {
378 Some(l) => attr::list_contains_name(&l, sym::hidden),
381 self.doc_hidden_stack.push(doc_hidden);
384 fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) {
385 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
388 fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate<'_>) {
389 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
391 for macro_def in krate.exported_macros {
392 let has_doc = macro_def.attrs.iter().any(|a| has_doc(a));
396 cx.tcx.sess.source_map().def_span(macro_def.span),
397 "missing documentation for macro",
403 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
404 let desc = match it.kind {
405 hir::ItemKind::Fn(..) => "a function",
406 hir::ItemKind::Mod(..) => "a module",
407 hir::ItemKind::Enum(..) => "an enum",
408 hir::ItemKind::Struct(..) => "a struct",
409 hir::ItemKind::Union(..) => "a union",
410 hir::ItemKind::Trait(.., trait_item_refs) => {
411 // Issue #11592: traits are always considered exported, even when private.
412 if let hir::VisibilityKind::Inherited = it.vis.node {
413 self.private_traits.insert(it.hir_id);
414 for trait_item_ref in trait_item_refs {
415 self.private_traits.insert(trait_item_ref.id.hir_id);
421 hir::ItemKind::TyAlias(..) => "a type alias",
422 hir::ItemKind::Impl { of_trait: Some(ref trait_ref), items, .. } => {
423 // If the trait is private, add the impl items to `private_traits` so they don't get
424 // reported for missing docs.
425 let real_trait = trait_ref.path.res.def_id();
426 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(real_trait) {
427 match cx.tcx.hir().find(hir_id) {
428 Some(Node::Item(item)) => {
429 if let hir::VisibilityKind::Inherited = item.vis.node {
430 for impl_item_ref in items {
431 self.private_traits.insert(impl_item_ref.id.hir_id);
440 hir::ItemKind::Const(..) => "a constant",
441 hir::ItemKind::Static(..) => "a static",
445 self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, desc);
448 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem<'_>) {
449 if self.private_traits.contains(&trait_item.hir_id) {
453 let desc = match trait_item.kind {
454 hir::TraitItemKind::Const(..) => "an associated constant",
455 hir::TraitItemKind::Method(..) => "a trait method",
456 hir::TraitItemKind::Type(..) => "an associated type",
459 self.check_missing_docs_attrs(
461 Some(trait_item.hir_id),
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.hir_id) == MethodLateContext::TraitImpl {
474 let desc = match impl_item.kind {
475 hir::ImplItemKind::Const(..) => "an associated constant",
476 hir::ImplItemKind::Method(..) => "a method",
477 hir::ImplItemKind::TyAlias(_) => "an associated type",
478 hir::ImplItemKind::OpaqueTy(_) => "an associated `impl Trait` type",
480 self.check_missing_docs_attrs(
482 Some(impl_item.hir_id),
489 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField<'_>) {
490 if !sf.is_positional() {
491 self.check_missing_docs_attrs(cx, Some(sf.hir_id), &sf.attrs, sf.span, "a struct field")
495 fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant<'_>) {
496 self.check_missing_docs_attrs(cx, Some(v.id), &v.attrs, v.span, "a variant");
501 pub MISSING_COPY_IMPLEMENTATIONS,
503 "detects potentially-forgotten implementations of `Copy`"
506 declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
508 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
509 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
510 if !cx.access_levels.is_reachable(item.hir_id) {
513 let (def, ty) = match item.kind {
514 hir::ItemKind::Struct(_, ref ast_generics) => {
515 if !ast_generics.params.is_empty() {
518 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
519 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
521 hir::ItemKind::Union(_, ref ast_generics) => {
522 if !ast_generics.params.is_empty() {
525 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
526 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
528 hir::ItemKind::Enum(_, ref ast_generics) => {
529 if !ast_generics.params.is_empty() {
532 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
533 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
537 if def.has_dtor(cx.tcx) {
540 let param_env = ty::ParamEnv::empty();
541 if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span) {
544 if can_type_implement_copy(cx.tcx, param_env, ty).is_ok() {
546 MISSING_COPY_IMPLEMENTATIONS,
548 "type could implement `Copy`; consider adding `impl \
556 MISSING_DEBUG_IMPLEMENTATIONS,
558 "detects missing implementations of Debug"
562 pub struct MissingDebugImplementations {
563 impling_types: Option<HirIdSet>,
566 impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
568 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
569 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
570 if !cx.access_levels.is_reachable(item.hir_id) {
575 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {}
579 let debug = match cx.tcx.get_diagnostic_item(sym::debug_trait) {
580 Some(debug) => debug,
584 if self.impling_types.is_none() {
585 let mut impls = HirIdSet::default();
586 cx.tcx.for_each_impl(debug, |d| {
587 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
588 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
589 impls.insert(hir_id);
594 self.impling_types = Some(impls);
595 debug!("{:?}", self.impling_types);
598 if !self.impling_types.as_ref().unwrap().contains(&item.hir_id) {
600 MISSING_DEBUG_IMPLEMENTATIONS,
603 "type does not implement `{}`; consider adding `#[derive(Debug)]` \
604 or a manual implementation",
605 cx.tcx.def_path_str(debug)
613 pub ANONYMOUS_PARAMETERS,
615 "detects anonymous parameters",
616 @future_incompatible = FutureIncompatibleInfo {
617 reference: "issue #41686 <https://github.com/rust-lang/rust/issues/41686>",
618 edition: Some(Edition::Edition2018),
623 /// Checks for use of anonymous parameters (RFC 1685).
624 AnonymousParameters => [ANONYMOUS_PARAMETERS]
627 impl EarlyLintPass for AnonymousParameters {
628 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
630 ast::AssocItemKind::Fn(ref sig, _) => {
631 for arg in sig.decl.inputs.iter() {
633 ast::PatKind::Ident(_, ident, None) => {
634 if ident.name == kw::Invalid {
635 let ty_snip = cx.sess.source_map().span_to_snippet(arg.ty.span);
637 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
638 (snip, Applicability::MachineApplicable)
640 ("<type>".to_owned(), Applicability::HasPlaceholders)
644 ANONYMOUS_PARAMETERS,
646 "anonymous parameters are deprecated and will be \
647 removed in the next edition.",
651 "try naming the parameter or explicitly \
653 format!("_: {}", ty_snip),
668 /// Check for use of attributes which have been deprecated.
670 pub struct DeprecatedAttr {
671 // This is not free to compute, so we want to keep it around, rather than
672 // compute it for every attribute.
673 depr_attrs: Vec<&'static (Symbol, AttributeType, AttributeTemplate, AttributeGate)>,
676 impl_lint_pass!(DeprecatedAttr => []);
678 impl DeprecatedAttr {
679 pub fn new() -> DeprecatedAttr {
680 DeprecatedAttr { depr_attrs: deprecated_attributes() }
684 fn lint_deprecated_attr(
685 cx: &EarlyContext<'_>,
686 attr: &ast::Attribute,
688 suggestion: Option<&str>,
690 cx.struct_span_lint(DEPRECATED, attr.span, &msg)
691 .span_suggestion_short(
693 suggestion.unwrap_or("remove this attribute"),
695 Applicability::MachineApplicable,
700 impl EarlyLintPass for DeprecatedAttr {
701 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
702 for &&(n, _, _, ref g) in &self.depr_attrs {
703 if attr.ident().map(|ident| ident.name) == Some(n) {
704 if let &AttributeGate::Gated(
705 Stability::Deprecated(link, suggestion),
712 format!("use of deprecated attribute `{}`: {}. See {}", name, reason, link);
713 lint_deprecated_attr(cx, attr, &msg, suggestion);
718 if attr.check_name(sym::no_start) || attr.check_name(sym::crate_id) {
719 let path_str = pprust::path_to_string(&attr.get_normal_item().path);
720 let msg = format!("use of deprecated attribute `{}`: no longer used.", path_str);
721 lint_deprecated_attr(cx, attr, &msg, None);
727 pub UNUSED_DOC_COMMENTS,
729 "detects doc comments that aren't used by rustdoc"
732 declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]);
734 impl UnusedDocComment {
737 cx: &EarlyContext<'_>,
740 is_macro_expansion: bool,
741 attrs: &[ast::Attribute],
743 let mut attrs = attrs.into_iter().peekable();
745 // Accumulate a single span for sugared doc comments.
746 let mut sugared_span: Option<Span> = None;
748 while let Some(attr) = attrs.next() {
749 if attr.is_doc_comment() {
751 sugared_span.map_or_else(|| attr.span, |span| span.with_hi(attr.span.hi())),
755 if attrs.peek().map(|next_attr| next_attr.is_doc_comment()).unwrap_or_default() {
759 let span = sugared_span.take().unwrap_or_else(|| attr.span);
761 if attr.is_doc_comment() || attr.check_name(sym::doc) {
762 let mut err = cx.struct_span_lint(UNUSED_DOC_COMMENTS, span, "unused doc comment");
766 format!("rustdoc does not generate documentation for {}", node_kind),
769 if is_macro_expansion {
771 "to document an item produced by a macro, \
772 the macro must produce the documentation as part of its expansion",
782 impl EarlyLintPass for UnusedDocComment {
783 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
784 if let ast::ItemKind::Mac(..) = item.kind {
785 self.warn_if_doc(cx, item.span, "macro expansions", true, &item.attrs);
789 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
790 let (kind, is_macro_expansion) = match stmt.kind {
791 ast::StmtKind::Local(..) => ("statements", false),
792 ast::StmtKind::Item(..) => ("inner items", false),
793 ast::StmtKind::Mac(..) => ("macro expansions", true),
794 // expressions will be reported by `check_expr`.
795 ast::StmtKind::Semi(..) | ast::StmtKind::Expr(..) => return,
798 self.warn_if_doc(cx, stmt.span, kind, is_macro_expansion, stmt.kind.attrs());
801 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
802 let arm_span = arm.pat.span.with_hi(arm.body.span.hi());
803 self.warn_if_doc(cx, arm_span, "match arms", false, &arm.attrs);
806 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
807 self.warn_if_doc(cx, expr.span, "expressions", false, &expr.attrs);
812 NO_MANGLE_CONST_ITEMS,
814 "const items will not have their symbols exported"
818 NO_MANGLE_GENERIC_ITEMS,
820 "generic items must be mangled"
823 declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
825 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
826 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
828 hir::ItemKind::Fn(.., ref generics, _) => {
829 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
830 for param in generics.params {
832 GenericParamKind::Lifetime { .. } => {}
833 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
834 let mut err = cx.struct_span_lint(
835 NO_MANGLE_GENERIC_ITEMS,
837 "functions generic over types or consts must be mangled",
839 err.span_suggestion_short(
841 "remove this attribute",
843 // Use of `#[no_mangle]` suggests FFI intent; correct
844 // fix may be to monomorphize source by hand
845 Applicability::MaybeIncorrect,
854 hir::ItemKind::Const(..) => {
855 if attr::contains_name(&it.attrs, sym::no_mangle) {
856 // Const items do not refer to a particular location in memory, and therefore
857 // don't have anything to attach a symbol to
858 let msg = "const items should never be `#[no_mangle]`";
859 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
861 // account for "pub const" (#45562)
866 .span_to_snippet(it.span)
867 .map(|snippet| snippet.find("const").unwrap_or(0))
868 .unwrap_or(0) as u32;
869 // `const` is 5 chars
870 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
873 "try a static value",
874 "pub static".to_owned(),
875 Applicability::MachineApplicable,
888 "mutating transmuted &mut T from &T may cause undefined behavior"
891 declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
893 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
894 fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
895 use rustc_target::spec::abi::Abi::RustIntrinsic;
897 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
898 consider instead using an UnsafeCell";
899 match get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (&ty1.kind, &ty2.kind)) {
900 Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
901 if to_mt == hir::Mutability::Mut && from_mt == hir::Mutability::Not {
902 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
908 fn get_transmute_from_to<'a, 'tcx>(
909 cx: &LateContext<'a, 'tcx>,
910 expr: &hir::Expr<'_>,
911 ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
912 let def = if let hir::ExprKind::Path(ref qpath) = expr.kind {
913 cx.tables.qpath_res(qpath, expr.hir_id)
917 if let Res::Def(DefKind::Fn, did) = def {
918 if !def_id_is_transmute(cx, did) {
921 let sig = cx.tables.node_type(expr.hir_id).fn_sig(cx.tcx);
922 let from = sig.inputs().skip_binder()[0];
923 let to = *sig.output().skip_binder();
924 return Some((from, to));
929 fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
930 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic
931 && cx.tcx.item_name(def_id) == sym::transmute
939 "enabling unstable features (deprecated. do not use)"
943 /// Forbids using the `#[feature(...)]` attribute
944 UnstableFeatures => [UNSTABLE_FEATURES]
947 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
948 fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) {
949 if attr.check_name(sym::feature) {
950 if let Some(items) = attr.meta_item_list() {
952 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
962 "`pub` items not reachable from crate root"
966 /// Lint for items marked `pub` that aren't reachable from other crates.
967 UnreachablePub => [UNREACHABLE_PUB]
970 impl UnreachablePub {
973 cx: &LateContext<'_, '_>,
976 vis: &hir::Visibility<'_>,
980 let mut applicability = Applicability::MachineApplicable;
982 hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
983 if span.from_expansion() {
984 applicability = Applicability::MaybeIncorrect;
986 let def_span = cx.tcx.sess.source_map().def_span(span);
987 let mut err = cx.struct_span_lint(
990 &format!("unreachable `pub` {}", what),
992 let replacement = if cx.tcx.features().crate_visibility_modifier {
1001 "consider restricting its visibility",
1006 err.help("or consider exporting it for use by other crates");
1015 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1016 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
1017 self.perform_lint(cx, "item", item.hir_id, &item.vis, item.span, true);
1020 fn check_foreign_item(
1022 cx: &LateContext<'_, '_>,
1023 foreign_item: &hir::ForeignItem<'tcx>,
1028 foreign_item.hir_id,
1035 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField<'_>) {
1036 self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false);
1039 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem<'_>) {
1040 self.perform_lint(cx, "item", impl_item.hir_id, &impl_item.vis, impl_item.span, false);
1047 "bounds in type aliases are not enforced"
1051 /// Lint for trait and lifetime bounds in type aliases being mostly ignored.
1052 /// They are relevant when using associated types, but otherwise neither checked
1053 /// at definition site nor enforced at use site.
1054 TypeAliasBounds => [TYPE_ALIAS_BOUNDS]
1057 impl TypeAliasBounds {
1058 fn is_type_variable_assoc(qpath: &hir::QPath<'_>) -> bool {
1060 hir::QPath::TypeRelative(ref ty, _) => {
1061 // If this is a type variable, we found a `T::Assoc`.
1063 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => match path.res {
1064 Res::Def(DefKind::TyParam, _) => true,
1070 hir::QPath::Resolved(..) => false,
1074 fn suggest_changing_assoc_types(ty: &hir::Ty<'_>, err: &mut DiagnosticBuilder<'_>) {
1075 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1076 // bound. Let's see if this type does that.
1078 // We use a HIR visitor to walk the type.
1079 use rustc_hir::intravisit::{self, Visitor};
1080 struct WalkAssocTypes<'a, 'db> {
1081 err: &'a mut DiagnosticBuilder<'db>,
1083 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1086 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
1087 intravisit::NestedVisitorMap::None
1090 fn visit_qpath(&mut self, qpath: &'v hir::QPath<'v>, id: hir::HirId, span: Span) {
1091 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1094 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1095 associated types in type aliases",
1098 intravisit::walk_qpath(self, qpath, id, span)
1102 // Let's go for a walk!
1103 let mut visitor = WalkAssocTypes { err };
1104 visitor.visit_ty(ty);
1108 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1109 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
1110 let (ty, type_alias_generics) = match item.kind {
1111 hir::ItemKind::TyAlias(ref ty, ref generics) => (&*ty, generics),
1114 let mut suggested_changing_assoc_types = false;
1115 // There must not be a where clause
1116 if !type_alias_generics.where_clause.predicates.is_empty() {
1117 let spans: Vec<_> = type_alias_generics
1121 .map(|pred| pred.span())
1123 let mut err = cx.struct_span_lint(
1126 "where clauses are not enforced in type aliases",
1128 err.span_suggestion(
1129 type_alias_generics.where_clause.span_for_predicates_or_empty_place(),
1130 "the clause will not be checked when the type alias is used, and should be removed",
1132 Applicability::MachineApplicable,
1134 if !suggested_changing_assoc_types {
1135 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1136 suggested_changing_assoc_types = true;
1140 // The parameters must not have bounds
1141 for param in type_alias_generics.params.iter() {
1142 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1143 let suggestion = spans
1146 let start = param.span.between(*sp); // Include the `:` in `T: Bound`.
1147 (start.to(*sp), String::new())
1150 if !spans.is_empty() {
1151 let mut err = cx.struct_span_lint(
1154 "bounds on generic parameters are not enforced in type aliases",
1156 let msg = "the bound will not be checked when the type alias is used, \
1157 and should be removed";
1158 err.multipart_suggestion(&msg, suggestion, Applicability::MachineApplicable);
1159 if !suggested_changing_assoc_types {
1160 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1161 suggested_changing_assoc_types = true;
1170 /// Lint constants that are erroneous.
1171 /// Without this lint, we might not get any diagnostic if the constant is
1172 /// unused within this crate, even though downstream crates can't use it
1173 /// without producing an error.
1174 UnusedBrokenConst => []
1177 fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) {
1178 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
1179 // trigger the query once for all constants since that will already report the errors
1180 // FIXME: Use ensure here
1181 let _ = cx.tcx.const_eval_poly(def_id);
1184 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1185 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
1187 hir::ItemKind::Const(_, body_id) => {
1188 check_const(cx, body_id);
1190 hir::ItemKind::Static(_, _, body_id) => {
1191 check_const(cx, body_id);
1201 "these bounds don't depend on an type parameters"
1205 /// Lint for trait and lifetime bounds that don't depend on type parameters
1206 /// which either do nothing, or stop the item from being used.
1207 TrivialConstraints => [TRIVIAL_BOUNDS]
1210 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1211 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'tcx>) {
1212 use rustc::ty::fold::TypeFoldable;
1213 use rustc::ty::Predicate::*;
1215 if cx.tcx.features().trivial_bounds {
1216 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1217 let predicates = cx.tcx.predicates_of(def_id);
1218 for &(predicate, span) in predicates.predicates {
1219 let predicate_kind_name = match predicate {
1220 Trait(..) => "Trait",
1222 RegionOutlives(..) => "Lifetime",
1224 // Ignore projections, as they can only be global
1225 // if the trait bound is global
1227 // Ignore bounds that a user can't type
1232 ConstEvaluatable(..) => continue,
1234 if predicate.is_global() {
1239 "{} bound {} does not depend on any type \
1240 or lifetime parameters",
1241 predicate_kind_name, predicate
1251 /// Does nothing as a lint pass, but registers some `Lint`s
1252 /// which are used by other parts of the compiler.
1256 NON_SHORTHAND_FIELD_PATTERNS,
1259 MISSING_COPY_IMPLEMENTATIONS,
1260 MISSING_DEBUG_IMPLEMENTATIONS,
1261 ANONYMOUS_PARAMETERS,
1262 UNUSED_DOC_COMMENTS,
1263 NO_MANGLE_CONST_ITEMS,
1264 NO_MANGLE_GENERIC_ITEMS,
1274 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1276 "`...` range patterns are deprecated"
1280 pub struct EllipsisInclusiveRangePatterns {
1281 /// If `Some(_)`, suppress all subsequent pattern
1282 /// warnings for better diagnostics.
1283 node_id: Option<ast::NodeId>,
1286 impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1288 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1289 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1290 if self.node_id.is_some() {
1291 // Don't recursively warn about patterns inside range endpoints.
1295 use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot};
1297 /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1298 /// corresponding to the ellipsis.
1299 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(Option<&Expr>, &Expr, Span)> {
1304 Spanned { span, node: RangeEnd::Included(DotDotDot) },
1305 ) => Some((a.as_deref(), b, *span)),
1310 let (parenthesise, endpoints) = match &pat.kind {
1311 PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)),
1312 _ => (false, matches_ellipsis_pat(pat)),
1315 if let Some((start, end, join)) = endpoints {
1316 let msg = "`...` range patterns are deprecated";
1317 let suggestion = "use `..=` for an inclusive range";
1319 self.node_id = Some(pat.id);
1320 let end = expr_to_string(&end);
1321 let replace = match start {
1322 Some(start) => format!("&({}..={})", expr_to_string(&start), end),
1323 None => format!("&(..={})", end),
1325 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, pat.span, msg);
1326 err.span_suggestion(
1330 Applicability::MachineApplicable,
1334 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, join, msg);
1335 err.span_suggestion_short(
1339 Applicability::MachineApplicable,
1346 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1347 if let Some(node_id) = self.node_id {
1348 if pat.id == node_id {
1356 UNNAMEABLE_TEST_ITEMS,
1358 "detects an item that cannot be named being marked as `#[test_case]`",
1359 report_in_external_macro
1362 pub struct UnnameableTestItems {
1363 boundary: hir::HirId, // HirId of the item under which things are not nameable
1364 items_nameable: bool,
1367 impl_lint_pass!(UnnameableTestItems => [UNNAMEABLE_TEST_ITEMS]);
1369 impl UnnameableTestItems {
1370 pub fn new() -> Self {
1371 Self { boundary: hir::DUMMY_HIR_ID, items_nameable: true }
1375 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
1376 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
1377 if self.items_nameable {
1378 if let hir::ItemKind::Mod(..) = it.kind {
1380 self.items_nameable = false;
1381 self.boundary = it.hir_id;
1386 if let Some(attr) = attr::find_by_name(&it.attrs, sym::rustc_test_marker) {
1387 cx.struct_span_lint(UNNAMEABLE_TEST_ITEMS, attr.span, "cannot test inner items").emit();
1391 fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
1392 if !self.items_nameable && self.boundary == it.hir_id {
1393 self.items_nameable = true;
1401 "detects edition keywords being used as an identifier",
1402 @future_incompatible = FutureIncompatibleInfo {
1403 reference: "issue #49716 <https://github.com/rust-lang/rust/issues/49716>",
1404 edition: Some(Edition::Edition2018),
1409 /// Check for uses of edition keywords used as an identifier.
1410 KeywordIdents => [KEYWORD_IDENTS]
1413 struct UnderMacro(bool);
1415 impl KeywordIdents {
1416 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) {
1417 for tt in tokens.into_trees() {
1419 // Only report non-raw idents.
1420 TokenTree::Token(token) => {
1421 if let Some((ident, false)) = token.ident() {
1422 self.check_ident_token(cx, UnderMacro(true), ident);
1425 TokenTree::Delimited(_, _, tts) => self.check_tokens(cx, tts),
1430 fn check_ident_token(
1432 cx: &EarlyContext<'_>,
1433 UnderMacro(under_macro): UnderMacro,
1436 let next_edition = match cx.sess.edition() {
1437 Edition::Edition2015 => {
1439 kw::Async | kw::Await | kw::Try => Edition::Edition2018,
1441 // rust-lang/rust#56327: Conservatively do not
1442 // attempt to report occurrences of `dyn` within
1443 // macro definitions or invocations, because `dyn`
1444 // can legitimately occur as a contextual keyword
1445 // in 2015 code denoting its 2018 meaning, and we
1446 // do not want rustfix to inject bugs into working
1447 // code by rewriting such occurrences.
1449 // But if we see `dyn` outside of a macro, we know
1450 // its precise role in the parsed AST and thus are
1451 // assured this is truly an attempt to use it as
1453 kw::Dyn if !under_macro => Edition::Edition2018,
1459 // There are no new keywords yet for the 2018 edition and beyond.
1463 // Don't lint `r#foo`.
1464 if cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span) {
1468 let mut lint = cx.struct_span_lint(
1471 &format!("`{}` is a keyword in the {} edition", ident, next_edition),
1473 lint.span_suggestion(
1475 "you can use a raw identifier to stay compatible",
1476 format!("r#{}", ident),
1477 Applicability::MachineApplicable,
1483 impl EarlyLintPass for KeywordIdents {
1484 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) {
1485 self.check_tokens(cx, mac_def.body.inner_tokens());
1487 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
1488 self.check_tokens(cx, mac.args.inner_tokens());
1490 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: ast::Ident) {
1491 self.check_ident_token(cx, UnderMacro(false), ident);
1495 declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1497 impl ExplicitOutlivesRequirements {
1498 fn lifetimes_outliving_lifetime<'tcx>(
1499 inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)],
1501 ) -> Vec<ty::Region<'tcx>> {
1504 .filter_map(|(pred, _)| match pred {
1505 ty::Predicate::RegionOutlives(outlives) => {
1506 let outlives = outlives.skip_binder();
1508 ty::ReEarlyBound(ebr) if ebr.index == index => Some(outlives.1),
1517 fn lifetimes_outliving_type<'tcx>(
1518 inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)],
1520 ) -> Vec<ty::Region<'tcx>> {
1523 .filter_map(|(pred, _)| match pred {
1524 ty::Predicate::TypeOutlives(outlives) => {
1525 let outlives = outlives.skip_binder();
1526 outlives.0.is_param(index).then_some(outlives.1)
1533 fn collect_outlived_lifetimes<'tcx>(
1535 param: &'tcx hir::GenericParam<'tcx>,
1537 inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)],
1538 ty_generics: &'tcx ty::Generics,
1539 ) -> Vec<ty::Region<'tcx>> {
1540 let index = ty_generics.param_def_id_to_index[&tcx.hir().local_def_id(param.hir_id)];
1543 hir::GenericParamKind::Lifetime { .. } => {
1544 Self::lifetimes_outliving_lifetime(inferred_outlives, index)
1546 hir::GenericParamKind::Type { .. } => {
1547 Self::lifetimes_outliving_type(inferred_outlives, index)
1549 hir::GenericParamKind::Const { .. } => Vec::new(),
1553 fn collect_outlives_bound_spans<'tcx>(
1556 bounds: &hir::GenericBounds<'_>,
1557 inferred_outlives: &[ty::Region<'tcx>],
1559 ) -> Vec<(usize, Span)> {
1560 use rustc::middle::resolve_lifetime::Region;
1565 .filter_map(|(i, bound)| {
1566 if let hir::GenericBound::Outlives(lifetime) = bound {
1567 let is_inferred = match tcx.named_region(lifetime.hir_id) {
1568 Some(Region::Static) if infer_static => inferred_outlives
1570 .any(|r| if let ty::ReStatic = r { true } else { false }),
1571 Some(Region::EarlyBound(index, ..)) => inferred_outlives.iter().any(|r| {
1572 if let ty::ReEarlyBound(ebr) = r { ebr.index == index } else { false }
1576 is_inferred.then_some((i, bound.span()))
1584 fn consolidate_outlives_bound_spans(
1587 bounds: &hir::GenericBounds<'_>,
1588 bound_spans: Vec<(usize, Span)>,
1590 if bounds.is_empty() {
1593 if bound_spans.len() == bounds.len() {
1594 let (_, last_bound_span) = bound_spans[bound_spans.len() - 1];
1595 // If all bounds are inferable, we want to delete the colon, so
1596 // start from just after the parameter (span passed as argument)
1597 vec![lo.to(last_bound_span)]
1599 let mut merged = Vec::new();
1600 let mut last_merged_i = None;
1602 let mut from_start = true;
1603 for (i, bound_span) in bound_spans {
1604 match last_merged_i {
1605 // If the first bound is inferable, our span should also eat the leading `+`.
1607 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
1608 last_merged_i = Some(0);
1610 // If consecutive bounds are inferable, merge their spans
1611 Some(h) if i == h + 1 => {
1612 if let Some(tail) = merged.last_mut() {
1613 // Also eat the trailing `+` if the first
1614 // more-than-one bound is inferable
1615 let to_span = if from_start && i < bounds.len() {
1616 bounds[i + 1].span().shrink_to_lo()
1620 *tail = tail.to(to_span);
1621 last_merged_i = Some(i);
1623 bug!("another bound-span visited earlier");
1627 // When we find a non-inferable bound, subsequent inferable bounds
1628 // won't be consecutive from the start (and we'll eat the leading
1629 // `+` rather than the trailing one)
1631 merged.push(bounds[i - 1].span().shrink_to_hi().to(bound_span));
1632 last_merged_i = Some(i);
1641 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitOutlivesRequirements {
1642 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
1643 use rustc::middle::resolve_lifetime::Region;
1645 let infer_static = cx.tcx.features().infer_static_outlives_requirements;
1646 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1647 if let hir::ItemKind::Struct(_, ref hir_generics)
1648 | hir::ItemKind::Enum(_, ref hir_generics)
1649 | hir::ItemKind::Union(_, ref hir_generics) = item.kind
1651 let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
1652 if inferred_outlives.is_empty() {
1656 let ty_generics = cx.tcx.generics_of(def_id);
1658 let mut bound_count = 0;
1659 let mut lint_spans = Vec::new();
1661 for param in hir_generics.params {
1662 let has_lifetime_bounds = param.bounds.iter().any(|bound| {
1663 if let hir::GenericBound::Outlives(_) = bound { true } else { false }
1665 if !has_lifetime_bounds {
1669 let relevant_lifetimes =
1670 self.collect_outlived_lifetimes(param, cx.tcx, inferred_outlives, ty_generics);
1671 if relevant_lifetimes.is_empty() {
1675 let bound_spans = self.collect_outlives_bound_spans(
1678 &relevant_lifetimes,
1681 bound_count += bound_spans.len();
1682 lint_spans.extend(self.consolidate_outlives_bound_spans(
1683 param.span.shrink_to_hi(),
1689 let mut where_lint_spans = Vec::new();
1690 let mut dropped_predicate_count = 0;
1691 let num_predicates = hir_generics.where_clause.predicates.len();
1692 for (i, where_predicate) in hir_generics.where_clause.predicates.iter().enumerate() {
1693 let (relevant_lifetimes, bounds, span) = match where_predicate {
1694 hir::WherePredicate::RegionPredicate(predicate) => {
1695 if let Some(Region::EarlyBound(index, ..)) =
1696 cx.tcx.named_region(predicate.lifetime.hir_id)
1699 Self::lifetimes_outliving_lifetime(inferred_outlives, index),
1707 hir::WherePredicate::BoundPredicate(predicate) => {
1708 // FIXME we can also infer bounds on associated types,
1709 // and should check for them here.
1710 match predicate.bounded_ty.kind {
1711 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1712 if let Res::Def(DefKind::TyParam, def_id) = path.res {
1713 let index = ty_generics.param_def_id_to_index[&def_id];
1715 Self::lifetimes_outliving_type(inferred_outlives, index),
1730 if relevant_lifetimes.is_empty() {
1734 let bound_spans = self.collect_outlives_bound_spans(
1737 &relevant_lifetimes,
1740 bound_count += bound_spans.len();
1742 let drop_predicate = bound_spans.len() == bounds.len();
1744 dropped_predicate_count += 1;
1747 // If all the bounds on a predicate were inferable and there are
1748 // further predicates, we want to eat the trailing comma.
1749 if drop_predicate && i + 1 < num_predicates {
1750 let next_predicate_span = hir_generics.where_clause.predicates[i + 1].span();
1751 where_lint_spans.push(span.to(next_predicate_span.shrink_to_lo()));
1753 where_lint_spans.extend(self.consolidate_outlives_bound_spans(
1754 span.shrink_to_lo(),
1761 // If all predicates are inferable, drop the entire clause
1762 // (including the `where`)
1763 if num_predicates > 0 && dropped_predicate_count == num_predicates {
1764 let where_span = hir_generics
1767 .expect("span of (nonempty) where clause should exist");
1768 // Extend the where clause back to the closing `>` of the
1769 // generics, except for tuple struct, which have the `where`
1770 // after the fields of the struct.
1771 let full_where_span =
1772 if let hir::ItemKind::Struct(hir::VariantData::Tuple(..), _) = item.kind {
1775 hir_generics.span.shrink_to_hi().to(where_span)
1777 lint_spans.push(full_where_span);
1779 lint_spans.extend(where_lint_spans);
1782 if !lint_spans.is_empty() {
1783 let mut err = cx.struct_span_lint(
1784 EXPLICIT_OUTLIVES_REQUIREMENTS,
1786 "outlives requirements can be inferred",
1788 err.multipart_suggestion(
1789 if bound_count == 1 { "remove this bound" } else { "remove these bounds" },
1790 lint_spans.into_iter().map(|span| (span, "".to_owned())).collect::<Vec<_>>(),
1791 Applicability::MachineApplicable,
1800 pub INCOMPLETE_FEATURES,
1802 "incomplete features that may function improperly in some or all cases"
1806 /// Check for used feature gates in `INCOMPLETE_FEATURES` in `librustc_feature/active.rs`.
1807 IncompleteFeatures => [INCOMPLETE_FEATURES]
1810 impl EarlyLintPass for IncompleteFeatures {
1811 fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
1812 let features = cx.sess.features_untracked();
1814 .declared_lang_features
1816 .map(|(name, span, _)| (name, span))
1817 .chain(features.declared_lib_features.iter().map(|(name, span)| (name, span)))
1818 .filter(|(name, _)| rustc_feature::INCOMPLETE_FEATURES.iter().any(|f| name == &f))
1819 .for_each(|(name, &span)| {
1820 cx.struct_span_lint(
1821 INCOMPLETE_FEATURES,
1824 "the feature `{}` is incomplete and may cause the compiler to crash",
1836 "an invalid value is being created (such as a NULL reference)"
1839 declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
1841 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidValue {
1842 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>) {
1843 #[derive(Debug, Copy, Clone, PartialEq)]
1849 /// Information about why a type cannot be initialized this way.
1850 /// Contains an error message and optionally a span to point at.
1851 type InitError = (String, Option<Span>);
1853 /// Test if this constant is all-0.
1854 fn is_zero(expr: &hir::Expr<'_>) -> bool {
1855 use hir::ExprKind::*;
1856 use syntax::ast::LitKind::*;
1859 if let Int(i, _) = lit.node {
1865 Tup(tup) => tup.iter().all(is_zero),
1870 /// Determine if this expression is a "dangerous initialization".
1871 fn is_dangerous_init(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) -> Option<InitKind> {
1872 // `transmute` is inside an anonymous module (the `extern` block?);
1873 // `Invalid` represents the empty string and matches that.
1874 // FIXME(#66075): use diagnostic items. Somehow, that does not seem to work
1875 // on intrinsics right now.
1876 const TRANSMUTE_PATH: &[Symbol] =
1877 &[sym::core, sym::intrinsics, kw::Invalid, sym::transmute];
1879 if let hir::ExprKind::Call(ref path_expr, ref args) = expr.kind {
1880 // Find calls to `mem::{uninitialized,zeroed}` methods.
1881 if let hir::ExprKind::Path(ref qpath) = path_expr.kind {
1882 let def_id = cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
1884 if cx.tcx.is_diagnostic_item(sym::mem_zeroed, def_id) {
1885 return Some(InitKind::Zeroed);
1886 } else if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, def_id) {
1887 return Some(InitKind::Uninit);
1888 } else if cx.match_def_path(def_id, TRANSMUTE_PATH) {
1889 if is_zero(&args[0]) {
1890 return Some(InitKind::Zeroed);
1894 } else if let hir::ExprKind::MethodCall(_, _, ref args) = expr.kind {
1895 // Find problematic calls to `MaybeUninit::assume_init`.
1896 let def_id = cx.tables.type_dependent_def_id(expr.hir_id)?;
1897 if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) {
1898 // This is a call to *some* method named `assume_init`.
1899 // See if the `self` parameter is one of the dangerous constructors.
1900 if let hir::ExprKind::Call(ref path_expr, _) = args[0].kind {
1901 if let hir::ExprKind::Path(ref qpath) = path_expr.kind {
1903 cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
1905 if cx.tcx.is_diagnostic_item(sym::maybe_uninit_zeroed, def_id) {
1906 return Some(InitKind::Zeroed);
1907 } else if cx.tcx.is_diagnostic_item(sym::maybe_uninit_uninit, def_id) {
1908 return Some(InitKind::Uninit);
1918 /// Return `Some` only if we are sure this type does *not*
1919 /// allow zero initialization.
1920 fn ty_find_init_error<'tcx>(
1924 ) -> Option<InitError> {
1925 use rustc::ty::TyKind::*;
1927 // Primitive types that don't like 0 as a value.
1928 Ref(..) => Some((format!("references must be non-null"), None)),
1929 Adt(..) if ty.is_box() => Some((format!("`Box` must be non-null"), None)),
1930 FnPtr(..) => Some((format!("function pointers must be non-null"), None)),
1931 Never => Some((format!("the `!` type has no valid value"), None)),
1932 RawPtr(tm) if matches!(tm.ty.kind, Dynamic(..)) =>
1933 // raw ptr to dyn Trait
1935 Some((format!("the vtable of a wide raw pointer must be non-null"), None))
1937 // Primitive types with other constraints.
1938 Bool if init == InitKind::Uninit => {
1939 Some((format!("booleans must be either `true` or `false`"), None))
1941 Char if init == InitKind::Uninit => {
1942 Some((format!("characters must be a valid Unicode codepoint"), None))
1944 // Recurse and checks for some compound types.
1945 Adt(adt_def, substs) if !adt_def.is_union() => {
1946 // First check f this ADT has a layout attribute (like `NonNull` and friends).
1947 use std::ops::Bound;
1948 match tcx.layout_scalar_valid_range(adt_def.did) {
1949 // We exploit here that `layout_scalar_valid_range` will never
1950 // return `Bound::Excluded`. (And we have tests checking that we
1951 // handle the attribute correctly.)
1952 (Bound::Included(lo), _) if lo > 0 => {
1953 return Some((format!("`{}` must be non-null", ty), None));
1955 (Bound::Included(_), _) | (_, Bound::Included(_))
1956 if init == InitKind::Uninit =>
1960 "`{}` must be initialized inside its custom valid range",
1969 match adt_def.variants.len() {
1970 0 => Some((format!("enums with no variants have no valid value"), None)),
1972 // Struct, or enum with exactly one variant.
1973 // Proceed recursively, check all fields.
1974 let variant = &adt_def.variants[VariantIdx::from_u32(0)];
1975 variant.fields.iter().find_map(|field| {
1976 ty_find_init_error(tcx, field.ty(tcx, substs), init).map(
1979 // Point to this field, should be helpful for figuring
1980 // out where the source of the error is.
1981 let span = tcx.def_span(field.did);
1984 " (in this {} field)",
1997 // Multi-variant enums are tricky: if all but one variant are
1998 // uninhabited, we might actually do layout like for a single-variant
1999 // enum, and then even leaving them uninitialized could be okay.
2000 _ => None, // Conservative fallback for multi-variant enum.
2004 // Proceed recursively, check all fields.
2005 ty.tuple_fields().find_map(|field| ty_find_init_error(tcx, field, init))
2007 // Conservative fallback.
2012 if let Some(init) = is_dangerous_init(cx, expr) {
2013 // This conjures an instance of a type out of nothing,
2014 // using zeroed or uninitialized memory.
2015 // We are extremely conservative with what we warn about.
2016 let conjured_ty = cx.tables.expr_ty(expr);
2017 if let Some((msg, span)) = ty_find_init_error(cx.tcx, conjured_ty, init) {
2018 let mut err = cx.struct_span_lint(
2022 "the type `{}` does not permit {}",
2025 InitKind::Zeroed => "zero-initialization",
2026 InitKind::Uninit => "being left uninitialized",
2030 err.span_label(expr.span, "this code causes undefined behavior when executed");
2033 "help: use `MaybeUninit<T>` instead, \
2034 and only call `assume_init` after initialization is done",
2036 if let Some(span) = span {
2037 err.span_note(span, &msg);