1 //! Lints in the Rust compiler.
3 //! This contains lints which can feasibly be implemented as their own
4 //! AST visitor. Also see `rustc::lint::builtin`, which contains the
5 //! definitions of lints that are emitted directly inside the main
8 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
9 //! Then add code to emit the new lint in the appropriate circumstances.
10 //! You can do that in an existing `LintPass` if it makes sense, or in a
11 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
12 //! compiler. Only do the latter if the check can't be written cleanly as a
13 //! `LintPass` (also, note that such lints will need to be defined in
14 //! `rustc::lint::builtin`, not here).
16 //! If you define a new `EarlyLintPass`, you will also need to add it to the
17 //! `add_early_builtin!` or `add_early_builtin_with_new!` invocation in
18 //! `lib.rs`. Use the former for unit-like structs and the latter for structs
19 //! with a `pub fn new()`.
21 //! If you define a new `LateLintPass`, you will also need to add it to the
22 //! `late_lint_methods!` invocation in `lib.rs`.
26 use rustc::hir::def::{Res, DefKind};
27 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
28 use rustc::ty::{self, Ty, TyCtxt, layout::VariantIdx};
29 use rustc::{lint, util};
31 use util::nodemap::HirIdSet;
32 use lint::{LateContext, LintContext, LintArray};
33 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
35 use rustc::util::nodemap::FxHashSet;
37 use syntax::tokenstream::{TokenTree, TokenStream};
38 use syntax::ast::{self, Expr};
40 use syntax::attr::{self, HasAttrs, AttributeTemplate};
41 use syntax::source_map::Spanned;
42 use syntax::edition::Edition;
43 use syntax::feature_gate::{self, AttributeGate, AttributeType};
44 use syntax::feature_gate::{Stability, deprecated_attributes};
45 use syntax_pos::{BytePos, Span};
46 use syntax::symbol::{Symbol, kw, sym};
47 use syntax::errors::{Applicability, DiagnosticBuilder};
48 use syntax::print::pprust::expr_to_string;
49 use syntax::visit::FnKind;
51 use rustc::hir::{self, GenericParamKind, PatKind};
53 use crate::nonstandard_style::{MethodLateContext, method_context};
57 // hardwired lints from librustc
58 pub use lint::builtin::*;
63 "suggest using `loop { }` instead of `while true { }`"
66 declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
68 /// Traverse through any amount of parenthesis and return the first non-parens expression.
69 fn pierce_parens(mut expr: &ast::Expr) -> &ast::Expr {
70 while let ast::ExprKind::Paren(sub) = &expr.node {
76 impl EarlyLintPass for WhileTrue {
77 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
78 if let ast::ExprKind::While(cond, ..) = &e.node {
79 if let ast::ExprKind::Lit(ref lit) = pierce_parens(cond).node {
80 if let ast::LitKind::Bool(true) = lit.node {
81 if !lit.span.from_expansion() {
82 let msg = "denote infinite loops with `loop { ... }`";
83 let condition_span = cx.sess.source_map().def_span(e.span);
84 cx.struct_span_lint(WHILE_TRUE, condition_span, msg)
85 .span_suggestion_short(
89 Applicability::MachineApplicable
102 "use of owned (Box type) heap memory"
105 declare_lint_pass!(BoxPointers => [BOX_POINTERS]);
108 fn check_heap_type(&self, cx: &LateContext<'_, '_>, span: Span, ty: Ty<'_>) {
109 for leaf_ty in ty.walk() {
110 if leaf_ty.is_box() {
111 let m = format!("type uses owned (Box type) pointers: {}", ty);
112 cx.span_lint(BOX_POINTERS, span, &m);
118 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
119 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
121 hir::ItemKind::Fn(..) |
122 hir::ItemKind::TyAlias(..) |
123 hir::ItemKind::Enum(..) |
124 hir::ItemKind::Struct(..) |
125 hir::ItemKind::Union(..) => {
126 let def_id = cx.tcx.hir().local_def_id(it.hir_id);
127 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
132 // If it's a struct, we also have to check the fields' types
134 hir::ItemKind::Struct(ref struct_def, _) |
135 hir::ItemKind::Union(ref struct_def, _) => {
136 for struct_field in struct_def.fields() {
137 let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id);
138 self.check_heap_type(cx, struct_field.span,
139 cx.tcx.type_of(def_id));
146 fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
147 let ty = cx.tables.node_type(e.hir_id);
148 self.check_heap_type(cx, e.span, ty);
153 NON_SHORTHAND_FIELD_PATTERNS,
155 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
158 declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
160 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
161 fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat) {
162 if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node {
163 let variant = cx.tables.pat_ty(pat).ty_adt_def()
164 .expect("struct pattern type is not an ADT")
165 .variant_of_res(cx.tables.qpath_res(qpath, pat.hir_id));
166 for fieldpat in field_pats {
167 if fieldpat.is_shorthand {
170 if fieldpat.span.from_expansion() {
171 // Don't lint if this is a macro expansion: macro authors
172 // shouldn't have to worry about this kind of style issue
176 if let PatKind::Binding(_, _, ident, None) = fieldpat.pat.node {
177 if cx.tcx.find_field_index(ident, &variant) ==
178 Some(cx.tcx.field_index(fieldpat.hir_id, cx.tables)) {
179 let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
181 &format!("the `{}:` in this pattern is redundant", ident));
182 let subspan = cx.tcx.sess.source_map().span_through_char(fieldpat.span,
184 err.span_suggestion_short(
188 Applicability::MachineApplicable
201 "usage of `unsafe` code"
204 declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
207 fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) {
208 // This comes from a macro that has `#[allow_internal_unsafe]`.
209 if span.allows_unsafe() {
213 cx.span_lint(UNSAFE_CODE, span, desc);
217 impl EarlyLintPass for UnsafeCode {
218 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
219 if attr.check_name(sym::allow_internal_unsafe) {
220 self.report_unsafe(cx, attr.span, "`allow_internal_unsafe` allows defining \
221 macros using unsafe without triggering \
222 the `unsafe_code` lint at their call site");
226 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
227 if let ast::ExprKind::Block(ref blk, _) = e.node {
228 // Don't warn about generated blocks; that'll just pollute the output.
229 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
230 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
235 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
237 ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => {
238 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
241 ast::ItemKind::Impl(ast::Unsafety::Unsafe, ..) => {
242 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
249 fn check_fn(&mut self,
250 cx: &EarlyContext<'_>,
256 FnKind::ItemFn(_, ast::FnHeader { unsafety: ast::Unsafety::Unsafe, .. }, ..) => {
257 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
260 FnKind::Method(_, sig, ..) => {
261 if sig.header.unsafety == ast::Unsafety::Unsafe {
262 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
270 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, item: &ast::TraitItem) {
271 if let ast::TraitItemKind::Method(ref sig, None) = item.node {
272 if sig.header.unsafety == ast::Unsafety::Unsafe {
273 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
282 "detects missing documentation for public members",
283 report_in_external_macro: true
286 pub struct MissingDoc {
287 /// Stack of whether `#[doc(hidden)]` is set at each level which has lint attributes.
288 doc_hidden_stack: Vec<bool>,
290 /// Private traits or trait items that leaked through. Don't check their methods.
291 private_traits: FxHashSet<hir::HirId>,
294 impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
296 fn has_doc(attr: &ast::Attribute) -> bool {
297 if !attr.check_name(sym::doc) {
301 if attr.is_value_str() {
305 if let Some(list) = attr.meta_item_list() {
307 if meta.check_name(sym::include) || meta.check_name(sym::hidden) {
317 pub fn new() -> MissingDoc {
319 doc_hidden_stack: vec![false],
320 private_traits: FxHashSet::default(),
324 fn doc_hidden(&self) -> bool {
325 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
328 fn check_missing_docs_attrs(&self,
329 cx: &LateContext<'_, '_>,
330 id: Option<hir::HirId>,
331 attrs: &[ast::Attribute],
333 desc: &'static str) {
334 // If we're building a test harness, then warning about
335 // documentation is probably not really relevant right now.
336 if cx.sess().opts.test {
340 // `#[doc(hidden)]` disables missing_docs check.
341 if self.doc_hidden() {
345 // Only check publicly-visible items, using the result from the privacy pass.
346 // It's an option so the crate root can also use this function (it doesn't
348 if let Some(id) = id {
349 if !cx.access_levels.is_exported(id) {
354 let has_doc = attrs.iter().any(|a| has_doc(a));
356 cx.span_lint(MISSING_DOCS,
357 cx.tcx.sess.source_map().def_span(sp),
358 &format!("missing documentation for {}", desc));
363 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
364 fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) {
365 let doc_hidden = self.doc_hidden() ||
366 attrs.iter().any(|attr| {
367 attr.check_name(sym::doc) &&
368 match attr.meta_item_list() {
370 Some(l) => attr::list_contains_name(&l, sym::hidden),
373 self.doc_hidden_stack.push(doc_hidden);
376 fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) {
377 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
380 fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate) {
381 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
383 for macro_def in &krate.exported_macros {
384 let has_doc = macro_def.attrs.iter().any(|a| has_doc(a));
386 cx.span_lint(MISSING_DOCS,
387 cx.tcx.sess.source_map().def_span(macro_def.span),
388 "missing documentation for macro");
393 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
394 let desc = match it.node {
395 hir::ItemKind::Fn(..) => "a function",
396 hir::ItemKind::Mod(..) => "a module",
397 hir::ItemKind::Enum(..) => "an enum",
398 hir::ItemKind::Struct(..) => "a struct",
399 hir::ItemKind::Union(..) => "a union",
400 hir::ItemKind::Trait(.., ref trait_item_refs) => {
401 // Issue #11592: traits are always considered exported, even when private.
402 if let hir::VisibilityKind::Inherited = it.vis.node {
403 self.private_traits.insert(it.hir_id);
404 for trait_item_ref in trait_item_refs {
405 self.private_traits.insert(trait_item_ref.id.hir_id);
411 hir::ItemKind::TyAlias(..) => "a type alias",
412 hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
413 // If the trait is private, add the impl items to `private_traits` so they don't get
414 // reported for missing docs.
415 let real_trait = trait_ref.path.res.def_id();
416 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(real_trait) {
417 match cx.tcx.hir().find(hir_id) {
418 Some(Node::Item(item)) => {
419 if let hir::VisibilityKind::Inherited = item.vis.node {
420 for impl_item_ref in impl_item_refs {
421 self.private_traits.insert(impl_item_ref.id.hir_id);
430 hir::ItemKind::Const(..) => "a constant",
431 hir::ItemKind::Static(..) => "a static",
435 self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, desc);
438 fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem) {
439 if self.private_traits.contains(&trait_item.hir_id) {
443 let desc = match trait_item.node {
444 hir::TraitItemKind::Const(..) => "an associated constant",
445 hir::TraitItemKind::Method(..) => "a trait method",
446 hir::TraitItemKind::Type(..) => "an associated type",
449 self.check_missing_docs_attrs(cx,
450 Some(trait_item.hir_id),
456 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
457 // If the method is an impl for a trait, don't doc.
458 if method_context(cx, impl_item.hir_id) == MethodLateContext::TraitImpl {
462 let desc = match impl_item.node {
463 hir::ImplItemKind::Const(..) => "an associated constant",
464 hir::ImplItemKind::Method(..) => "a method",
465 hir::ImplItemKind::TyAlias(_) => "an associated type",
466 hir::ImplItemKind::OpaqueTy(_) => "an associated `impl Trait` type",
468 self.check_missing_docs_attrs(cx,
469 Some(impl_item.hir_id),
475 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField) {
476 if !sf.is_positional() {
477 self.check_missing_docs_attrs(cx,
485 fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant) {
486 self.check_missing_docs_attrs(cx,
495 pub MISSING_COPY_IMPLEMENTATIONS,
497 "detects potentially-forgotten implementations of `Copy`"
500 declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
502 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
503 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
504 if !cx.access_levels.is_reachable(item.hir_id) {
507 let (def, ty) = match item.node {
508 hir::ItemKind::Struct(_, ref ast_generics) => {
509 if !ast_generics.params.is_empty() {
512 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
513 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
515 hir::ItemKind::Union(_, ref ast_generics) => {
516 if !ast_generics.params.is_empty() {
519 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
520 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
522 hir::ItemKind::Enum(_, ref ast_generics) => {
523 if !ast_generics.params.is_empty() {
526 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
527 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
531 if def.has_dtor(cx.tcx) {
534 let param_env = ty::ParamEnv::empty();
535 if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span) {
538 if param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
539 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
541 "type could implement `Copy`; consider adding `impl \
548 MISSING_DEBUG_IMPLEMENTATIONS,
550 "detects missing implementations of fmt::Debug"
554 pub struct MissingDebugImplementations {
555 impling_types: Option<HirIdSet>,
558 impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
560 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
561 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
562 if !cx.access_levels.is_reachable(item.hir_id) {
567 hir::ItemKind::Struct(..) |
568 hir::ItemKind::Union(..) |
569 hir::ItemKind::Enum(..) => {}
573 let debug = match cx.tcx.lang_items().debug_trait() {
574 Some(debug) => debug,
578 if self.impling_types.is_none() {
579 let mut impls = HirIdSet::default();
580 cx.tcx.for_each_impl(debug, |d| {
581 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
582 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
583 impls.insert(hir_id);
588 self.impling_types = Some(impls);
589 debug!("{:?}", self.impling_types);
592 if !self.impling_types.as_ref().unwrap().contains(&item.hir_id) {
593 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
595 "type does not implement `fmt::Debug`; consider adding `#[derive(Debug)]` \
596 or a manual implementation")
602 pub ANONYMOUS_PARAMETERS,
604 "detects anonymous parameters"
608 /// Checks for use of anonymous parameters (RFC 1685).
609 AnonymousParameters => [ANONYMOUS_PARAMETERS]
612 impl EarlyLintPass for AnonymousParameters {
613 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::TraitItem) {
615 ast::TraitItemKind::Method(ref sig, _) => {
616 for arg in sig.decl.inputs.iter() {
618 ast::PatKind::Ident(_, ident, None) => {
619 if ident.name == kw::Invalid {
623 .span_to_snippet(arg.ty.span);
625 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
626 (snip, Applicability::MachineApplicable)
628 ("<type>".to_owned(), Applicability::HasPlaceholders)
632 ANONYMOUS_PARAMETERS,
634 "anonymous parameters are deprecated and will be \
635 removed in the next edition."
638 "Try naming the parameter or explicitly \
640 format!("_: {}", ty_snip),
654 /// Check for use of attributes which have been deprecated.
656 pub struct DeprecatedAttr {
657 // This is not free to compute, so we want to keep it around, rather than
658 // compute it for every attribute.
659 depr_attrs: Vec<&'static (Symbol, AttributeType, AttributeTemplate, AttributeGate)>,
662 impl_lint_pass!(DeprecatedAttr => []);
664 impl DeprecatedAttr {
665 pub fn new() -> DeprecatedAttr {
667 depr_attrs: deprecated_attributes(),
672 impl EarlyLintPass for DeprecatedAttr {
673 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
674 for &&(n, _, _, ref g) in &self.depr_attrs {
675 if attr.ident().map(|ident| ident.name) == Some(n) {
676 if let &AttributeGate::Gated(Stability::Deprecated(link, suggestion),
680 let msg = format!("use of deprecated attribute `{}`: {}. See {}",
682 let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
683 err.span_suggestion_short(
685 suggestion.unwrap_or("remove this attribute"),
687 Applicability::MachineApplicable
698 pub UNUSED_DOC_COMMENTS,
700 "detects doc comments that aren't used by rustdoc"
703 declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]);
705 impl UnusedDocComment {
708 cx: &EarlyContext<'_>,
711 is_macro_expansion: bool,
712 attrs: &[ast::Attribute]
714 let mut attrs = attrs.into_iter().peekable();
716 // Accumulate a single span for sugared doc comments.
717 let mut sugared_span: Option<Span> = None;
719 while let Some(attr) = attrs.next() {
720 if attr.is_sugared_doc {
722 sugared_span.map_or_else(
724 |span| span.with_hi(attr.span.hi()),
729 if attrs.peek().map(|next_attr| next_attr.is_sugared_doc).unwrap_or_default() {
733 let span = sugared_span.take().unwrap_or_else(|| attr.span);
735 if attr.check_name(sym::doc) {
736 let mut err = cx.struct_span_lint(UNUSED_DOC_COMMENTS, span, "unused doc comment");
740 format!("rustdoc does not generate documentation for {}", node_kind)
743 if is_macro_expansion {
744 err.help("to document an item produced by a macro, \
745 the macro must produce the documentation as part of its expansion");
754 impl EarlyLintPass for UnusedDocComment {
755 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
756 if let ast::ItemKind::Mac(..) = item.node {
757 self.warn_if_doc(cx, item.span, "macro expansions", true, &item.attrs);
761 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
762 let (kind, is_macro_expansion) = match stmt.node {
763 ast::StmtKind::Local(..) => ("statements", false),
764 ast::StmtKind::Item(..) => ("inner items", false),
765 ast::StmtKind::Mac(..) => ("macro expansions", true),
766 // expressions will be reported by `check_expr`.
767 ast::StmtKind::Semi(..) |
768 ast::StmtKind::Expr(..) => return,
771 self.warn_if_doc(cx, stmt.span, kind, is_macro_expansion, stmt.node.attrs());
774 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
775 let arm_span = arm.pats[0].span.with_hi(arm.body.span.hi());
776 self.warn_if_doc(cx, arm_span, "match arms", false, &arm.attrs);
779 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
780 self.warn_if_doc(cx, expr.span, "expressions", false, &expr.attrs);
787 "compiler plugin used as ordinary library in non-plugin crate"
790 declare_lint_pass!(PluginAsLibrary => [PLUGIN_AS_LIBRARY]);
792 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
793 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
794 if cx.tcx.plugin_registrar_fn(LOCAL_CRATE).is_some() {
795 // We're compiling a plugin; it's fine to link other plugins.
800 hir::ItemKind::ExternCrate(..) => (),
804 let def_id = cx.tcx.hir().local_def_id(it.hir_id);
805 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
806 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
808 // Probably means we aren't linking the crate for some reason.
810 // Not sure if / when this could happen.
816 cx.span_lint(PLUGIN_AS_LIBRARY,
818 "compiler plugin used as an ordinary library");
824 NO_MANGLE_CONST_ITEMS,
826 "const items will not have their symbols exported"
830 NO_MANGLE_GENERIC_ITEMS,
832 "generic items must be mangled"
835 declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
837 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
838 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
840 hir::ItemKind::Fn(.., ref generics, _) => {
841 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
842 for param in &generics.params {
844 GenericParamKind::Lifetime { .. } => {}
845 GenericParamKind::Type { .. } |
846 GenericParamKind::Const { .. } => {
847 let mut err = cx.struct_span_lint(
848 NO_MANGLE_GENERIC_ITEMS,
850 "functions generic over types or consts must be mangled",
852 err.span_suggestion_short(
854 "remove this attribute",
856 // Use of `#[no_mangle]` suggests FFI intent; correct
857 // fix may be to monomorphize source by hand
858 Applicability::MaybeIncorrect
867 hir::ItemKind::Const(..) => {
868 if attr::contains_name(&it.attrs, sym::no_mangle) {
869 // Const items do not refer to a particular location in memory, and therefore
870 // don't have anything to attach a symbol to
871 let msg = "const items should never be `#[no_mangle]`";
872 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
874 // account for "pub const" (#45562)
875 let start = cx.tcx.sess.source_map().span_to_snippet(it.span)
876 .map(|snippet| snippet.find("const").unwrap_or(0))
877 .unwrap_or(0) as u32;
878 // `const` is 5 chars
879 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
882 "try a static value",
883 "pub static".to_owned(),
884 Applicability::MachineApplicable
897 "mutating transmuted &mut T from &T may cause undefined behavior"
900 declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
902 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
903 fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr) {
904 use rustc_target::spec::abi::Abi::RustIntrinsic;
906 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
907 consider instead using an UnsafeCell";
908 match get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (&ty1.sty, &ty2.sty)) {
909 Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
910 if to_mt == hir::Mutability::MutMutable &&
911 from_mt == hir::Mutability::MutImmutable {
912 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
918 fn get_transmute_from_to<'a, 'tcx>
919 (cx: &LateContext<'a, 'tcx>,
921 -> Option<(Ty<'tcx>, Ty<'tcx>)> {
922 let def = if let hir::ExprKind::Path(ref qpath) = expr.node {
923 cx.tables.qpath_res(qpath, expr.hir_id)
927 if let Res::Def(DefKind::Fn, did) = def {
928 if !def_id_is_transmute(cx, did) {
931 let sig = cx.tables.node_type(expr.hir_id).fn_sig(cx.tcx);
932 let from = sig.inputs().skip_binder()[0];
933 let to = *sig.output().skip_binder();
934 return Some((from, to));
939 fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
940 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
941 cx.tcx.item_name(def_id) == sym::transmute
949 "enabling unstable features (deprecated. do not use)"
953 /// Forbids using the `#[feature(...)]` attribute
954 UnstableFeatures => [UNSTABLE_FEATURES]
957 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
958 fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) {
959 if attr.check_name(sym::feature) {
960 if let Some(items) = attr.meta_item_list() {
962 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
970 UNIONS_WITH_DROP_FIELDS,
972 "use of unions that contain fields with possibly non-trivial drop code"
976 /// Lint for unions that contain fields with possibly non-trivial destructors.
977 UnionsWithDropFields => [UNIONS_WITH_DROP_FIELDS]
980 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
981 fn check_item(&mut self, ctx: &LateContext<'_, '_>, item: &hir::Item) {
982 if let hir::ItemKind::Union(ref vdata, _) = item.node {
983 for field in vdata.fields() {
984 let field_ty = ctx.tcx.type_of(
985 ctx.tcx.hir().local_def_id(field.hir_id));
986 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
987 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
989 "union contains a field with possibly non-trivial drop code, \
990 drop code of union fields is ignored when dropping the union");
1001 "`pub` items not reachable from crate root"
1005 /// Lint for items marked `pub` that aren't reachable from other crates.
1006 UnreachablePub => [UNREACHABLE_PUB]
1009 impl UnreachablePub {
1010 fn perform_lint(&self, cx: &LateContext<'_, '_>, what: &str, id: hir::HirId,
1011 vis: &hir::Visibility, span: Span, exportable: bool) {
1012 let mut applicability = Applicability::MachineApplicable;
1014 hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
1015 if span.from_expansion() {
1016 applicability = Applicability::MaybeIncorrect;
1018 let def_span = cx.tcx.sess.source_map().def_span(span);
1019 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1020 &format!("unreachable `pub` {}", what));
1021 let replacement = if cx.tcx.features().crate_visibility_modifier {
1027 err.span_suggestion(
1029 "consider restricting its visibility",
1034 err.help("or consider exporting it for use by other crates");
1043 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1044 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1045 self.perform_lint(cx, "item", item.hir_id, &item.vis, item.span, true);
1048 fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, foreign_item: &hir::ForeignItem) {
1049 self.perform_lint(cx, "item", foreign_item.hir_id, &foreign_item.vis,
1050 foreign_item.span, true);
1053 fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) {
1054 self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false);
1057 fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
1058 self.perform_lint(cx, "item", impl_item.hir_id, &impl_item.vis, impl_item.span, false);
1065 "bounds in type aliases are not enforced"
1069 /// Lint for trait and lifetime bounds in type aliases being mostly ignored.
1070 /// They are relevant when using associated types, but otherwise neither checked
1071 /// at definition site nor enforced at use site.
1072 TypeAliasBounds => [TYPE_ALIAS_BOUNDS]
1075 impl TypeAliasBounds {
1076 fn is_type_variable_assoc(qpath: &hir::QPath) -> bool {
1078 hir::QPath::TypeRelative(ref ty, _) => {
1079 // If this is a type variable, we found a `T::Assoc`.
1081 hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1083 Res::Def(DefKind::TyParam, _) => true,
1090 hir::QPath::Resolved(..) => false,
1094 fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder<'_>) {
1095 // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1096 // bound. Let's see if this type does that.
1098 // We use a HIR visitor to walk the type.
1099 use rustc::hir::intravisit::{self, Visitor};
1100 struct WalkAssocTypes<'a, 'db> {
1101 err: &'a mut DiagnosticBuilder<'db>
1103 impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1104 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'v>
1106 intravisit::NestedVisitorMap::None
1109 fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: hir::HirId, span: Span) {
1110 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1111 self.err.span_help(span,
1112 "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1113 associated types in type aliases");
1115 intravisit::walk_qpath(self, qpath, id, span)
1119 // Let's go for a walk!
1120 let mut visitor = WalkAssocTypes { err };
1121 visitor.visit_ty(ty);
1125 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1126 fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
1127 let (ty, type_alias_generics) = match item.node {
1128 hir::ItemKind::TyAlias(ref ty, ref generics) => (&*ty, generics),
1131 let mut suggested_changing_assoc_types = false;
1132 // There must not be a where clause
1133 if !type_alias_generics.where_clause.predicates.is_empty() {
1134 let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1135 .map(|pred| pred.span()).collect();
1136 let mut err = cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans,
1137 "where clauses are not enforced in type aliases");
1138 err.help("the clause will not be checked when the type alias is used, \
1139 and should be removed");
1140 if !suggested_changing_assoc_types {
1141 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1142 suggested_changing_assoc_types = true;
1146 // The parameters must not have bounds
1147 for param in type_alias_generics.params.iter() {
1148 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1149 if !spans.is_empty() {
1150 let mut err = cx.struct_span_lint(
1153 "bounds on generic parameters are not enforced in type aliases",
1155 err.help("the bound will not be checked when the type alias is used, \
1156 and should be removed");
1157 if !suggested_changing_assoc_types {
1158 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1159 suggested_changing_assoc_types = true;
1168 /// Lint constants that are erroneous.
1169 /// Without this lint, we might not get any diagnostic if the constant is
1170 /// unused within this crate, even though downstream crates can't use it
1171 /// without producing an error.
1172 UnusedBrokenConst => []
1175 fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) {
1176 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
1177 let param_env = if cx.tcx.is_static(def_id) {
1178 // Use the same param_env as `codegen_static_initializer`, to reuse the cache.
1179 ty::ParamEnv::reveal_all()
1181 cx.tcx.param_env(def_id)
1183 let cid = ::rustc::mir::interpret::GlobalId {
1184 instance: ty::Instance::mono(cx.tcx, def_id),
1187 // trigger the query once for all constants since that will already report the errors
1188 // FIXME: Use ensure here
1189 let _ = cx.tcx.const_eval(param_env.and(cid));
1192 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1193 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1195 hir::ItemKind::Const(_, body_id) => {
1196 check_const(cx, body_id);
1198 hir::ItemKind::Static(_, _, body_id) => {
1199 check_const(cx, body_id);
1209 "these bounds don't depend on an type parameters"
1213 /// Lint for trait and lifetime bounds that don't depend on type parameters
1214 /// which either do nothing, or stop the item from being used.
1215 TrivialConstraints => [TRIVIAL_BOUNDS]
1218 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1221 cx: &LateContext<'a, 'tcx>,
1222 item: &'tcx hir::Item,
1224 use rustc::ty::fold::TypeFoldable;
1225 use rustc::ty::Predicate::*;
1227 if cx.tcx.features().trivial_bounds {
1228 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1229 let predicates = cx.tcx.predicates_of(def_id);
1230 for &(predicate, span) in &predicates.predicates {
1231 let predicate_kind_name = match predicate {
1232 Trait(..) => "Trait",
1234 RegionOutlives(..) => "Lifetime",
1236 // Ignore projections, as they can only be global
1237 // if the trait bound is global
1239 // Ignore bounds that a user can't type
1244 ConstEvaluatable(..) => continue,
1246 if predicate.is_global() {
1250 &format!("{} bound {} does not depend on any type \
1251 or lifetime parameters", predicate_kind_name, predicate),
1260 /// Does nothing as a lint pass, but registers some `Lint`s
1261 /// which are used by other parts of the compiler.
1265 NON_SHORTHAND_FIELD_PATTERNS,
1268 MISSING_COPY_IMPLEMENTATIONS,
1269 MISSING_DEBUG_IMPLEMENTATIONS,
1270 ANONYMOUS_PARAMETERS,
1271 UNUSED_DOC_COMMENTS,
1273 NO_MANGLE_CONST_ITEMS,
1274 NO_MANGLE_GENERIC_ITEMS,
1277 UNIONS_WITH_DROP_FIELDS,
1285 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1287 "`...` range patterns are deprecated"
1291 pub struct EllipsisInclusiveRangePatterns {
1292 /// If `Some(_)`, suppress all subsequent pattern
1293 /// warnings for better diagnostics.
1294 node_id: Option<ast::NodeId>,
1297 impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1299 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1300 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1301 if self.node_id.is_some() {
1302 // Don't recursively warn about patterns inside range endpoints.
1306 use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot};
1308 /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1309 /// corresponding to the ellipsis.
1310 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(&P<Expr>, &P<Expr>, Span)> {
1312 PatKind::Range(a, b, Spanned { span, node: RangeEnd::Included(DotDotDot), .. }) => {
1319 let (parenthesise, endpoints) = match &pat.node {
1320 PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)),
1321 _ => (false, matches_ellipsis_pat(pat)),
1324 if let Some((start, end, join)) = endpoints {
1325 let msg = "`...` range patterns are deprecated";
1326 let suggestion = "use `..=` for an inclusive range";
1328 self.node_id = Some(pat.id);
1329 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, pat.span, msg);
1330 err.span_suggestion(
1333 format!("&({}..={})", expr_to_string(&start), expr_to_string(&end)),
1334 Applicability::MachineApplicable,
1338 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, join, msg);
1339 err.span_suggestion_short(
1343 Applicability::MachineApplicable,
1350 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1351 if let Some(node_id) = self.node_id {
1352 if pat.id == node_id {
1360 UNNAMEABLE_TEST_ITEMS,
1362 "detects an item that cannot be named being marked as `#[test_case]`",
1363 report_in_external_macro: true
1366 pub struct UnnameableTestItems {
1367 boundary: hir::HirId, // HirId of the item under which things are not nameable
1368 items_nameable: bool,
1371 impl_lint_pass!(UnnameableTestItems => [UNNAMEABLE_TEST_ITEMS]);
1373 impl UnnameableTestItems {
1374 pub fn new() -> Self {
1376 boundary: hir::DUMMY_HIR_ID,
1377 items_nameable: true
1382 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
1383 fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
1384 if self.items_nameable {
1385 if let hir::ItemKind::Mod(..) = it.node {}
1387 self.items_nameable = false;
1388 self.boundary = it.hir_id;
1393 if let Some(attr) = attr::find_by_name(&it.attrs, sym::rustc_test_marker) {
1394 cx.struct_span_lint(
1395 UNNAMEABLE_TEST_ITEMS,
1397 "cannot test inner items",
1402 fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item) {
1403 if !self.items_nameable && self.boundary == it.hir_id {
1404 self.items_nameable = true;
1412 "detects edition keywords being used as an identifier"
1416 /// Check for uses of edition keywords used as an identifier.
1417 KeywordIdents => [KEYWORD_IDENTS]
1420 struct UnderMacro(bool);
1422 impl KeywordIdents {
1423 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) {
1424 for tt in tokens.into_trees() {
1426 // Only report non-raw idents.
1427 TokenTree::Token(token) => if let Some((ident, false)) = token.ident() {
1428 self.check_ident_token(cx, UnderMacro(true), ident);
1430 TokenTree::Delimited(_, _, tts) => {
1431 self.check_tokens(cx, tts)
1437 fn check_ident_token(&mut self,
1438 cx: &EarlyContext<'_>,
1439 UnderMacro(under_macro): UnderMacro,
1442 let next_edition = match cx.sess.edition() {
1443 Edition::Edition2015 => {
1445 kw::Async | kw::Await | kw::Try => Edition::Edition2018,
1447 // rust-lang/rust#56327: Conservatively do not
1448 // attempt to report occurrences of `dyn` within
1449 // macro definitions or invocations, because `dyn`
1450 // can legitimately occur as a contextual keyword
1451 // in 2015 code denoting its 2018 meaning, and we
1452 // do not want rustfix to inject bugs into working
1453 // code by rewriting such occurrences.
1455 // But if we see `dyn` outside of a macro, we know
1456 // its precise role in the parsed AST and thus are
1457 // assured this is truly an attempt to use it as
1459 kw::Dyn if !under_macro => Edition::Edition2018,
1465 // There are no new keywords yet for the 2018 edition and beyond.
1469 // Don't lint `r#foo`.
1470 if cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span) {
1474 let mut lint = cx.struct_span_lint(
1477 &format!("`{}` is a keyword in the {} edition",
1481 lint.span_suggestion(
1483 "you can use a raw identifier to stay compatible",
1484 format!("r#{}", ident.as_str()),
1485 Applicability::MachineApplicable,
1491 impl EarlyLintPass for KeywordIdents {
1492 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) {
1493 self.check_tokens(cx, mac_def.stream());
1495 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
1496 self.check_tokens(cx, mac.tts.clone().into());
1498 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: ast::Ident) {
1499 self.check_ident_token(cx, UnderMacro(false), ident);
1503 declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1505 impl ExplicitOutlivesRequirements {
1506 fn lifetimes_outliving_lifetime<'tcx>(
1507 inferred_outlives: &'tcx [ty::Predicate<'tcx>],
1509 ) -> Vec<ty::Region<'tcx>> {
1510 inferred_outlives.iter().filter_map(|pred| {
1512 ty::Predicate::RegionOutlives(outlives) => {
1513 let outlives = outlives.skip_binder();
1515 ty::ReEarlyBound(ebr) if ebr.index == index => {
1526 fn lifetimes_outliving_type<'tcx>(
1527 inferred_outlives: &'tcx [ty::Predicate<'tcx>],
1529 ) -> Vec<ty::Region<'tcx>> {
1530 inferred_outlives.iter().filter_map(|pred| {
1532 ty::Predicate::TypeOutlives(outlives) => {
1533 let outlives = outlives.skip_binder();
1534 if outlives.0.is_param(index) {
1545 fn collect_outlived_lifetimes<'tcx>(
1547 param: &'tcx hir::GenericParam,
1549 inferred_outlives: &'tcx [ty::Predicate<'tcx>],
1550 ty_generics: &'tcx ty::Generics,
1551 ) -> Vec<ty::Region<'tcx>> {
1552 let index = ty_generics.param_def_id_to_index[
1553 &tcx.hir().local_def_id(param.hir_id)];
1556 hir::GenericParamKind::Lifetime { .. } => {
1557 Self::lifetimes_outliving_lifetime(inferred_outlives, index)
1559 hir::GenericParamKind::Type { .. } => {
1560 Self::lifetimes_outliving_type(inferred_outlives, index)
1562 hir::GenericParamKind::Const { .. } => Vec::new(),
1567 fn collect_outlives_bound_spans<'tcx>(
1570 bounds: &hir::GenericBounds,
1571 inferred_outlives: &[ty::Region<'tcx>],
1573 ) -> Vec<(usize, Span)> {
1574 use rustc::middle::resolve_lifetime::Region;
1579 .filter_map(|(i, bound)| {
1580 if let hir::GenericBound::Outlives(lifetime) = bound {
1581 let is_inferred = match tcx.named_region(lifetime.hir_id) {
1582 Some(Region::Static) if infer_static => {
1583 inferred_outlives.iter()
1584 .any(|r| if let ty::ReStatic = r { true } else { false })
1586 Some(Region::EarlyBound(index, ..)) => inferred_outlives
1589 if let ty::ReEarlyBound(ebr) = r {
1598 Some((i, bound.span()))
1609 fn consolidate_outlives_bound_spans(
1612 bounds: &hir::GenericBounds,
1613 bound_spans: Vec<(usize, Span)>
1615 if bounds.is_empty() {
1618 if bound_spans.len() == bounds.len() {
1619 let (_, last_bound_span) = bound_spans[bound_spans.len()-1];
1620 // If all bounds are inferable, we want to delete the colon, so
1621 // start from just after the parameter (span passed as argument)
1622 vec![lo.to(last_bound_span)]
1624 let mut merged = Vec::new();
1625 let mut last_merged_i = None;
1627 let mut from_start = true;
1628 for (i, bound_span) in bound_spans {
1629 match last_merged_i {
1630 // If the first bound is inferable, our span should also eat the leading `+`.
1632 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
1633 last_merged_i = Some(0);
1635 // If consecutive bounds are inferable, merge their spans
1636 Some(h) if i == h+1 => {
1637 if let Some(tail) = merged.last_mut() {
1638 // Also eat the trailing `+` if the first
1639 // more-than-one bound is inferable
1640 let to_span = if from_start && i < bounds.len() {
1641 bounds[i+1].span().shrink_to_lo()
1645 *tail = tail.to(to_span);
1646 last_merged_i = Some(i);
1648 bug!("another bound-span visited earlier");
1652 // When we find a non-inferable bound, subsequent inferable bounds
1653 // won't be consecutive from the start (and we'll eat the leading
1654 // `+` rather than the trailing one)
1656 merged.push(bounds[i-1].span().shrink_to_hi().to(bound_span));
1657 last_merged_i = Some(i);
1666 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitOutlivesRequirements {
1667 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
1668 use rustc::middle::resolve_lifetime::Region;
1670 let infer_static = cx.tcx.features().infer_static_outlives_requirements;
1671 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1672 if let hir::ItemKind::Struct(_, ref hir_generics)
1673 | hir::ItemKind::Enum(_, ref hir_generics)
1674 | hir::ItemKind::Union(_, ref hir_generics) = item.node
1676 let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
1677 if inferred_outlives.is_empty() {
1681 let ty_generics = cx.tcx.generics_of(def_id);
1683 let mut bound_count = 0;
1684 let mut lint_spans = Vec::new();
1686 for param in &hir_generics.params {
1687 let has_lifetime_bounds = param.bounds.iter().any(|bound| {
1688 if let hir::GenericBound::Outlives(_) = bound {
1694 if !has_lifetime_bounds {
1698 let relevant_lifetimes = self.collect_outlived_lifetimes(
1704 if relevant_lifetimes.is_empty() {
1708 let bound_spans = self.collect_outlives_bound_spans(
1709 cx.tcx, ¶m.bounds, &relevant_lifetimes, infer_static,
1711 bound_count += bound_spans.len();
1713 self.consolidate_outlives_bound_spans(
1714 param.span.shrink_to_hi(), ¶m.bounds, bound_spans
1719 let mut where_lint_spans = Vec::new();
1720 let mut dropped_predicate_count = 0;
1721 let num_predicates = hir_generics.where_clause.predicates.len();
1722 for (i, where_predicate) in hir_generics.where_clause.predicates.iter().enumerate() {
1723 let (relevant_lifetimes, bounds, span) = match where_predicate {
1724 hir::WherePredicate::RegionPredicate(predicate) => {
1725 if let Some(Region::EarlyBound(index, ..))
1726 = cx.tcx.named_region(predicate.lifetime.hir_id)
1729 Self::lifetimes_outliving_lifetime(inferred_outlives, index),
1737 hir::WherePredicate::BoundPredicate(predicate) => {
1738 // FIXME we can also infer bounds on associated types,
1739 // and should check for them here.
1740 match predicate.bounded_ty.node {
1741 hir::TyKind::Path(hir::QPath::Resolved(
1745 if let Res::Def(DefKind::TyParam, def_id) = path.res {
1746 let index = ty_generics.param_def_id_to_index[&def_id];
1748 Self::lifetimes_outliving_type(inferred_outlives, index),
1761 if relevant_lifetimes.is_empty() {
1765 let bound_spans = self.collect_outlives_bound_spans(
1766 cx.tcx, bounds, &relevant_lifetimes, infer_static,
1768 bound_count += bound_spans.len();
1770 let drop_predicate = bound_spans.len() == bounds.len();
1772 dropped_predicate_count += 1;
1775 // If all the bounds on a predicate were inferable and there are
1776 // further predicates, we want to eat the trailing comma.
1777 if drop_predicate && i + 1 < num_predicates {
1778 let next_predicate_span = hir_generics.where_clause.predicates[i + 1].span();
1779 where_lint_spans.push(
1780 span.to(next_predicate_span.shrink_to_lo())
1783 where_lint_spans.extend(
1784 self.consolidate_outlives_bound_spans(
1785 span.shrink_to_lo(),
1793 // If all predicates are inferable, drop the entire clause
1794 // (including the `where`)
1795 if num_predicates > 0 && dropped_predicate_count == num_predicates {
1796 let where_span = hir_generics.where_clause.span()
1797 .expect("span of (nonempty) where clause should exist");
1798 // Extend the where clause back to the closing `>` of the
1799 // generics, except for tuple struct, which have the `where`
1800 // after the fields of the struct.
1801 let full_where_span = if let hir::ItemKind::Struct(hir::VariantData::Tuple(..), _)
1806 hir_generics.span.shrink_to_hi().to(where_span)
1812 lint_spans.extend(where_lint_spans);
1815 if !lint_spans.is_empty() {
1816 let mut err = cx.struct_span_lint(
1817 EXPLICIT_OUTLIVES_REQUIREMENTS,
1819 "outlives requirements can be inferred"
1821 err.multipart_suggestion(
1822 if bound_count == 1 {
1825 "remove these bounds"
1827 lint_spans.into_iter().map(|span| (span, "".to_owned())).collect::<Vec<_>>(),
1828 Applicability::MachineApplicable
1837 pub INCOMPLETE_FEATURES,
1839 "incomplete features that may function improperly in some or all cases"
1843 /// Check for used feature gates in `INCOMPLETE_FEATURES` in `feature_gate.rs`.
1844 IncompleteFeatures => [INCOMPLETE_FEATURES]
1847 impl EarlyLintPass for IncompleteFeatures {
1848 fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
1849 let features = cx.sess.features_untracked();
1850 features.declared_lang_features
1851 .iter().map(|(name, span, _)| (name, span))
1852 .chain(features.declared_lib_features.iter().map(|(name, span)| (name, span)))
1853 .filter(|(name, _)| feature_gate::INCOMPLETE_FEATURES.iter().any(|f| name == &f))
1854 .for_each(|(name, &span)| {
1855 cx.struct_span_lint(
1856 INCOMPLETE_FEATURES,
1859 "the feature `{}` is incomplete and may cause the compiler to crash",
1871 "an invalid value is being created (such as a NULL reference)"
1874 declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
1876 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidValue {
1877 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &hir::Expr) {
1879 #[derive(Debug, Copy, Clone, PartialEq)]
1880 enum InitKind { Zeroed, Uninit };
1882 /// Information about why a type cannot be initialized this way.
1883 /// Contains an error message and optionally a span to point at.
1884 type InitError = (String, Option<Span>);
1886 /// Test if this constant is all-0.
1887 fn is_zero(expr: &hir::Expr) -> bool {
1888 use hir::ExprKind::*;
1889 use syntax::ast::LitKind::*;
1892 if let Int(i, _) = lit.node {
1898 tup.iter().all(is_zero),
1904 /// Determine if this expression is a "dangerous initialization".
1905 fn is_dangerous_init(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> Option<InitKind> {
1906 const ZEROED_PATH: &[Symbol] = &[sym::core, sym::mem, sym::zeroed];
1907 const UININIT_PATH: &[Symbol] = &[sym::core, sym::mem, sym::uninitialized];
1908 // `transmute` is inside an anonymous module (the `extern` block?);
1909 // `Invalid` represents the empty string and matches that.
1910 const TRANSMUTE_PATH: &[Symbol] =
1911 &[sym::core, sym::intrinsics, kw::Invalid, sym::transmute];
1913 if let hir::ExprKind::Call(ref path_expr, ref args) = expr.node {
1914 if let hir::ExprKind::Path(ref qpath) = path_expr.node {
1915 let def_id = cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
1917 if cx.match_def_path(def_id, ZEROED_PATH) {
1918 return Some(InitKind::Zeroed);
1920 if cx.match_def_path(def_id, UININIT_PATH) {
1921 return Some(InitKind::Uninit);
1923 if cx.match_def_path(def_id, TRANSMUTE_PATH) {
1924 if is_zero(&args[0]) {
1925 return Some(InitKind::Zeroed);
1928 // FIXME: Also detect `MaybeUninit::zeroed().assume_init()` and
1929 // `MaybeUninit::uninit().assume_init()`.
1936 /// Return `Some` only if we are sure this type does *not*
1937 /// allow zero initialization.
1938 fn ty_find_init_error<'tcx>(
1942 ) -> Option<InitError> {
1943 use rustc::ty::TyKind::*;
1945 // Primitive types that don't like 0 as a value.
1946 Ref(..) => Some((format!("References must be non-null"), None)),
1947 Adt(..) if ty.is_box() => Some((format!("`Box` must be non-null"), None)),
1948 FnPtr(..) => Some((format!("Function pointers must be non-null"), None)),
1949 Never => Some((format!("The never type (`!`) has no valid value"), None)),
1950 // Primitive types with other constraints.
1951 Bool if init == InitKind::Uninit =>
1952 Some((format!("Booleans must be `true` or `false`"), None)),
1953 Char if init == InitKind::Uninit =>
1954 Some((format!("Characters must be a valid unicode codepoint"), None)),
1955 // Recurse and checks for some compound types.
1956 Adt(adt_def, substs) if !adt_def.is_union() => {
1957 // First check f this ADT has a layout attribute (like `NonNull` and friends).
1958 use std::ops::Bound;
1959 match tcx.layout_scalar_valid_range(adt_def.did) {
1960 // We exploit here that `layout_scalar_valid_range` will never
1961 // return `Bound::Excluded`. (And we have tests checking that we
1962 // handle the attribute correctly.)
1963 (Bound::Included(lo), _) if lo > 0 =>
1964 return Some((format!("{} must be non-null", ty), None)),
1965 (Bound::Included(_), _) | (_, Bound::Included(_))
1966 if init == InitKind::Uninit =>
1968 format!("{} must be initialized inside its custom valid range", ty),
1974 match adt_def.variants.len() {
1975 0 => Some((format!("0-variant enums have no valid value"), None)),
1977 // Struct, or enum with exactly one variant.
1978 // Proceed recursively, check all fields.
1979 let variant = &adt_def.variants[VariantIdx::from_u32(0)];
1980 variant.fields.iter().find_map(|field| {
1983 field.ty(tcx, substs),
1985 ).map(|(mut msg, span)| if span.is_none() {
1986 // Point to this field, should be helpful for figuring
1987 // out where the source of the error is.
1988 let span = tcx.def_span(field.did);
1989 write!(&mut msg, " (in this {} field)", adt_def.descr())
1998 // Multi-variant enums are tricky: if all but one variant are
1999 // uninhabited, we might actually do layout like for a single-variant
2000 // enum, and then even leaving them uninitialized could be okay.
2001 _ => None, // Conservative fallback for multi-variant enum.
2005 // Proceed recursively, check all fields.
2006 ty.tuple_fields().find_map(|field| ty_find_init_error(tcx, field, init))
2008 // Conservative fallback.
2013 if let Some(init) = is_dangerous_init(cx, expr) {
2014 // This conjures an instance of a type out of nothing,
2015 // using zeroed or uninitialized memory.
2016 // We are extremely conservative with what we warn about.
2017 let conjured_ty = cx.tables.expr_ty(expr);
2018 if let Some((msg, span)) = ty_find_init_error(cx.tcx, conjured_ty, init) {
2019 let mut err = cx.struct_span_lint(
2023 "the type `{}` does not permit {}",
2026 InitKind::Zeroed => "zero-initialization",
2027 InitKind::Uninit => "being left uninitialized",
2031 err.span_label(expr.span,
2032 "this code causes undefined behavior when executed");
2033 err.span_label(expr.span, "help: use `MaybeUninit<T>` instead");
2034 if let Some(span) = span {
2035 err.span_note(span, &msg);