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 rustc::hir::def::{Res, DefKind};
25 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
26 use rustc::ty::{self, Ty, TyCtxt, layout::VariantIdx};
27 use rustc::{lint, util};
29 use util::nodemap::HirIdSet;
30 use lint::{LateContext, LintContext, LintArray};
31 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
33 use rustc::util::nodemap::FxHashSet;
35 use syntax::tokenstream::{TokenTree, TokenStream};
36 use syntax::ast::{self, Expr};
38 use syntax::attr::{self, HasAttrs, AttributeTemplate};
39 use syntax::source_map::Spanned;
40 use syntax::edition::Edition;
41 use syntax::feature_gate::{self, AttributeGate, AttributeType};
42 use syntax::feature_gate::{Stability, deprecated_attributes};
43 use syntax_pos::{BytePos, Span, SyntaxContext};
44 use syntax::symbol::{Symbol, kw, sym};
45 use syntax::errors::{Applicability, DiagnosticBuilder};
46 use syntax::print::pprust::expr_to_string;
47 use syntax::visit::FnKind;
49 use rustc::hir::{self, GenericParamKind, PatKind};
51 use crate::nonstandard_style::{MethodLateContext, method_context};
55 // hardwired lints from librustc
56 pub use lint::builtin::*;
61 "suggest using `loop { }` instead of `while true { }`"
64 declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
66 /// Traverse through any amount of parenthesis and return the first non-parens expression.
67 fn pierce_parens(mut expr: &ast::Expr) -> &ast::Expr {
68 while let ast::ExprKind::Paren(sub) = &expr.node {
74 impl EarlyLintPass for WhileTrue {
75 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
76 if let ast::ExprKind::While(cond, ..) = &e.node {
77 if let ast::ExprKind::Lit(ref lit) = pierce_parens(cond).node {
78 if let ast::LitKind::Bool(true) = lit.node {
79 if lit.span.ctxt() == SyntaxContext::empty() {
80 let msg = "denote infinite loops with `loop { ... }`";
81 let condition_span = cx.sess.source_map().def_span(e.span);
82 cx.struct_span_lint(WHILE_TRUE, condition_span, msg)
83 .span_suggestion_short(
87 Applicability::MachineApplicable
100 "use of owned (Box type) heap memory"
103 declare_lint_pass!(BoxPointers => [BOX_POINTERS]);
106 fn check_heap_type(&self, cx: &LateContext<'_, '_>, span: Span, ty: Ty<'_>) {
107 for leaf_ty in ty.walk() {
108 if leaf_ty.is_box() {
109 let m = format!("type uses owned (Box type) pointers: {}", ty);
110 cx.span_lint(BOX_POINTERS, span, &m);
116 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
117 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
119 hir::ItemKind::Fn(..) |
120 hir::ItemKind::TyAlias(..) |
121 hir::ItemKind::Enum(..) |
122 hir::ItemKind::Struct(..) |
123 hir::ItemKind::Union(..) => {
124 let def_id = cx.tcx.hir().local_def_id(it.hir_id);
125 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
130 // If it's a struct, we also have to check the fields' types
132 hir::ItemKind::Struct(ref struct_def, _) |
133 hir::ItemKind::Union(ref struct_def, _) => {
134 for struct_field in struct_def.fields() {
135 let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id);
136 self.check_heap_type(cx, struct_field.span,
137 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, ref field_pats, _) = pat.node {
161 let variant = cx.tables.pat_ty(pat).ty_adt_def()
162 .expect("struct pattern type is not an ADT")
163 .variant_of_res(cx.tables.qpath_res(qpath, pat.hir_id));
164 for fieldpat in field_pats {
165 if fieldpat.node.is_shorthand {
168 if fieldpat.span.ctxt().outer_expn_info().is_some() {
169 // Don't lint if this is a macro expansion: macro authors
170 // shouldn't have to worry about this kind of style issue
174 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
175 if cx.tcx.find_field_index(ident, &variant) ==
176 Some(cx.tcx.field_index(fieldpat.node.hir_id, cx.tables)) {
177 let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
179 &format!("the `{}:` in this pattern is redundant", ident));
180 let subspan = cx.tcx.sess.source_map().span_through_char(fieldpat.span,
182 err.span_suggestion_short(
186 Applicability::MachineApplicable
199 "usage of `unsafe` code"
202 declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
205 fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) {
206 // This comes from a macro that has `#[allow_internal_unsafe]`.
207 if span.allows_unsafe() {
211 cx.span_lint(UNSAFE_CODE, span, desc);
215 impl EarlyLintPass for UnsafeCode {
216 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
217 if attr.check_name(sym::allow_internal_unsafe) {
218 self.report_unsafe(cx, attr.span, "`allow_internal_unsafe` allows defining \
219 macros using unsafe without triggering \
220 the `unsafe_code` lint at their call site");
224 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
225 if let ast::ExprKind::Block(ref blk, _) = e.node {
226 // Don't warn about generated blocks; that'll just pollute the output.
227 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
228 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
233 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
235 ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => {
236 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
239 ast::ItemKind::Impl(ast::Unsafety::Unsafe, ..) => {
240 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
247 fn check_fn(&mut self,
248 cx: &EarlyContext<'_>,
254 FnKind::ItemFn(_, ast::FnHeader { unsafety: ast::Unsafety::Unsafe, .. }, ..) => {
255 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
258 FnKind::Method(_, sig, ..) => {
259 if sig.header.unsafety == ast::Unsafety::Unsafe {
260 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
268 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, item: &ast::TraitItem) {
269 if let ast::TraitItemKind::Method(ref sig, None) = item.node {
270 if sig.header.unsafety == ast::Unsafety::Unsafe {
271 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
280 "detects missing documentation for public members",
281 report_in_external_macro: true
284 pub struct MissingDoc {
285 /// Stack of whether `#[doc(hidden)]` is set at each level which has lint attributes.
286 doc_hidden_stack: Vec<bool>,
288 /// Private traits or trait items that leaked through. Don't check their methods.
289 private_traits: FxHashSet<hir::HirId>,
292 impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
294 fn has_doc(attr: &ast::Attribute) -> bool {
295 if !attr.check_name(sym::doc) {
299 if attr.is_value_str() {
303 if let Some(list) = attr.meta_item_list() {
305 if meta.check_name(sym::include) || meta.check_name(sym::hidden) {
315 pub fn new() -> MissingDoc {
317 doc_hidden_stack: vec![false],
318 private_traits: FxHashSet::default(),
322 fn doc_hidden(&self) -> bool {
323 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
326 fn check_missing_docs_attrs(&self,
327 cx: &LateContext<'_, '_>,
328 id: Option<hir::HirId>,
329 attrs: &[ast::Attribute],
331 desc: &'static str) {
332 // If we're building a test harness, then warning about
333 // documentation is probably not really relevant right now.
334 if cx.sess().opts.test {
338 // `#[doc(hidden)]` disables missing_docs check.
339 if self.doc_hidden() {
343 // Only check publicly-visible items, using the result from the privacy pass.
344 // It's an option so the crate root can also use this function (it doesn't
346 if let Some(id) = id {
347 if !cx.access_levels.is_exported(id) {
352 let has_doc = attrs.iter().any(|a| has_doc(a));
354 cx.span_lint(MISSING_DOCS,
355 cx.tcx.sess.source_map().def_span(sp),
356 &format!("missing documentation for {}", desc));
361 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
362 fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) {
363 let doc_hidden = self.doc_hidden() ||
364 attrs.iter().any(|attr| {
365 attr.check_name(sym::doc) &&
366 match attr.meta_item_list() {
368 Some(l) => attr::list_contains_name(&l, sym::hidden),
371 self.doc_hidden_stack.push(doc_hidden);
374 fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) {
375 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
378 fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate) {
379 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
381 for macro_def in &krate.exported_macros {
382 let has_doc = macro_def.attrs.iter().any(|a| has_doc(a));
384 cx.span_lint(MISSING_DOCS,
385 cx.tcx.sess.source_map().def_span(macro_def.span),
386 "missing documentation for macro");
391 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
392 let desc = match it.node {
393 hir::ItemKind::Fn(..) => "a function",
394 hir::ItemKind::Mod(..) => "a module",
395 hir::ItemKind::Enum(..) => "an enum",
396 hir::ItemKind::Struct(..) => "a struct",
397 hir::ItemKind::Union(..) => "a union",
398 hir::ItemKind::Trait(.., ref trait_item_refs) => {
399 // Issue #11592: traits are always considered exported, even when private.
400 if let hir::VisibilityKind::Inherited = it.vis.node {
401 self.private_traits.insert(it.hir_id);
402 for trait_item_ref in trait_item_refs {
403 self.private_traits.insert(trait_item_ref.id.hir_id);
409 hir::ItemKind::TyAlias(..) => "a type alias",
410 hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
411 // If the trait is private, add the impl items to `private_traits` so they don't get
412 // reported for missing docs.
413 let real_trait = trait_ref.path.res.def_id();
414 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(real_trait) {
415 match cx.tcx.hir().find(hir_id) {
416 Some(Node::Item(item)) => {
417 if let hir::VisibilityKind::Inherited = item.vis.node {
418 for impl_item_ref in impl_item_refs {
419 self.private_traits.insert(impl_item_ref.id.hir_id);
428 hir::ItemKind::Const(..) => "a constant",
429 hir::ItemKind::Static(..) => "a static",
433 self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, desc);
436 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem) {
437 if self.private_traits.contains(&trait_item.hir_id) {
441 let desc = match trait_item.node {
442 hir::TraitItemKind::Const(..) => "an associated constant",
443 hir::TraitItemKind::Method(..) => "a trait method",
444 hir::TraitItemKind::Type(..) => "an associated type",
447 self.check_missing_docs_attrs(cx,
448 Some(trait_item.hir_id),
454 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
455 // If the method is an impl for a trait, don't doc.
456 if method_context(cx, impl_item.hir_id) == MethodLateContext::TraitImpl {
460 let desc = match impl_item.node {
461 hir::ImplItemKind::Const(..) => "an associated constant",
462 hir::ImplItemKind::Method(..) => "a method",
463 hir::ImplItemKind::TyAlias(_) => "an associated type",
464 hir::ImplItemKind::OpaqueTy(_) => "an associated `impl Trait` type",
466 self.check_missing_docs_attrs(cx,
467 Some(impl_item.hir_id),
473 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField) {
474 if !sf.is_positional() {
475 self.check_missing_docs_attrs(cx,
483 fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant, _: &hir::Generics) {
484 self.check_missing_docs_attrs(cx,
493 pub MISSING_COPY_IMPLEMENTATIONS,
495 "detects potentially-forgotten implementations of `Copy`"
498 declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
500 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
501 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
502 if !cx.access_levels.is_reachable(item.hir_id) {
505 let (def, ty) = match item.node {
506 hir::ItemKind::Struct(_, ref ast_generics) => {
507 if !ast_generics.params.is_empty() {
510 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
511 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
513 hir::ItemKind::Union(_, ref ast_generics) => {
514 if !ast_generics.params.is_empty() {
517 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
518 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
520 hir::ItemKind::Enum(_, ref ast_generics) => {
521 if !ast_generics.params.is_empty() {
524 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
525 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
529 if def.has_dtor(cx.tcx) {
532 let param_env = ty::ParamEnv::empty();
533 if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span) {
536 if param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
537 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
539 "type could implement `Copy`; consider adding `impl \
546 MISSING_DEBUG_IMPLEMENTATIONS,
548 "detects missing implementations of fmt::Debug"
552 pub struct MissingDebugImplementations {
553 impling_types: Option<HirIdSet>,
556 impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
558 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
559 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
560 if !cx.access_levels.is_reachable(item.hir_id) {
565 hir::ItemKind::Struct(..) |
566 hir::ItemKind::Union(..) |
567 hir::ItemKind::Enum(..) => {}
571 let debug = match cx.tcx.lang_items().debug_trait() {
572 Some(debug) => debug,
576 if self.impling_types.is_none() {
577 let mut impls = HirIdSet::default();
578 cx.tcx.for_each_impl(debug, |d| {
579 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
580 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
581 impls.insert(hir_id);
586 self.impling_types = Some(impls);
587 debug!("{:?}", self.impling_types);
590 if !self.impling_types.as_ref().unwrap().contains(&item.hir_id) {
591 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
593 "type does not implement `fmt::Debug`; consider adding `#[derive(Debug)]` \
594 or a manual implementation")
600 pub ANONYMOUS_PARAMETERS,
602 "detects anonymous parameters"
606 /// Checks for use of anonymous parameters (RFC 1685).
607 AnonymousParameters => [ANONYMOUS_PARAMETERS]
610 impl EarlyLintPass for AnonymousParameters {
611 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::TraitItem) {
613 ast::TraitItemKind::Method(ref sig, _) => {
614 for arg in sig.decl.inputs.iter() {
616 ast::PatKind::Ident(_, ident, None) => {
617 if ident.name == kw::Invalid {
621 .span_to_snippet(arg.ty.span);
623 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
624 (snip, Applicability::MachineApplicable)
626 ("<type>".to_owned(), Applicability::HasPlaceholders)
630 ANONYMOUS_PARAMETERS,
632 "anonymous parameters are deprecated and will be \
633 removed in the next edition."
636 "Try naming the parameter or explicitly \
638 format!("_: {}", ty_snip),
652 /// Check for use of attributes which have been deprecated.
654 pub struct DeprecatedAttr {
655 // This is not free to compute, so we want to keep it around, rather than
656 // compute it for every attribute.
657 depr_attrs: Vec<&'static (Symbol, AttributeType, AttributeTemplate, AttributeGate)>,
660 impl_lint_pass!(DeprecatedAttr => []);
662 impl DeprecatedAttr {
663 pub fn new() -> DeprecatedAttr {
665 depr_attrs: deprecated_attributes(),
670 impl EarlyLintPass for DeprecatedAttr {
671 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
672 for &&(n, _, _, ref g) in &self.depr_attrs {
673 if attr.ident().map(|ident| ident.name) == Some(n) {
674 if let &AttributeGate::Gated(Stability::Deprecated(link, suggestion),
678 let msg = format!("use of deprecated attribute `{}`: {}. See {}",
680 let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
681 err.span_suggestion_short(
683 suggestion.unwrap_or("remove this attribute"),
685 Applicability::MachineApplicable
696 pub UNUSED_DOC_COMMENTS,
698 "detects doc comments that aren't used by rustdoc"
701 declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]);
703 impl UnusedDocComment {
706 cx: &EarlyContext<'_>,
709 is_macro_expansion: bool,
710 attrs: &[ast::Attribute]
712 let mut attrs = attrs.into_iter().peekable();
714 // Accumulate a single span for sugared doc comments.
715 let mut sugared_span: Option<Span> = None;
717 while let Some(attr) = attrs.next() {
718 if attr.is_sugared_doc {
720 sugared_span.map_or_else(
722 |span| span.with_hi(attr.span.hi()),
727 if attrs.peek().map(|next_attr| next_attr.is_sugared_doc).unwrap_or_default() {
731 let span = sugared_span.take().unwrap_or_else(|| attr.span);
733 if attr.check_name(sym::doc) {
734 let mut err = cx.struct_span_lint(UNUSED_DOC_COMMENTS, span, "unused doc comment");
738 format!("rustdoc does not generate documentation for {}", node_kind)
741 if is_macro_expansion {
742 err.help("to document an item produced by a macro, \
743 the macro must produce the documentation as part of its expansion");
752 impl EarlyLintPass for UnusedDocComment {
753 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
754 if let ast::ItemKind::Mac(..) = item.node {
755 self.warn_if_doc(cx, item.span, "macro expansions", true, &item.attrs);
759 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
760 let (kind, is_macro_expansion) = match stmt.node {
761 ast::StmtKind::Local(..) => ("statements", false),
762 ast::StmtKind::Item(..) => ("inner items", false),
763 ast::StmtKind::Mac(..) => ("macro expansions", true),
764 // expressions will be reported by `check_expr`.
765 ast::StmtKind::Semi(..) |
766 ast::StmtKind::Expr(..) => return,
769 self.warn_if_doc(cx, stmt.span, kind, is_macro_expansion, stmt.node.attrs());
772 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
773 let arm_span = arm.pats[0].span.with_hi(arm.body.span.hi());
774 self.warn_if_doc(cx, arm_span, "match arms", false, &arm.attrs);
777 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
778 self.warn_if_doc(cx, expr.span, "expressions", false, &expr.attrs);
785 "compiler plugin used as ordinary library in non-plugin crate"
788 declare_lint_pass!(PluginAsLibrary => [PLUGIN_AS_LIBRARY]);
790 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
791 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
792 if cx.tcx.plugin_registrar_fn(LOCAL_CRATE).is_some() {
793 // We're compiling a plugin; it's fine to link other plugins.
798 hir::ItemKind::ExternCrate(..) => (),
802 let def_id = cx.tcx.hir().local_def_id(it.hir_id);
803 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
804 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
806 // Probably means we aren't linking the crate for some reason.
808 // Not sure if / when this could happen.
814 cx.span_lint(PLUGIN_AS_LIBRARY,
816 "compiler plugin used as an ordinary library");
822 NO_MANGLE_CONST_ITEMS,
824 "const items will not have their symbols exported"
828 NO_MANGLE_GENERIC_ITEMS,
830 "generic items must be mangled"
833 declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
835 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
836 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
838 hir::ItemKind::Fn(.., ref generics, _) => {
839 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
840 for param in &generics.params {
842 GenericParamKind::Lifetime { .. } => {}
843 GenericParamKind::Type { .. } |
844 GenericParamKind::Const { .. } => {
845 let mut err = cx.struct_span_lint(
846 NO_MANGLE_GENERIC_ITEMS,
848 "functions generic over types or consts must be mangled",
850 err.span_suggestion_short(
852 "remove this attribute",
854 // Use of `#[no_mangle]` suggests FFI intent; correct
855 // fix may be to monomorphize source by hand
856 Applicability::MaybeIncorrect
865 hir::ItemKind::Const(..) => {
866 if attr::contains_name(&it.attrs, sym::no_mangle) {
867 // Const items do not refer to a particular location in memory, and therefore
868 // don't have anything to attach a symbol to
869 let msg = "const items should never be `#[no_mangle]`";
870 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
872 // account for "pub const" (#45562)
873 let start = cx.tcx.sess.source_map().span_to_snippet(it.span)
874 .map(|snippet| snippet.find("const").unwrap_or(0))
875 .unwrap_or(0) as u32;
876 // `const` is 5 chars
877 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
880 "try a static value",
881 "pub static".to_owned(),
882 Applicability::MachineApplicable
895 "mutating transmuted &mut T from &T may cause undefined behavior"
898 declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
900 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
901 fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr) {
902 use rustc_target::spec::abi::Abi::RustIntrinsic;
904 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
905 consider instead using an UnsafeCell";
906 match get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (&ty1.sty, &ty2.sty)) {
907 Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
908 if to_mt == hir::Mutability::MutMutable &&
909 from_mt == hir::Mutability::MutImmutable {
910 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
916 fn get_transmute_from_to<'a, 'tcx>
917 (cx: &LateContext<'a, 'tcx>,
919 -> Option<(Ty<'tcx>, Ty<'tcx>)> {
920 let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
921 cx.tables.qpath_res(qpath, expr.hir_id)
925 if let Res::Def(DefKind::Fn, did) = def {
926 if !def_id_is_transmute(cx, did) {
929 let sig = cx.tables.node_type(expr.hir_id).fn_sig(cx.tcx);
930 let from = sig.inputs().skip_binder()[0];
931 let to = *sig.output().skip_binder();
932 return Some((from, to));
937 fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
938 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
939 cx.tcx.item_name(def_id) == sym::transmute
947 "enabling unstable features (deprecated. do not use)"
951 /// Forbids using the `#[feature(...)]` attribute
952 UnstableFeatures => [UNSTABLE_FEATURES]
955 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
956 fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) {
957 if attr.check_name(sym::feature) {
958 if let Some(items) = attr.meta_item_list() {
960 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
968 UNIONS_WITH_DROP_FIELDS,
970 "use of unions that contain fields with possibly non-trivial drop code"
974 /// Lint for unions that contain fields with possibly non-trivial destructors.
975 UnionsWithDropFields => [UNIONS_WITH_DROP_FIELDS]
978 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
979 fn check_item(&mut self, ctx: &LateContext<'_, '_>, item: &hir::Item) {
980 if let hir::ItemKind::Union(ref vdata, _) = item.node {
981 for field in vdata.fields() {
982 let field_ty = ctx.tcx.type_of(
983 ctx.tcx.hir().local_def_id(field.hir_id));
984 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
985 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
987 "union contains a field with possibly non-trivial drop code, \
988 drop code of union fields is ignored when dropping the union");
999 "`pub` items not reachable from crate root"
1003 /// Lint for items marked `pub` that aren't reachable from other crates.
1004 UnreachablePub => [UNREACHABLE_PUB]
1007 impl UnreachablePub {
1008 fn perform_lint(&self, cx: &LateContext<'_, '_>, what: &str, id: hir::HirId,
1009 vis: &hir::Visibility, span: Span, exportable: bool) {
1010 let mut applicability = Applicability::MachineApplicable;
1012 hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
1013 if span.ctxt().outer_expn_info().is_some() {
1014 applicability = Applicability::MaybeIncorrect;
1016 let def_span = cx.tcx.sess.source_map().def_span(span);
1017 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1018 &format!("unreachable `pub` {}", what));
1019 let replacement = if cx.tcx.features().crate_visibility_modifier {
1025 err.span_suggestion(
1027 "consider restricting its visibility",
1032 err.help("or consider exporting it for use by other crates");
1041 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1042 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1043 self.perform_lint(cx, "item", item.hir_id, &item.vis, item.span, true);
1046 fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, foreign_item: &hir::ForeignItem) {
1047 self.perform_lint(cx, "item", foreign_item.hir_id, &foreign_item.vis,
1048 foreign_item.span, true);
1051 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) {
1052 self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false);
1055 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
1056 self.perform_lint(cx, "item", impl_item.hir_id, &impl_item.vis, impl_item.span, false);
1063 "bounds in type aliases are not enforced"
1067 /// Lint for trait and lifetime bounds in type aliases being mostly ignored.
1068 /// They are relevant when using associated types, but otherwise neither checked
1069 /// at definition site nor enforced at use site.
1070 TypeAliasBounds => [TYPE_ALIAS_BOUNDS]
1073 impl TypeAliasBounds {
1074 fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1076 hir::QPath::TypeRelative(ref ty, _) => {
1077 // If this is a type variable, we found a `T::Assoc`.
1079 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1081 Res::Def(DefKind::TyParam, _) => true,
1088 hir::QPath::Resolved(..) => false,
1092 fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder<'_>) {
1093 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1094 // bound. Let's see if this type does that.
1096 // We use a HIR visitor to walk the type.
1097 use rustc::hir::intravisit::{self, Visitor};
1098 struct WalkAssocTypes<'a, 'db> {
1099 err: &'a mut DiagnosticBuilder<'db>
1101 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1102 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1104 intravisit::NestedVisitorMap::None
1107 fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: hir::HirId, span: Span) {
1108 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1109 self.err.span_help(span,
1110 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1111 associated types in type aliases");
1113 intravisit::walk_qpath(self, qpath, id, span)
1117 // Let's go for a walk!
1118 let mut visitor = WalkAssocTypes { err };
1119 visitor.visit_ty(ty);
1123 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1124 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1125 let (ty, type_alias_generics) = match item.node {
1126 hir::ItemKind::TyAlias(ref ty, ref generics) => (&*ty, generics),
1129 let mut suggested_changing_assoc_types = false;
1130 // There must not be a where clause
1131 if !type_alias_generics.where_clause.predicates.is_empty() {
1132 let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1133 .map(|pred| pred.span()).collect();
1134 let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1135 "where clauses are not enforced in type aliases");
1136 err.help("the clause will not be checked when the type alias is used, \
1137 and should be removed");
1138 if !suggested_changing_assoc_types {
1139 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1140 suggested_changing_assoc_types = true;
1144 // The parameters must not have bounds
1145 for param in type_alias_generics.params.iter() {
1146 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1147 if !spans.is_empty() {
1148 let mut err = cx.struct_span_lint(
1151 "bounds on generic parameters are not enforced in type aliases",
1153 err.help("the bound will not be checked when the type alias is used, \
1154 and should be removed");
1155 if !suggested_changing_assoc_types {
1156 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1157 suggested_changing_assoc_types = true;
1166 /// Lint constants that are erroneous.
1167 /// Without this lint, we might not get any diagnostic if the constant is
1168 /// unused within this crate, even though downstream crates can't use it
1169 /// without producing an error.
1170 UnusedBrokenConst => []
1173 fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) {
1174 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
1175 let param_env = if cx.tcx.is_static(def_id) {
1176 // Use the same param_env as `codegen_static_initializer`, to reuse the cache.
1177 ty::ParamEnv::reveal_all()
1179 cx.tcx.param_env(def_id)
1181 let cid = ::rustc::mir::interpret::GlobalId {
1182 instance: ty::Instance::mono(cx.tcx, def_id),
1185 // trigger the query once for all constants since that will already report the errors
1186 // FIXME: Use ensure here
1187 let _ = cx.tcx.const_eval(param_env.and(cid));
1190 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1191 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1193 hir::ItemKind::Const(_, body_id) => {
1194 check_const(cx, body_id);
1196 hir::ItemKind::Static(_, _, body_id) => {
1197 check_const(cx, body_id);
1207 "these bounds don't depend on an type parameters"
1211 /// Lint for trait and lifetime bounds that don't depend on type parameters
1212 /// which either do nothing, or stop the item from being used.
1213 TrivialConstraints => [TRIVIAL_BOUNDS]
1216 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1219 cx: &LateContext<'a, 'tcx>,
1220 item: &'tcx hir::Item,
1222 use rustc::ty::fold::TypeFoldable;
1223 use rustc::ty::Predicate::*;
1225 if cx.tcx.features().trivial_bounds {
1226 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1227 let predicates = cx.tcx.predicates_of(def_id);
1228 for &(predicate, span) in &predicates.predicates {
1229 let predicate_kind_name = match predicate {
1230 Trait(..) => "Trait",
1232 RegionOutlives(..) => "Lifetime",
1234 // Ignore projections, as they can only be global
1235 // if the trait bound is global
1237 // Ignore bounds that a user can't type
1242 ConstEvaluatable(..) => continue,
1244 if predicate.is_global() {
1248 &format!("{} bound {} does not depend on any type \
1249 or lifetime parameters", predicate_kind_name, predicate),
1258 /// Does nothing as a lint pass, but registers some `Lint`s
1259 /// which are used by other parts of the compiler.
1263 NON_SHORTHAND_FIELD_PATTERNS,
1266 MISSING_COPY_IMPLEMENTATIONS,
1267 MISSING_DEBUG_IMPLEMENTATIONS,
1268 ANONYMOUS_PARAMETERS,
1269 UNUSED_DOC_COMMENTS,
1271 NO_MANGLE_CONST_ITEMS,
1272 NO_MANGLE_GENERIC_ITEMS,
1275 UNIONS_WITH_DROP_FIELDS,
1283 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1285 "`...` range patterns are deprecated"
1289 pub struct EllipsisInclusiveRangePatterns {
1290 /// If `Some(_)`, suppress all subsequent pattern
1291 /// warnings for better diagnostics.
1292 node_id: Option<ast::NodeId>,
1295 impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1297 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1298 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1299 if self.node_id.is_some() {
1300 // Don't recursively warn about patterns inside range endpoints.
1304 use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot};
1306 /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1307 /// corresponding to the ellipsis.
1308 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(&P<Expr>, &P<Expr>, Span)> {
1310 PatKind::Range(a, b, Spanned { span, node: RangeEnd::Included(DotDotDot), .. }) => {
1317 let (parenthesise, endpoints) = match &pat.node {
1318 PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)),
1319 _ => (false, matches_ellipsis_pat(pat)),
1322 if let Some((start, end, join)) = endpoints {
1323 let msg = "`...` range patterns are deprecated";
1324 let suggestion = "use `..=` for an inclusive range";
1326 self.node_id = Some(pat.id);
1327 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, pat.span, msg);
1328 err.span_suggestion(
1331 format!("&({}..={})", expr_to_string(&start), expr_to_string(&end)),
1332 Applicability::MachineApplicable,
1336 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, join, msg);
1337 err.span_suggestion_short(
1341 Applicability::MachineApplicable,
1348 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1349 if let Some(node_id) = self.node_id {
1350 if pat.id == node_id {
1358 UNNAMEABLE_TEST_ITEMS,
1360 "detects an item that cannot be named being marked as `#[test_case]`",
1361 report_in_external_macro: true
1364 pub struct UnnameableTestItems {
1365 boundary: hir::HirId, // HirId of the item under which things are not nameable
1366 items_nameable: bool,
1369 impl_lint_pass!(UnnameableTestItems => [UNNAMEABLE_TEST_ITEMS]);
1371 impl UnnameableTestItems {
1372 pub fn new() -> Self {
1374 boundary: hir::DUMMY_HIR_ID,
1375 items_nameable: true
1380 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
1381 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1382 if self.items_nameable {
1383 if let hir::ItemKind::Mod(..) = it.node {}
1385 self.items_nameable = false;
1386 self.boundary = it.hir_id;
1391 if let Some(attr) = attr::find_by_name(&it.attrs, sym::rustc_test_marker) {
1392 cx.struct_span_lint(
1393 UNNAMEABLE_TEST_ITEMS,
1395 "cannot test inner items",
1400 fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item) {
1401 if !self.items_nameable && self.boundary == it.hir_id {
1402 self.items_nameable = true;
1410 "detects edition keywords being used as an identifier"
1414 /// Check for uses of edition keywords used as an identifier.
1415 KeywordIdents => [KEYWORD_IDENTS]
1418 struct UnderMacro(bool);
1420 impl KeywordIdents {
1421 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) {
1422 for tt in tokens.into_trees() {
1424 // Only report non-raw idents.
1425 TokenTree::Token(token) => if let Some((ident, false)) = token.ident() {
1426 self.check_ident_token(cx, UnderMacro(true), ident);
1428 TokenTree::Delimited(_, _, tts) => {
1429 self.check_tokens(cx, tts)
1435 fn check_ident_token(&mut self,
1436 cx: &EarlyContext<'_>,
1437 UnderMacro(under_macro): UnderMacro,
1440 let next_edition = match cx.sess.edition() {
1441 Edition::Edition2015 => {
1443 kw::Async | kw::Await | kw::Try => Edition::Edition2018,
1445 // rust-lang/rust#56327: Conservatively do not
1446 // attempt to report occurrences of `dyn` within
1447 // macro definitions or invocations, because `dyn`
1448 // can legitimately occur as a contextual keyword
1449 // in 2015 code denoting its 2018 meaning, and we
1450 // do not want rustfix to inject bugs into working
1451 // code by rewriting such occurrences.
1453 // But if we see `dyn` outside of a macro, we know
1454 // its precise role in the parsed AST and thus are
1455 // assured this is truly an attempt to use it as
1457 kw::Dyn if !under_macro => Edition::Edition2018,
1463 // There are no new keywords yet for the 2018 edition and beyond.
1467 // Don't lint `r#foo`.
1468 if cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span) {
1472 let mut lint = cx.struct_span_lint(
1475 &format!("`{}` is a keyword in the {} edition",
1479 lint.span_suggestion(
1481 "you can use a raw identifier to stay compatible",
1482 format!("r#{}", ident.as_str()),
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.stream());
1493 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
1494 self.check_tokens(cx, mac.node.tts.clone().into());
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>],
1507 ) -> Vec<ty::Region<'tcx>> {
1508 inferred_outlives.iter().filter_map(|pred| {
1510 ty::Predicate::RegionOutlives(outlives) => {
1511 let outlives = outlives.skip_binder();
1513 ty::ReEarlyBound(ebr) if ebr.index == index => {
1524 fn lifetimes_outliving_type<'tcx>(
1525 inferred_outlives: &'tcx [ty::Predicate<'tcx>],
1527 ) -> Vec<ty::Region<'tcx>> {
1528 inferred_outlives.iter().filter_map(|pred| {
1530 ty::Predicate::TypeOutlives(outlives) => {
1531 let outlives = outlives.skip_binder();
1532 if outlives.0.is_param(index) {
1543 fn collect_outlived_lifetimes<'tcx>(
1545 param: &'tcx hir::GenericParam,
1547 inferred_outlives: &'tcx [ty::Predicate<'tcx>],
1548 ty_generics: &'tcx ty::Generics,
1549 ) -> Vec<ty::Region<'tcx>> {
1550 let index = ty_generics.param_def_id_to_index[
1551 &tcx.hir().local_def_id(param.hir_id)];
1554 hir::GenericParamKind::Lifetime { .. } => {
1555 Self::lifetimes_outliving_lifetime(inferred_outlives, index)
1557 hir::GenericParamKind::Type { .. } => {
1558 Self::lifetimes_outliving_type(inferred_outlives, index)
1560 hir::GenericParamKind::Const { .. } => Vec::new(),
1565 fn collect_outlives_bound_spans<'tcx>(
1568 bounds: &hir::GenericBounds,
1569 inferred_outlives: &[ty::Region<'tcx>],
1571 ) -> Vec<(usize, Span)> {
1572 use rustc::middle::resolve_lifetime::Region;
1577 .filter_map(|(i, bound)| {
1578 if let hir::GenericBound::Outlives(lifetime) = bound {
1579 let is_inferred = match tcx.named_region(lifetime.hir_id) {
1580 Some(Region::Static) if infer_static => {
1581 inferred_outlives.iter()
1582 .any(|r| if let ty::ReStatic = r { true } else { false })
1584 Some(Region::EarlyBound(index, ..)) => inferred_outlives
1587 if let ty::ReEarlyBound(ebr) = r {
1596 Some((i, bound.span()))
1607 fn consolidate_outlives_bound_spans(
1610 bounds: &hir::GenericBounds,
1611 bound_spans: Vec<(usize, Span)>
1613 if bounds.is_empty() {
1616 if bound_spans.len() == bounds.len() {
1617 let (_, last_bound_span) = bound_spans[bound_spans.len()-1];
1618 // If all bounds are inferable, we want to delete the colon, so
1619 // start from just after the parameter (span passed as argument)
1620 vec![lo.to(last_bound_span)]
1622 let mut merged = Vec::new();
1623 let mut last_merged_i = None;
1625 let mut from_start = true;
1626 for (i, bound_span) in bound_spans {
1627 match last_merged_i {
1628 // If the first bound is inferable, our span should also eat the leading `+`.
1630 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
1631 last_merged_i = Some(0);
1633 // If consecutive bounds are inferable, merge their spans
1634 Some(h) if i == h+1 => {
1635 if let Some(tail) = merged.last_mut() {
1636 // Also eat the trailing `+` if the first
1637 // more-than-one bound is inferable
1638 let to_span = if from_start && i < bounds.len() {
1639 bounds[i+1].span().shrink_to_lo()
1643 *tail = tail.to(to_span);
1644 last_merged_i = Some(i);
1646 bug!("another bound-span visited earlier");
1650 // When we find a non-inferable bound, subsequent inferable bounds
1651 // won't be consecutive from the start (and we'll eat the leading
1652 // `+` rather than the trailing one)
1654 merged.push(bounds[i-1].span().shrink_to_hi().to(bound_span));
1655 last_merged_i = Some(i);
1664 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitOutlivesRequirements {
1665 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
1666 use rustc::middle::resolve_lifetime::Region;
1668 let infer_static = cx.tcx.features().infer_static_outlives_requirements;
1669 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1670 if let hir::ItemKind::Struct(_, ref hir_generics)
1671 | hir::ItemKind::Enum(_, ref hir_generics)
1672 | hir::ItemKind::Union(_, ref hir_generics) = item.node
1674 let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
1675 if inferred_outlives.is_empty() {
1679 let ty_generics = cx.tcx.generics_of(def_id);
1681 let mut bound_count = 0;
1682 let mut lint_spans = Vec::new();
1684 for param in &hir_generics.params {
1685 let has_lifetime_bounds = param.bounds.iter().any(|bound| {
1686 if let hir::GenericBound::Outlives(_) = bound {
1692 if !has_lifetime_bounds {
1696 let relevant_lifetimes = self.collect_outlived_lifetimes(
1702 if relevant_lifetimes.is_empty() {
1706 let bound_spans = self.collect_outlives_bound_spans(
1707 cx.tcx, ¶m.bounds, &relevant_lifetimes, infer_static,
1709 bound_count += bound_spans.len();
1711 self.consolidate_outlives_bound_spans(
1712 param.span.shrink_to_hi(), ¶m.bounds, bound_spans
1717 let mut where_lint_spans = Vec::new();
1718 let mut dropped_predicate_count = 0;
1719 let num_predicates = hir_generics.where_clause.predicates.len();
1720 for (i, where_predicate) in hir_generics.where_clause.predicates.iter().enumerate() {
1721 let (relevant_lifetimes, bounds, span) = match where_predicate {
1722 hir::WherePredicate::RegionPredicate(predicate) => {
1723 if let Some(Region::EarlyBound(index, ..))
1724 = cx.tcx.named_region(predicate.lifetime.hir_id)
1727 Self::lifetimes_outliving_lifetime(inferred_outlives, index),
1735 hir::WherePredicate::BoundPredicate(predicate) => {
1736 // FIXME we can also infer bounds on associated types,
1737 // and should check for them here.
1738 match predicate.bounded_ty.node {
1739 hir::TyKind::Path(hir::QPath::Resolved(
1743 if let Res::Def(DefKind::TyParam, def_id) = path.res {
1744 let index = ty_generics.param_def_id_to_index[&def_id];
1746 Self::lifetimes_outliving_type(inferred_outlives, index),
1759 if relevant_lifetimes.is_empty() {
1763 let bound_spans = self.collect_outlives_bound_spans(
1764 cx.tcx, bounds, &relevant_lifetimes, infer_static,
1766 bound_count += bound_spans.len();
1768 let drop_predicate = bound_spans.len() == bounds.len();
1770 dropped_predicate_count += 1;
1773 // If all the bounds on a predicate were inferable and there are
1774 // further predicates, we want to eat the trailing comma.
1775 if drop_predicate && i + 1 < num_predicates {
1776 let next_predicate_span = hir_generics.where_clause.predicates[i + 1].span();
1777 where_lint_spans.push(
1778 span.to(next_predicate_span.shrink_to_lo())
1781 where_lint_spans.extend(
1782 self.consolidate_outlives_bound_spans(
1783 span.shrink_to_lo(),
1791 // If all predicates are inferable, drop the entire clause
1792 // (including the `where`)
1793 if num_predicates > 0 && dropped_predicate_count == num_predicates {
1794 let where_span = hir_generics.where_clause.span()
1795 .expect("span of (nonempty) where clause should exist");
1796 // Extend the where clause back to the closing `>` of the
1797 // generics, except for tuple struct, which have the `where`
1798 // after the fields of the struct.
1799 let full_where_span = if let hir::ItemKind::Struct(hir::VariantData::Tuple(..), _)
1804 hir_generics.span.shrink_to_hi().to(where_span)
1810 lint_spans.extend(where_lint_spans);
1813 if !lint_spans.is_empty() {
1814 let mut err = cx.struct_span_lint(
1815 EXPLICIT_OUTLIVES_REQUIREMENTS,
1817 "outlives requirements can be inferred"
1819 err.multipart_suggestion(
1820 if bound_count == 1 {
1823 "remove these bounds"
1825 lint_spans.into_iter().map(|span| (span, "".to_owned())).collect::<Vec<_>>(),
1826 Applicability::MachineApplicable
1835 pub INCOMPLETE_FEATURES,
1837 "incomplete features that may function improperly in some or all cases"
1841 /// Check for used feature gates in `INCOMPLETE_FEATURES` in `feature_gate.rs`.
1842 IncompleteFeatures => [INCOMPLETE_FEATURES]
1845 impl EarlyLintPass for IncompleteFeatures {
1846 fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
1847 let features = cx.sess.features_untracked();
1848 features.declared_lang_features
1849 .iter().map(|(name, span, _)| (name, span))
1850 .chain(features.declared_lib_features.iter().map(|(name, span)| (name, span)))
1851 .filter(|(name, _)| feature_gate::INCOMPLETE_FEATURES.iter().any(|f| name == &f))
1852 .for_each(|(name, &span)| {
1853 cx.struct_span_lint(
1854 INCOMPLETE_FEATURES,
1857 "the feature `{}` is incomplete and may cause the compiler to crash",
1869 "an invalid value is being created (such as a NULL reference)"
1872 declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
1874 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidValue {
1875 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &hir::Expr) {
1877 const ZEROED_PATH: &[Symbol] = &[sym::core, sym::mem, sym::zeroed];
1878 const UININIT_PATH: &[Symbol] = &[sym::core, sym::mem, sym::uninitialized];
1880 /// Return `false` only if we are sure this type does *not*
1881 /// allow zero initialization.
1882 fn ty_maybe_allows_zero_init<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
1883 use rustc::ty::TyKind::*;
1885 // Primitive types that don't like 0 as a value.
1886 Ref(..) | FnPtr(..) | Never => false,
1887 Adt(..) if ty.is_box() => false,
1888 // Recurse for some compound types.
1889 Adt(adt_def, substs) if !adt_def.is_union() => {
1890 match adt_def.variants.len() {
1891 0 => false, // Uninhabited enum!
1893 // Struct, or enum with exactly one variant.
1894 // Proceed recursively, check all fields.
1895 let variant = &adt_def.variants[VariantIdx::from_u32(0)];
1896 variant.fields.iter().all(|field| {
1897 ty_maybe_allows_zero_init(
1899 field.ty(tcx, substs),
1903 _ => true, // Conservative fallback for multi-variant enum.
1907 // Proceed recursively, check all fields.
1908 ty.tuple_fields().all(|field| ty_maybe_allows_zero_init(tcx, field))
1910 // FIXME: Would be nice to also warn for `NonNull`/`NonZero*`.
1911 // FIXME: *Only for `mem::uninitialized`*, we could also warn for `bool`,
1912 // `char`, and any multivariant enum.
1913 // Conservative fallback.
1918 if let hir::ExprKind::Call(ref path_expr, ref _args) = expr.node {
1919 if let hir::ExprKind::Path(ref qpath) = path_expr.node {
1920 if let Some(def_id) = cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
1921 if cx.match_def_path(def_id, &ZEROED_PATH) ||
1922 cx.match_def_path(def_id, &UININIT_PATH)
1924 // This conjures an instance of a type out of nothing,
1925 // using zeroed or uninitialized memory.
1926 // We are extremely conservative with what we warn about.
1927 let conjured_ty = cx.tables.expr_ty(expr);
1929 if !ty_maybe_allows_zero_init(cx.tcx, conjured_ty) {
1930 cx.struct_span_lint(
1934 "the type `{}` does not permit {}",
1936 if cx.match_def_path(def_id, &ZEROED_PATH) {
1937 "zero-initialization"
1939 "being left uninitialized"
1943 .note("this means that this code causes undefined behavior \
1945 .help("use `MaybeUninit` instead")