]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
Rollup merge of #67358 - cuviper:get_or_insert_owned, r=LukasKalbertodt
[rust.git] / src / librustc_lint / builtin.rs
1 //! Lints in the Rust compiler.
2 //!
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
6 //! compiler.
7 //!
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).
15 //!
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()`.
20 //!
21 //! If you define a new `LateLintPass`, you will also need to add it to the
22 //! `late_lint_methods!` invocation in `lib.rs`.
23
24 use std::fmt::Write;
25
26 use lint::{EarlyContext, EarlyLintPass, LateLintPass, LintPass};
27 use lint::{LateContext, LintArray, LintContext};
28 use rustc::hir::map::Map;
29 use rustc::lint;
30 use rustc::lint::FutureIncompatibleInfo;
31 use rustc::traits::misc::can_type_implement_copy;
32 use rustc::ty::{self, layout::VariantIdx, Ty, TyCtxt};
33 use rustc_data_structures::fx::FxHashSet;
34 use rustc_feature::Stability;
35 use rustc_feature::{deprecated_attributes, AttributeGate, AttributeTemplate, AttributeType};
36 use rustc_hir as hir;
37 use rustc_hir::def::{DefKind, Res};
38 use rustc_hir::def_id::DefId;
39 use rustc_hir::{GenericParamKind, PatKind};
40 use rustc_hir::{HirIdSet, Node};
41 use rustc_span::edition::Edition;
42 use rustc_span::source_map::Spanned;
43 use rustc_span::symbol::{kw, sym, Symbol};
44 use rustc_span::{BytePos, Span};
45 use syntax::ast::{self, Expr};
46 use syntax::attr::{self, HasAttrs};
47 use syntax::errors::{Applicability, DiagnosticBuilder};
48 use syntax::print::pprust::{self, expr_to_string};
49 use syntax::ptr::P;
50 use syntax::tokenstream::{TokenStream, TokenTree};
51 use syntax::visit::FnKind;
52
53 use crate::nonstandard_style::{method_context, MethodLateContext};
54
55 use log::debug;
56
57 // hardwired lints from librustc
58 pub use lint::builtin::*;
59
60 declare_lint! {
61     WHILE_TRUE,
62     Warn,
63     "suggest using `loop { }` instead of `while true { }`"
64 }
65
66 declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
67
68 /// Traverse through any amount of parenthesis and return the first non-parens expression.
69 fn pierce_parens(mut expr: &ast::Expr) -> &ast::Expr {
70     while let ast::ExprKind::Paren(sub) = &expr.kind {
71         expr = sub;
72     }
73     expr
74 }
75
76 impl EarlyLintPass for WhileTrue {
77     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
78         if let ast::ExprKind::While(cond, ..) = &e.kind {
79             if let ast::ExprKind::Lit(ref lit) = pierce_parens(cond).kind {
80                 if let ast::LitKind::Bool(true) = lit.kind {
81                     if !lit.span.from_expansion() {
82                         let msg = "denote infinite loops with `loop { ... }`";
83                         let condition_span = cx.sess.source_map().def_span(e.span);
84                         cx.struct_span_lint(WHILE_TRUE, condition_span, msg)
85                             .span_suggestion_short(
86                                 condition_span,
87                                 "use `loop`",
88                                 "loop".to_owned(),
89                                 Applicability::MachineApplicable,
90                             )
91                             .emit();
92                     }
93                 }
94             }
95         }
96     }
97 }
98
99 declare_lint! {
100     BOX_POINTERS,
101     Allow,
102     "use of owned (Box type) heap memory"
103 }
104
105 declare_lint_pass!(BoxPointers => [BOX_POINTERS]);
106
107 impl BoxPointers {
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);
113             }
114         }
115     }
116 }
117
118 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
119     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
120         match it.kind {
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))
128             }
129             _ => (),
130         }
131
132         // If it's a struct, we also have to check the fields' types
133         match it.kind {
134             hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
135                 for struct_field in struct_def.fields() {
136                     let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id);
137                     self.check_heap_type(cx, struct_field.span, cx.tcx.type_of(def_id));
138                 }
139             }
140             _ => (),
141         }
142     }
143
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);
147     }
148 }
149
150 declare_lint! {
151     NON_SHORTHAND_FIELD_PATTERNS,
152     Warn,
153     "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
154 }
155
156 declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
157
158 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
159     fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>) {
160         if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
161             let variant = cx
162                 .tables
163                 .pat_ty(pat)
164                 .ty_adt_def()
165                 .expect("struct pattern type is not an ADT")
166                 .variant_of_res(cx.tables.qpath_res(qpath, pat.hir_id));
167             for fieldpat in field_pats {
168                 if fieldpat.is_shorthand {
169                     continue;
170                 }
171                 if fieldpat.span.from_expansion() {
172                     // Don't lint if this is a macro expansion: macro authors
173                     // shouldn't have to worry about this kind of style issue
174                     // (Issue #49588)
175                     continue;
176                 }
177                 if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind {
178                     if cx.tcx.find_field_index(ident, &variant)
179                         == Some(cx.tcx.field_index(fieldpat.hir_id, cx.tables))
180                     {
181                         let mut err = cx.struct_span_lint(
182                             NON_SHORTHAND_FIELD_PATTERNS,
183                             fieldpat.span,
184                             &format!("the `{}:` in this pattern is redundant", ident),
185                         );
186                         let binding = match binding_annot {
187                             hir::BindingAnnotation::Unannotated => None,
188                             hir::BindingAnnotation::Mutable => Some("mut"),
189                             hir::BindingAnnotation::Ref => Some("ref"),
190                             hir::BindingAnnotation::RefMut => Some("ref mut"),
191                         };
192                         let ident = if let Some(binding) = binding {
193                             format!("{} {}", binding, ident)
194                         } else {
195                             ident.to_string()
196                         };
197                         err.span_suggestion(
198                             fieldpat.span,
199                             "use shorthand field pattern",
200                             ident,
201                             Applicability::MachineApplicable,
202                         );
203                         err.emit();
204                     }
205                 }
206             }
207         }
208     }
209 }
210
211 declare_lint! {
212     UNSAFE_CODE,
213     Allow,
214     "usage of `unsafe` code"
215 }
216
217 declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
218
219 impl UnsafeCode {
220     fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) {
221         // This comes from a macro that has `#[allow_internal_unsafe]`.
222         if span.allows_unsafe() {
223             return;
224         }
225
226         cx.span_lint(UNSAFE_CODE, span, desc);
227     }
228 }
229
230 impl EarlyLintPass for UnsafeCode {
231     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
232         if attr.check_name(sym::allow_internal_unsafe) {
233             self.report_unsafe(
234                 cx,
235                 attr.span,
236                 "`allow_internal_unsafe` allows defining \
237                                                macros using unsafe without triggering \
238                                                the `unsafe_code` lint at their call site",
239             );
240         }
241     }
242
243     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
244         if let ast::ExprKind::Block(ref blk, _) = e.kind {
245             // Don't warn about generated blocks; that'll just pollute the output.
246             if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
247                 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
248             }
249         }
250     }
251
252     fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
253         match it.kind {
254             ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => {
255                 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
256             }
257
258             ast::ItemKind::Impl(ast::Unsafety::Unsafe, ..) => {
259                 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
260             }
261
262             _ => return,
263         }
264     }
265
266     fn check_fn(
267         &mut self,
268         cx: &EarlyContext<'_>,
269         fk: FnKind<'_>,
270         _: &ast::FnDecl,
271         span: Span,
272         _: ast::NodeId,
273     ) {
274         match fk {
275             FnKind::ItemFn(_, ast::FnHeader { unsafety: ast::Unsafety::Unsafe, .. }, ..) => {
276                 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
277             }
278
279             FnKind::Method(_, sig, ..) => {
280                 if sig.header.unsafety == ast::Unsafety::Unsafe {
281                     self.report_unsafe(cx, span, "implementation of an `unsafe` method")
282                 }
283             }
284
285             _ => (),
286         }
287     }
288
289     fn check_trait_item(&mut self, cx: &EarlyContext<'_>, item: &ast::AssocItem) {
290         if let ast::AssocItemKind::Fn(ref sig, None) = item.kind {
291             if sig.header.unsafety == ast::Unsafety::Unsafe {
292                 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
293             }
294         }
295     }
296 }
297
298 declare_lint! {
299     pub MISSING_DOCS,
300     Allow,
301     "detects missing documentation for public members",
302     report_in_external_macro
303 }
304
305 pub struct MissingDoc {
306     /// Stack of whether `#[doc(hidden)]` is set at each level which has lint attributes.
307     doc_hidden_stack: Vec<bool>,
308
309     /// Private traits or trait items that leaked through. Don't check their methods.
310     private_traits: FxHashSet<hir::HirId>,
311 }
312
313 impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
314
315 fn has_doc(attr: &ast::Attribute) -> bool {
316     if attr.is_doc_comment() {
317         return true;
318     }
319
320     if !attr.check_name(sym::doc) {
321         return false;
322     }
323
324     if attr.is_value_str() {
325         return true;
326     }
327
328     if let Some(list) = attr.meta_item_list() {
329         for meta in list {
330             if meta.check_name(sym::include) || meta.check_name(sym::hidden) {
331                 return true;
332             }
333         }
334     }
335
336     false
337 }
338
339 impl MissingDoc {
340     pub fn new() -> MissingDoc {
341         MissingDoc { doc_hidden_stack: vec![false], private_traits: FxHashSet::default() }
342     }
343
344     fn doc_hidden(&self) -> bool {
345         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
346     }
347
348     fn check_missing_docs_attrs(
349         &self,
350         cx: &LateContext<'_, '_>,
351         id: Option<hir::HirId>,
352         attrs: &[ast::Attribute],
353         sp: Span,
354         desc: &'static str,
355     ) {
356         // If we're building a test harness, then warning about
357         // documentation is probably not really relevant right now.
358         if cx.sess().opts.test {
359             return;
360         }
361
362         // `#[doc(hidden)]` disables missing_docs check.
363         if self.doc_hidden() {
364             return;
365         }
366
367         // Only check publicly-visible items, using the result from the privacy pass.
368         // It's an option so the crate root can also use this function (it doesn't
369         // have a `NodeId`).
370         if let Some(id) = id {
371             if !cx.access_levels.is_exported(id) {
372                 return;
373             }
374         }
375
376         let has_doc = attrs.iter().any(|a| has_doc(a));
377         if !has_doc {
378             cx.span_lint(
379                 MISSING_DOCS,
380                 cx.tcx.sess.source_map().def_span(sp),
381                 &format!("missing documentation for {}", desc),
382             );
383         }
384     }
385 }
386
387 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
388     fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) {
389         let doc_hidden = self.doc_hidden()
390             || attrs.iter().any(|attr| {
391                 attr.check_name(sym::doc)
392                     && match attr.meta_item_list() {
393                         None => false,
394                         Some(l) => attr::list_contains_name(&l, sym::hidden),
395                     }
396             });
397         self.doc_hidden_stack.push(doc_hidden);
398     }
399
400     fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) {
401         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
402     }
403
404     fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate<'_>) {
405         self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
406
407         for macro_def in krate.exported_macros {
408             let has_doc = macro_def.attrs.iter().any(|a| has_doc(a));
409             if !has_doc {
410                 cx.span_lint(
411                     MISSING_DOCS,
412                     cx.tcx.sess.source_map().def_span(macro_def.span),
413                     "missing documentation for macro",
414                 );
415             }
416         }
417     }
418
419     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
420         let desc = match it.kind {
421             hir::ItemKind::Fn(..) => "a function",
422             hir::ItemKind::Mod(..) => "a module",
423             hir::ItemKind::Enum(..) => "an enum",
424             hir::ItemKind::Struct(..) => "a struct",
425             hir::ItemKind::Union(..) => "a union",
426             hir::ItemKind::Trait(.., trait_item_refs) => {
427                 // Issue #11592: traits are always considered exported, even when private.
428                 if let hir::VisibilityKind::Inherited = it.vis.node {
429                     self.private_traits.insert(it.hir_id);
430                     for trait_item_ref in trait_item_refs {
431                         self.private_traits.insert(trait_item_ref.id.hir_id);
432                     }
433                     return;
434                 }
435                 "a trait"
436             }
437             hir::ItemKind::TyAlias(..) => "a type alias",
438             hir::ItemKind::Impl(.., Some(ref trait_ref), _, impl_item_refs) => {
439                 // If the trait is private, add the impl items to `private_traits` so they don't get
440                 // reported for missing docs.
441                 let real_trait = trait_ref.path.res.def_id();
442                 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(real_trait) {
443                     match cx.tcx.hir().find(hir_id) {
444                         Some(Node::Item(item)) => {
445                             if let hir::VisibilityKind::Inherited = item.vis.node {
446                                 for impl_item_ref in impl_item_refs {
447                                     self.private_traits.insert(impl_item_ref.id.hir_id);
448                                 }
449                             }
450                         }
451                         _ => {}
452                     }
453                 }
454                 return;
455             }
456             hir::ItemKind::Const(..) => "a constant",
457             hir::ItemKind::Static(..) => "a static",
458             _ => return,
459         };
460
461         self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, desc);
462     }
463
464     fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem<'_>) {
465         if self.private_traits.contains(&trait_item.hir_id) {
466             return;
467         }
468
469         let desc = match trait_item.kind {
470             hir::TraitItemKind::Const(..) => "an associated constant",
471             hir::TraitItemKind::Method(..) => "a trait method",
472             hir::TraitItemKind::Type(..) => "an associated type",
473         };
474
475         self.check_missing_docs_attrs(
476             cx,
477             Some(trait_item.hir_id),
478             &trait_item.attrs,
479             trait_item.span,
480             desc,
481         );
482     }
483
484     fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem<'_>) {
485         // If the method is an impl for a trait, don't doc.
486         if method_context(cx, impl_item.hir_id) == MethodLateContext::TraitImpl {
487             return;
488         }
489
490         let desc = match impl_item.kind {
491             hir::ImplItemKind::Const(..) => "an associated constant",
492             hir::ImplItemKind::Method(..) => "a method",
493             hir::ImplItemKind::TyAlias(_) => "an associated type",
494             hir::ImplItemKind::OpaqueTy(_) => "an associated `impl Trait` type",
495         };
496         self.check_missing_docs_attrs(
497             cx,
498             Some(impl_item.hir_id),
499             &impl_item.attrs,
500             impl_item.span,
501             desc,
502         );
503     }
504
505     fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField<'_>) {
506         if !sf.is_positional() {
507             self.check_missing_docs_attrs(cx, Some(sf.hir_id), &sf.attrs, sf.span, "a struct field")
508         }
509     }
510
511     fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant<'_>) {
512         self.check_missing_docs_attrs(cx, Some(v.id), &v.attrs, v.span, "a variant");
513     }
514 }
515
516 declare_lint! {
517     pub MISSING_COPY_IMPLEMENTATIONS,
518     Allow,
519     "detects potentially-forgotten implementations of `Copy`"
520 }
521
522 declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
523
524 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
525     fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
526         if !cx.access_levels.is_reachable(item.hir_id) {
527             return;
528         }
529         let (def, ty) = match item.kind {
530             hir::ItemKind::Struct(_, ref ast_generics) => {
531                 if !ast_generics.params.is_empty() {
532                     return;
533                 }
534                 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
535                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
536             }
537             hir::ItemKind::Union(_, ref ast_generics) => {
538                 if !ast_generics.params.is_empty() {
539                     return;
540                 }
541                 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
542                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
543             }
544             hir::ItemKind::Enum(_, ref ast_generics) => {
545                 if !ast_generics.params.is_empty() {
546                     return;
547                 }
548                 let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.hir_id));
549                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
550             }
551             _ => return,
552         };
553         if def.has_dtor(cx.tcx) {
554             return;
555         }
556         let param_env = ty::ParamEnv::empty();
557         if ty.is_copy_modulo_regions(cx.tcx, param_env, item.span) {
558             return;
559         }
560         if can_type_implement_copy(cx.tcx, param_env, ty).is_ok() {
561             cx.span_lint(
562                 MISSING_COPY_IMPLEMENTATIONS,
563                 item.span,
564                 "type could implement `Copy`; consider adding `impl \
565                           Copy`",
566             )
567         }
568     }
569 }
570
571 declare_lint! {
572     MISSING_DEBUG_IMPLEMENTATIONS,
573     Allow,
574     "detects missing implementations of fmt::Debug"
575 }
576
577 #[derive(Default)]
578 pub struct MissingDebugImplementations {
579     impling_types: Option<HirIdSet>,
580 }
581
582 impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
583
584 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
585     fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
586         if !cx.access_levels.is_reachable(item.hir_id) {
587             return;
588         }
589
590         match item.kind {
591             hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {}
592             _ => return,
593         }
594
595         let debug = match cx.tcx.get_diagnostic_item(sym::debug_trait) {
596             Some(debug) => debug,
597             None => return,
598         };
599
600         if self.impling_types.is_none() {
601             let mut impls = HirIdSet::default();
602             cx.tcx.for_each_impl(debug, |d| {
603                 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
604                     if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
605                         impls.insert(hir_id);
606                     }
607                 }
608             });
609
610             self.impling_types = Some(impls);
611             debug!("{:?}", self.impling_types);
612         }
613
614         if !self.impling_types.as_ref().unwrap().contains(&item.hir_id) {
615             cx.span_lint(
616                 MISSING_DEBUG_IMPLEMENTATIONS,
617                 item.span,
618                 "type does not implement `fmt::Debug`; consider adding `#[derive(Debug)]` \
619                           or a manual implementation",
620             )
621         }
622     }
623 }
624
625 declare_lint! {
626     pub ANONYMOUS_PARAMETERS,
627     Allow,
628     "detects anonymous parameters",
629     @future_incompatible = FutureIncompatibleInfo {
630         reference: "issue #41686 <https://github.com/rust-lang/rust/issues/41686>",
631         edition: Some(Edition::Edition2018),
632     };
633 }
634
635 declare_lint_pass!(
636     /// Checks for use of anonymous parameters (RFC 1685).
637     AnonymousParameters => [ANONYMOUS_PARAMETERS]
638 );
639
640 impl EarlyLintPass for AnonymousParameters {
641     fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
642         match it.kind {
643             ast::AssocItemKind::Fn(ref sig, _) => {
644                 for arg in sig.decl.inputs.iter() {
645                     match arg.pat.kind {
646                         ast::PatKind::Ident(_, ident, None) => {
647                             if ident.name == kw::Invalid {
648                                 let ty_snip = cx.sess.source_map().span_to_snippet(arg.ty.span);
649
650                                 let (ty_snip, appl) = if let Ok(snip) = ty_snip {
651                                     (snip, Applicability::MachineApplicable)
652                                 } else {
653                                     ("<type>".to_owned(), Applicability::HasPlaceholders)
654                                 };
655
656                                 cx.struct_span_lint(
657                                     ANONYMOUS_PARAMETERS,
658                                     arg.pat.span,
659                                     "anonymous parameters are deprecated and will be \
660                                      removed in the next edition.",
661                                 )
662                                 .span_suggestion(
663                                     arg.pat.span,
664                                     "Try naming the parameter or explicitly \
665                                     ignoring it",
666                                     format!("_: {}", ty_snip),
667                                     appl,
668                                 )
669                                 .emit();
670                             }
671                         }
672                         _ => (),
673                     }
674                 }
675             }
676             _ => (),
677         }
678     }
679 }
680
681 /// Check for use of attributes which have been deprecated.
682 #[derive(Clone)]
683 pub struct DeprecatedAttr {
684     // This is not free to compute, so we want to keep it around, rather than
685     // compute it for every attribute.
686     depr_attrs: Vec<&'static (Symbol, AttributeType, AttributeTemplate, AttributeGate)>,
687 }
688
689 impl_lint_pass!(DeprecatedAttr => []);
690
691 impl DeprecatedAttr {
692     pub fn new() -> DeprecatedAttr {
693         DeprecatedAttr { depr_attrs: deprecated_attributes() }
694     }
695 }
696
697 fn lint_deprecated_attr(
698     cx: &EarlyContext<'_>,
699     attr: &ast::Attribute,
700     msg: &str,
701     suggestion: Option<&str>,
702 ) {
703     cx.struct_span_lint(DEPRECATED, attr.span, &msg)
704         .span_suggestion_short(
705             attr.span,
706             suggestion.unwrap_or("remove this attribute"),
707             String::new(),
708             Applicability::MachineApplicable,
709         )
710         .emit();
711 }
712
713 impl EarlyLintPass for DeprecatedAttr {
714     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
715         for &&(n, _, _, ref g) in &self.depr_attrs {
716             if attr.ident().map(|ident| ident.name) == Some(n) {
717                 if let &AttributeGate::Gated(
718                     Stability::Deprecated(link, suggestion),
719                     ref name,
720                     ref reason,
721                     _,
722                 ) = g
723                 {
724                     let msg =
725                         format!("use of deprecated attribute `{}`: {}. See {}", name, reason, link);
726                     lint_deprecated_attr(cx, attr, &msg, suggestion);
727                 }
728                 return;
729             }
730         }
731         if attr.check_name(sym::no_start) || attr.check_name(sym::crate_id) {
732             let path_str = pprust::path_to_string(&attr.get_normal_item().path);
733             let msg = format!("use of deprecated attribute `{}`: no longer used.", path_str);
734             lint_deprecated_attr(cx, attr, &msg, None);
735         }
736     }
737 }
738
739 declare_lint! {
740     pub UNUSED_DOC_COMMENTS,
741     Warn,
742     "detects doc comments that aren't used by rustdoc"
743 }
744
745 declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]);
746
747 impl UnusedDocComment {
748     fn warn_if_doc(
749         &self,
750         cx: &EarlyContext<'_>,
751         node_span: Span,
752         node_kind: &str,
753         is_macro_expansion: bool,
754         attrs: &[ast::Attribute],
755     ) {
756         let mut attrs = attrs.into_iter().peekable();
757
758         // Accumulate a single span for sugared doc comments.
759         let mut sugared_span: Option<Span> = None;
760
761         while let Some(attr) = attrs.next() {
762             if attr.is_doc_comment() {
763                 sugared_span = Some(
764                     sugared_span.map_or_else(|| attr.span, |span| span.with_hi(attr.span.hi())),
765                 );
766             }
767
768             if attrs.peek().map(|next_attr| next_attr.is_doc_comment()).unwrap_or_default() {
769                 continue;
770             }
771
772             let span = sugared_span.take().unwrap_or_else(|| attr.span);
773
774             if attr.is_doc_comment() || attr.check_name(sym::doc) {
775                 let mut err = cx.struct_span_lint(UNUSED_DOC_COMMENTS, span, "unused doc comment");
776
777                 err.span_label(
778                     node_span,
779                     format!("rustdoc does not generate documentation for {}", node_kind),
780                 );
781
782                 if is_macro_expansion {
783                     err.help(
784                         "to document an item produced by a macro, \
785                               the macro must produce the documentation as part of its expansion",
786                     );
787                 }
788
789                 err.emit();
790             }
791         }
792     }
793 }
794
795 impl EarlyLintPass for UnusedDocComment {
796     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
797         if let ast::ItemKind::Mac(..) = item.kind {
798             self.warn_if_doc(cx, item.span, "macro expansions", true, &item.attrs);
799         }
800     }
801
802     fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
803         let (kind, is_macro_expansion) = match stmt.kind {
804             ast::StmtKind::Local(..) => ("statements", false),
805             ast::StmtKind::Item(..) => ("inner items", false),
806             ast::StmtKind::Mac(..) => ("macro expansions", true),
807             // expressions will be reported by `check_expr`.
808             ast::StmtKind::Semi(..) | ast::StmtKind::Expr(..) => return,
809         };
810
811         self.warn_if_doc(cx, stmt.span, kind, is_macro_expansion, stmt.kind.attrs());
812     }
813
814     fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
815         let arm_span = arm.pat.span.with_hi(arm.body.span.hi());
816         self.warn_if_doc(cx, arm_span, "match arms", false, &arm.attrs);
817     }
818
819     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
820         self.warn_if_doc(cx, expr.span, "expressions", false, &expr.attrs);
821     }
822 }
823
824 declare_lint! {
825     NO_MANGLE_CONST_ITEMS,
826     Deny,
827     "const items will not have their symbols exported"
828 }
829
830 declare_lint! {
831     NO_MANGLE_GENERIC_ITEMS,
832     Warn,
833     "generic items must be mangled"
834 }
835
836 declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
837
838 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
839     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
840         match it.kind {
841             hir::ItemKind::Fn(.., ref generics, _) => {
842                 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
843                     for param in generics.params {
844                         match param.kind {
845                             GenericParamKind::Lifetime { .. } => {}
846                             GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
847                                 let mut err = cx.struct_span_lint(
848                                     NO_MANGLE_GENERIC_ITEMS,
849                                     it.span,
850                                     "functions generic over types or consts must be mangled",
851                                 );
852                                 err.span_suggestion_short(
853                                     no_mangle_attr.span,
854                                     "remove this attribute",
855                                     String::new(),
856                                     // Use of `#[no_mangle]` suggests FFI intent; correct
857                                     // fix may be to monomorphize source by hand
858                                     Applicability::MaybeIncorrect,
859                                 );
860                                 err.emit();
861                                 break;
862                             }
863                         }
864                     }
865                 }
866             }
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);
873
874                     // account for "pub const" (#45562)
875                     let start = cx
876                         .tcx
877                         .sess
878                         .source_map()
879                         .span_to_snippet(it.span)
880                         .map(|snippet| snippet.find("const").unwrap_or(0))
881                         .unwrap_or(0) as u32;
882                     // `const` is 5 chars
883                     let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
884                     err.span_suggestion(
885                         const_span,
886                         "try a static value",
887                         "pub static".to_owned(),
888                         Applicability::MachineApplicable,
889                     );
890                     err.emit();
891                 }
892             }
893             _ => {}
894         }
895     }
896 }
897
898 declare_lint! {
899     MUTABLE_TRANSMUTES,
900     Deny,
901     "mutating transmuted &mut T from &T may cause undefined behavior"
902 }
903
904 declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
905
906 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
907     fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
908         use rustc_target::spec::abi::Abi::RustIntrinsic;
909
910         let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
911                    consider instead using an UnsafeCell";
912         match get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (&ty1.kind, &ty2.kind)) {
913             Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
914                 if to_mt == hir::Mutability::Mut && from_mt == hir::Mutability::Not {
915                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
916                 }
917             }
918             _ => (),
919         }
920
921         fn get_transmute_from_to<'a, 'tcx>(
922             cx: &LateContext<'a, 'tcx>,
923             expr: &hir::Expr<'_>,
924         ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
925             let def = if let hir::ExprKind::Path(ref qpath) = expr.kind {
926                 cx.tables.qpath_res(qpath, expr.hir_id)
927             } else {
928                 return None;
929             };
930             if let Res::Def(DefKind::Fn, did) = def {
931                 if !def_id_is_transmute(cx, did) {
932                     return None;
933                 }
934                 let sig = cx.tables.node_type(expr.hir_id).fn_sig(cx.tcx);
935                 let from = sig.inputs().skip_binder()[0];
936                 let to = *sig.output().skip_binder();
937                 return Some((from, to));
938             }
939             None
940         }
941
942         fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
943             cx.tcx.fn_sig(def_id).abi() == RustIntrinsic
944                 && cx.tcx.item_name(def_id) == sym::transmute
945         }
946     }
947 }
948
949 declare_lint! {
950     UNSTABLE_FEATURES,
951     Allow,
952     "enabling unstable features (deprecated. do not use)"
953 }
954
955 declare_lint_pass!(
956     /// Forbids using the `#[feature(...)]` attribute
957     UnstableFeatures => [UNSTABLE_FEATURES]
958 );
959
960 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
961     fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) {
962         if attr.check_name(sym::feature) {
963             if let Some(items) = attr.meta_item_list() {
964                 for item in items {
965                     ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
966                 }
967             }
968         }
969     }
970 }
971
972 declare_lint! {
973     pub UNREACHABLE_PUB,
974     Allow,
975     "`pub` items not reachable from crate root"
976 }
977
978 declare_lint_pass!(
979     /// Lint for items marked `pub` that aren't reachable from other crates.
980     UnreachablePub => [UNREACHABLE_PUB]
981 );
982
983 impl UnreachablePub {
984     fn perform_lint(
985         &self,
986         cx: &LateContext<'_, '_>,
987         what: &str,
988         id: hir::HirId,
989         vis: &hir::Visibility<'_>,
990         span: Span,
991         exportable: bool,
992     ) {
993         let mut applicability = Applicability::MachineApplicable;
994         match vis.node {
995             hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
996                 if span.from_expansion() {
997                     applicability = Applicability::MaybeIncorrect;
998                 }
999                 let def_span = cx.tcx.sess.source_map().def_span(span);
1000                 let mut err = cx.struct_span_lint(
1001                     UNREACHABLE_PUB,
1002                     def_span,
1003                     &format!("unreachable `pub` {}", what),
1004                 );
1005                 let replacement = if cx.tcx.features().crate_visibility_modifier {
1006                     "crate"
1007                 } else {
1008                     "pub(crate)"
1009                 }
1010                 .to_owned();
1011
1012                 err.span_suggestion(
1013                     vis.span,
1014                     "consider restricting its visibility",
1015                     replacement,
1016                     applicability,
1017                 );
1018                 if exportable {
1019                     err.help("or consider exporting it for use by other crates");
1020                 }
1021                 err.emit();
1022             }
1023             _ => {}
1024         }
1025     }
1026 }
1027
1028 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1029     fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
1030         self.perform_lint(cx, "item", item.hir_id, &item.vis, item.span, true);
1031     }
1032
1033     fn check_foreign_item(
1034         &mut self,
1035         cx: &LateContext<'_, '_>,
1036         foreign_item: &hir::ForeignItem<'tcx>,
1037     ) {
1038         self.perform_lint(
1039             cx,
1040             "item",
1041             foreign_item.hir_id,
1042             &foreign_item.vis,
1043             foreign_item.span,
1044             true,
1045         );
1046     }
1047
1048     fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField<'_>) {
1049         self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false);
1050     }
1051
1052     fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem<'_>) {
1053         self.perform_lint(cx, "item", impl_item.hir_id, &impl_item.vis, impl_item.span, false);
1054     }
1055 }
1056
1057 declare_lint! {
1058     TYPE_ALIAS_BOUNDS,
1059     Warn,
1060     "bounds in type aliases are not enforced"
1061 }
1062
1063 declare_lint_pass!(
1064     /// Lint for trait and lifetime bounds in type aliases being mostly ignored.
1065     /// They are relevant when using associated types, but otherwise neither checked
1066     /// at definition site nor enforced at use site.
1067     TypeAliasBounds => [TYPE_ALIAS_BOUNDS]
1068 );
1069
1070 impl TypeAliasBounds {
1071     fn is_type_variable_assoc(qpath: &hir::QPath<'_>) -> bool {
1072         match *qpath {
1073             hir::QPath::TypeRelative(ref ty, _) => {
1074                 // If this is a type variable, we found a `T::Assoc`.
1075                 match ty.kind {
1076                     hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => match path.res {
1077                         Res::Def(DefKind::TyParam, _) => true,
1078                         _ => false,
1079                     },
1080                     _ => false,
1081                 }
1082             }
1083             hir::QPath::Resolved(..) => false,
1084         }
1085     }
1086
1087     fn suggest_changing_assoc_types(ty: &hir::Ty<'_>, err: &mut DiagnosticBuilder<'_>) {
1088         // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
1089         // bound.  Let's see if this type does that.
1090
1091         // We use a HIR visitor to walk the type.
1092         use rustc_hir::intravisit::{self, Visitor};
1093         struct WalkAssocTypes<'a, 'db> {
1094             err: &'a mut DiagnosticBuilder<'db>,
1095         }
1096         impl<'a, 'db, 'v> Visitor<'v> for WalkAssocTypes<'a, 'db> {
1097             type Map = Map<'v>;
1098
1099             fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
1100                 intravisit::NestedVisitorMap::None
1101             }
1102
1103             fn visit_qpath(&mut self, qpath: &'v hir::QPath<'v>, id: hir::HirId, span: Span) {
1104                 if TypeAliasBounds::is_type_variable_assoc(qpath) {
1105                     self.err.span_help(
1106                         span,
1107                         "use fully disambiguated paths (i.e., `<T as Trait>::Assoc`) to refer to \
1108                          associated types in type aliases",
1109                     );
1110                 }
1111                 intravisit::walk_qpath(self, qpath, id, span)
1112             }
1113         }
1114
1115         // Let's go for a walk!
1116         let mut visitor = WalkAssocTypes { err };
1117         visitor.visit_ty(ty);
1118     }
1119 }
1120
1121 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
1122     fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
1123         let (ty, type_alias_generics) = match item.kind {
1124             hir::ItemKind::TyAlias(ref ty, ref generics) => (&*ty, generics),
1125             _ => return,
1126         };
1127         let mut suggested_changing_assoc_types = false;
1128         // There must not be a where clause
1129         if !type_alias_generics.where_clause.predicates.is_empty() {
1130             let spans: Vec<_> = type_alias_generics
1131                 .where_clause
1132                 .predicates
1133                 .iter()
1134                 .map(|pred| pred.span())
1135                 .collect();
1136             let mut err = cx.struct_span_lint(
1137                 TYPE_ALIAS_BOUNDS,
1138                 spans,
1139                 "where clauses are not enforced in type aliases",
1140             );
1141             err.span_suggestion(
1142                 type_alias_generics.where_clause.span_for_predicates_or_empty_place(),
1143                 "the clause will not be checked when the type alias is used, and should be removed",
1144                 String::new(),
1145                 Applicability::MachineApplicable,
1146             );
1147             if !suggested_changing_assoc_types {
1148                 TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1149                 suggested_changing_assoc_types = true;
1150             }
1151             err.emit();
1152         }
1153         // The parameters must not have bounds
1154         for param in type_alias_generics.params.iter() {
1155             let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
1156             let suggestion = spans
1157                 .iter()
1158                 .map(|sp| {
1159                     let start = param.span.between(*sp); // Include the `:` in `T: Bound`.
1160                     (start.to(*sp), String::new())
1161                 })
1162                 .collect();
1163             if !spans.is_empty() {
1164                 let mut err = cx.struct_span_lint(
1165                     TYPE_ALIAS_BOUNDS,
1166                     spans,
1167                     "bounds on generic parameters are not enforced in type aliases",
1168                 );
1169                 let msg = "the bound will not be checked when the type alias is used, \
1170                            and should be removed";
1171                 err.multipart_suggestion(&msg, suggestion, Applicability::MachineApplicable);
1172                 if !suggested_changing_assoc_types {
1173                     TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err);
1174                     suggested_changing_assoc_types = true;
1175                 }
1176                 err.emit();
1177             }
1178         }
1179     }
1180 }
1181
1182 declare_lint_pass!(
1183     /// Lint constants that are erroneous.
1184     /// Without this lint, we might not get any diagnostic if the constant is
1185     /// unused within this crate, even though downstream crates can't use it
1186     /// without producing an error.
1187     UnusedBrokenConst => []
1188 );
1189
1190 fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) {
1191     let def_id = cx.tcx.hir().body_owner_def_id(body_id);
1192     // trigger the query once for all constants since that will already report the errors
1193     // FIXME: Use ensure here
1194     let _ = cx.tcx.const_eval_poly(def_id);
1195 }
1196
1197 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
1198     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
1199         match it.kind {
1200             hir::ItemKind::Const(_, body_id) => {
1201                 check_const(cx, body_id);
1202             }
1203             hir::ItemKind::Static(_, _, body_id) => {
1204                 check_const(cx, body_id);
1205             }
1206             _ => {}
1207         }
1208     }
1209 }
1210
1211 declare_lint! {
1212     TRIVIAL_BOUNDS,
1213     Warn,
1214     "these bounds don't depend on an type parameters"
1215 }
1216
1217 declare_lint_pass!(
1218     /// Lint for trait and lifetime bounds that don't depend on type parameters
1219     /// which either do nothing, or stop the item from being used.
1220     TrivialConstraints => [TRIVIAL_BOUNDS]
1221 );
1222
1223 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints {
1224     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'tcx>) {
1225         use rustc::ty::fold::TypeFoldable;
1226         use rustc::ty::Predicate::*;
1227
1228         if cx.tcx.features().trivial_bounds {
1229             let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1230             let predicates = cx.tcx.predicates_of(def_id);
1231             for &(predicate, span) in predicates.predicates {
1232                 let predicate_kind_name = match predicate {
1233                     Trait(..) => "Trait",
1234                     TypeOutlives(..) |
1235                     RegionOutlives(..) => "Lifetime",
1236
1237                     // Ignore projections, as they can only be global
1238                     // if the trait bound is global
1239                     Projection(..) |
1240                     // Ignore bounds that a user can't type
1241                     WellFormed(..) |
1242                     ObjectSafe(..) |
1243                     ClosureKind(..) |
1244                     Subtype(..) |
1245                     ConstEvaluatable(..) => continue,
1246                 };
1247                 if predicate.is_global() {
1248                     cx.span_lint(
1249                         TRIVIAL_BOUNDS,
1250                         span,
1251                         &format!(
1252                             "{} bound {} does not depend on any type \
1253                                 or lifetime parameters",
1254                             predicate_kind_name, predicate
1255                         ),
1256                     );
1257                 }
1258             }
1259         }
1260     }
1261 }
1262
1263 declare_lint_pass!(
1264     /// Does nothing as a lint pass, but registers some `Lint`s
1265     /// which are used by other parts of the compiler.
1266     SoftLints => [
1267         WHILE_TRUE,
1268         BOX_POINTERS,
1269         NON_SHORTHAND_FIELD_PATTERNS,
1270         UNSAFE_CODE,
1271         MISSING_DOCS,
1272         MISSING_COPY_IMPLEMENTATIONS,
1273         MISSING_DEBUG_IMPLEMENTATIONS,
1274         ANONYMOUS_PARAMETERS,
1275         UNUSED_DOC_COMMENTS,
1276         NO_MANGLE_CONST_ITEMS,
1277         NO_MANGLE_GENERIC_ITEMS,
1278         MUTABLE_TRANSMUTES,
1279         UNSTABLE_FEATURES,
1280         UNREACHABLE_PUB,
1281         TYPE_ALIAS_BOUNDS,
1282         TRIVIAL_BOUNDS
1283     ]
1284 );
1285
1286 declare_lint! {
1287     pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1288     Warn,
1289     "`...` range patterns are deprecated"
1290 }
1291
1292 #[derive(Default)]
1293 pub struct EllipsisInclusiveRangePatterns {
1294     /// If `Some(_)`, suppress all subsequent pattern
1295     /// warnings for better diagnostics.
1296     node_id: Option<ast::NodeId>,
1297 }
1298
1299 impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1300
1301 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1302     fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1303         if self.node_id.is_some() {
1304             // Don't recursively warn about patterns inside range endpoints.
1305             return;
1306         }
1307
1308         use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot};
1309
1310         /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1311         /// corresponding to the ellipsis.
1312         fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(&P<Expr>, &P<Expr>, Span)> {
1313             match &pat.kind {
1314                 PatKind::Range(a, b, Spanned { span, node: RangeEnd::Included(DotDotDot), .. }) => {
1315                     Some((a, b, *span))
1316                 }
1317                 _ => None,
1318             }
1319         }
1320
1321         let (parenthesise, endpoints) = match &pat.kind {
1322             PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)),
1323             _ => (false, matches_ellipsis_pat(pat)),
1324         };
1325
1326         if let Some((start, end, join)) = endpoints {
1327             let msg = "`...` range patterns are deprecated";
1328             let suggestion = "use `..=` for an inclusive range";
1329             if parenthesise {
1330                 self.node_id = Some(pat.id);
1331                 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, pat.span, msg);
1332                 err.span_suggestion(
1333                     pat.span,
1334                     suggestion,
1335                     format!("&({}..={})", expr_to_string(&start), expr_to_string(&end)),
1336                     Applicability::MachineApplicable,
1337                 );
1338                 err.emit();
1339             } else {
1340                 let mut err = cx.struct_span_lint(ELLIPSIS_INCLUSIVE_RANGE_PATTERNS, join, msg);
1341                 err.span_suggestion_short(
1342                     join,
1343                     suggestion,
1344                     "..=".to_owned(),
1345                     Applicability::MachineApplicable,
1346                 );
1347                 err.emit();
1348             };
1349         }
1350     }
1351
1352     fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1353         if let Some(node_id) = self.node_id {
1354             if pat.id == node_id {
1355                 self.node_id = None
1356             }
1357         }
1358     }
1359 }
1360
1361 declare_lint! {
1362     UNNAMEABLE_TEST_ITEMS,
1363     Warn,
1364     "detects an item that cannot be named being marked as `#[test_case]`",
1365     report_in_external_macro
1366 }
1367
1368 pub struct UnnameableTestItems {
1369     boundary: hir::HirId, // HirId of the item under which things are not nameable
1370     items_nameable: bool,
1371 }
1372
1373 impl_lint_pass!(UnnameableTestItems => [UNNAMEABLE_TEST_ITEMS]);
1374
1375 impl UnnameableTestItems {
1376     pub fn new() -> Self {
1377         Self { boundary: hir::DUMMY_HIR_ID, items_nameable: true }
1378     }
1379 }
1380
1381 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
1382     fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
1383         if self.items_nameable {
1384             if let hir::ItemKind::Mod(..) = it.kind {
1385             } else {
1386                 self.items_nameable = false;
1387                 self.boundary = it.hir_id;
1388             }
1389             return;
1390         }
1391
1392         if let Some(attr) = attr::find_by_name(&it.attrs, sym::rustc_test_marker) {
1393             cx.struct_span_lint(UNNAMEABLE_TEST_ITEMS, attr.span, "cannot test inner items").emit();
1394         }
1395     }
1396
1397     fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item<'_>) {
1398         if !self.items_nameable && self.boundary == it.hir_id {
1399             self.items_nameable = true;
1400         }
1401     }
1402 }
1403
1404 declare_lint! {
1405     pub KEYWORD_IDENTS,
1406     Allow,
1407     "detects edition keywords being used as an identifier",
1408     @future_incompatible = FutureIncompatibleInfo {
1409         reference: "issue #49716 <https://github.com/rust-lang/rust/issues/49716>",
1410         edition: Some(Edition::Edition2018),
1411     };
1412 }
1413
1414 declare_lint_pass!(
1415     /// Check for uses of edition keywords used as an identifier.
1416     KeywordIdents => [KEYWORD_IDENTS]
1417 );
1418
1419 struct UnderMacro(bool);
1420
1421 impl KeywordIdents {
1422     fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) {
1423         for tt in tokens.into_trees() {
1424             match tt {
1425                 // Only report non-raw idents.
1426                 TokenTree::Token(token) => {
1427                     if let Some((ident, false)) = token.ident() {
1428                         self.check_ident_token(cx, UnderMacro(true), ident);
1429                     }
1430                 }
1431                 TokenTree::Delimited(_, _, tts) => self.check_tokens(cx, tts),
1432             }
1433         }
1434     }
1435
1436     fn check_ident_token(
1437         &mut self,
1438         cx: &EarlyContext<'_>,
1439         UnderMacro(under_macro): UnderMacro,
1440         ident: ast::Ident,
1441     ) {
1442         let next_edition = match cx.sess.edition() {
1443             Edition::Edition2015 => {
1444                 match ident.name {
1445                     kw::Async | kw::Await | kw::Try => Edition::Edition2018,
1446
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.
1454                     //
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
1458                     // an identifier.
1459                     kw::Dyn if !under_macro => Edition::Edition2018,
1460
1461                     _ => return,
1462                 }
1463             }
1464
1465             // There are no new keywords yet for the 2018 edition and beyond.
1466             _ => return,
1467         };
1468
1469         // Don't lint `r#foo`.
1470         if cx.sess.parse_sess.raw_identifier_spans.borrow().contains(&ident.span) {
1471             return;
1472         }
1473
1474         let mut lint = cx.struct_span_lint(
1475             KEYWORD_IDENTS,
1476             ident.span,
1477             &format!("`{}` is a keyword in the {} edition", ident, next_edition),
1478         );
1479         lint.span_suggestion(
1480             ident.span,
1481             "you can use a raw identifier to stay compatible",
1482             format!("r#{}", ident),
1483             Applicability::MachineApplicable,
1484         );
1485         lint.emit()
1486     }
1487 }
1488
1489 impl EarlyLintPass for KeywordIdents {
1490     fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) {
1491         self.check_tokens(cx, mac_def.body.inner_tokens());
1492     }
1493     fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
1494         self.check_tokens(cx, mac.args.inner_tokens());
1495     }
1496     fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: ast::Ident) {
1497         self.check_ident_token(cx, UnderMacro(false), ident);
1498     }
1499 }
1500
1501 declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1502
1503 impl ExplicitOutlivesRequirements {
1504     fn lifetimes_outliving_lifetime<'tcx>(
1505         inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)],
1506         index: u32,
1507     ) -> Vec<ty::Region<'tcx>> {
1508         inferred_outlives
1509             .iter()
1510             .filter_map(|(pred, _)| match pred {
1511                 ty::Predicate::RegionOutlives(outlives) => {
1512                     let outlives = outlives.skip_binder();
1513                     match outlives.0 {
1514                         ty::ReEarlyBound(ebr) if ebr.index == index => Some(outlives.1),
1515                         _ => None,
1516                     }
1517                 }
1518                 _ => None,
1519             })
1520             .collect()
1521     }
1522
1523     fn lifetimes_outliving_type<'tcx>(
1524         inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)],
1525         index: u32,
1526     ) -> Vec<ty::Region<'tcx>> {
1527         inferred_outlives
1528             .iter()
1529             .filter_map(|(pred, _)| match pred {
1530                 ty::Predicate::TypeOutlives(outlives) => {
1531                     let outlives = outlives.skip_binder();
1532                     outlives.0.is_param(index).then_some(outlives.1)
1533                 }
1534                 _ => None,
1535             })
1536             .collect()
1537     }
1538
1539     fn collect_outlived_lifetimes<'tcx>(
1540         &self,
1541         param: &'tcx hir::GenericParam<'tcx>,
1542         tcx: TyCtxt<'tcx>,
1543         inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)],
1544         ty_generics: &'tcx ty::Generics,
1545     ) -> Vec<ty::Region<'tcx>> {
1546         let index = ty_generics.param_def_id_to_index[&tcx.hir().local_def_id(param.hir_id)];
1547
1548         match param.kind {
1549             hir::GenericParamKind::Lifetime { .. } => {
1550                 Self::lifetimes_outliving_lifetime(inferred_outlives, index)
1551             }
1552             hir::GenericParamKind::Type { .. } => {
1553                 Self::lifetimes_outliving_type(inferred_outlives, index)
1554             }
1555             hir::GenericParamKind::Const { .. } => Vec::new(),
1556         }
1557     }
1558
1559     fn collect_outlives_bound_spans<'tcx>(
1560         &self,
1561         tcx: TyCtxt<'tcx>,
1562         bounds: &hir::GenericBounds<'_>,
1563         inferred_outlives: &[ty::Region<'tcx>],
1564         infer_static: bool,
1565     ) -> Vec<(usize, Span)> {
1566         use rustc::middle::resolve_lifetime::Region;
1567
1568         bounds
1569             .iter()
1570             .enumerate()
1571             .filter_map(|(i, bound)| {
1572                 if let hir::GenericBound::Outlives(lifetime) = bound {
1573                     let is_inferred = match tcx.named_region(lifetime.hir_id) {
1574                         Some(Region::Static) if infer_static => inferred_outlives
1575                             .iter()
1576                             .any(|r| if let ty::ReStatic = r { true } else { false }),
1577                         Some(Region::EarlyBound(index, ..)) => inferred_outlives.iter().any(|r| {
1578                             if let ty::ReEarlyBound(ebr) = r { ebr.index == index } else { false }
1579                         }),
1580                         _ => false,
1581                     };
1582                     is_inferred.then_some((i, bound.span()))
1583                 } else {
1584                     None
1585                 }
1586             })
1587             .collect()
1588     }
1589
1590     fn consolidate_outlives_bound_spans(
1591         &self,
1592         lo: Span,
1593         bounds: &hir::GenericBounds<'_>,
1594         bound_spans: Vec<(usize, Span)>,
1595     ) -> Vec<Span> {
1596         if bounds.is_empty() {
1597             return Vec::new();
1598         }
1599         if bound_spans.len() == bounds.len() {
1600             let (_, last_bound_span) = bound_spans[bound_spans.len() - 1];
1601             // If all bounds are inferable, we want to delete the colon, so
1602             // start from just after the parameter (span passed as argument)
1603             vec![lo.to(last_bound_span)]
1604         } else {
1605             let mut merged = Vec::new();
1606             let mut last_merged_i = None;
1607
1608             let mut from_start = true;
1609             for (i, bound_span) in bound_spans {
1610                 match last_merged_i {
1611                     // If the first bound is inferable, our span should also eat the leading `+`.
1612                     None if i == 0 => {
1613                         merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
1614                         last_merged_i = Some(0);
1615                     }
1616                     // If consecutive bounds are inferable, merge their spans
1617                     Some(h) if i == h + 1 => {
1618                         if let Some(tail) = merged.last_mut() {
1619                             // Also eat the trailing `+` if the first
1620                             // more-than-one bound is inferable
1621                             let to_span = if from_start && i < bounds.len() {
1622                                 bounds[i + 1].span().shrink_to_lo()
1623                             } else {
1624                                 bound_span
1625                             };
1626                             *tail = tail.to(to_span);
1627                             last_merged_i = Some(i);
1628                         } else {
1629                             bug!("another bound-span visited earlier");
1630                         }
1631                     }
1632                     _ => {
1633                         // When we find a non-inferable bound, subsequent inferable bounds
1634                         // won't be consecutive from the start (and we'll eat the leading
1635                         // `+` rather than the trailing one)
1636                         from_start = false;
1637                         merged.push(bounds[i - 1].span().shrink_to_hi().to(bound_span));
1638                         last_merged_i = Some(i);
1639                     }
1640                 }
1641             }
1642             merged
1643         }
1644     }
1645 }
1646
1647 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitOutlivesRequirements {
1648     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
1649         use rustc::middle::resolve_lifetime::Region;
1650
1651         let infer_static = cx.tcx.features().infer_static_outlives_requirements;
1652         let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1653         if let hir::ItemKind::Struct(_, ref hir_generics)
1654         | hir::ItemKind::Enum(_, ref hir_generics)
1655         | hir::ItemKind::Union(_, ref hir_generics) = item.kind
1656         {
1657             let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
1658             if inferred_outlives.is_empty() {
1659                 return;
1660             }
1661
1662             let ty_generics = cx.tcx.generics_of(def_id);
1663
1664             let mut bound_count = 0;
1665             let mut lint_spans = Vec::new();
1666
1667             for param in hir_generics.params {
1668                 let has_lifetime_bounds = param.bounds.iter().any(|bound| {
1669                     if let hir::GenericBound::Outlives(_) = bound { true } else { false }
1670                 });
1671                 if !has_lifetime_bounds {
1672                     continue;
1673                 }
1674
1675                 let relevant_lifetimes =
1676                     self.collect_outlived_lifetimes(param, cx.tcx, inferred_outlives, ty_generics);
1677                 if relevant_lifetimes.is_empty() {
1678                     continue;
1679                 }
1680
1681                 let bound_spans = self.collect_outlives_bound_spans(
1682                     cx.tcx,
1683                     &param.bounds,
1684                     &relevant_lifetimes,
1685                     infer_static,
1686                 );
1687                 bound_count += bound_spans.len();
1688                 lint_spans.extend(self.consolidate_outlives_bound_spans(
1689                     param.span.shrink_to_hi(),
1690                     &param.bounds,
1691                     bound_spans,
1692                 ));
1693             }
1694
1695             let mut where_lint_spans = Vec::new();
1696             let mut dropped_predicate_count = 0;
1697             let num_predicates = hir_generics.where_clause.predicates.len();
1698             for (i, where_predicate) in hir_generics.where_clause.predicates.iter().enumerate() {
1699                 let (relevant_lifetimes, bounds, span) = match where_predicate {
1700                     hir::WherePredicate::RegionPredicate(predicate) => {
1701                         if let Some(Region::EarlyBound(index, ..)) =
1702                             cx.tcx.named_region(predicate.lifetime.hir_id)
1703                         {
1704                             (
1705                                 Self::lifetimes_outliving_lifetime(inferred_outlives, index),
1706                                 &predicate.bounds,
1707                                 predicate.span,
1708                             )
1709                         } else {
1710                             continue;
1711                         }
1712                     }
1713                     hir::WherePredicate::BoundPredicate(predicate) => {
1714                         // FIXME we can also infer bounds on associated types,
1715                         // and should check for them here.
1716                         match predicate.bounded_ty.kind {
1717                             hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1718                                 if let Res::Def(DefKind::TyParam, def_id) = path.res {
1719                                     let index = ty_generics.param_def_id_to_index[&def_id];
1720                                     (
1721                                         Self::lifetimes_outliving_type(inferred_outlives, index),
1722                                         &predicate.bounds,
1723                                         predicate.span,
1724                                     )
1725                                 } else {
1726                                     continue;
1727                                 }
1728                             }
1729                             _ => {
1730                                 continue;
1731                             }
1732                         }
1733                     }
1734                     _ => continue,
1735                 };
1736                 if relevant_lifetimes.is_empty() {
1737                     continue;
1738                 }
1739
1740                 let bound_spans = self.collect_outlives_bound_spans(
1741                     cx.tcx,
1742                     bounds,
1743                     &relevant_lifetimes,
1744                     infer_static,
1745                 );
1746                 bound_count += bound_spans.len();
1747
1748                 let drop_predicate = bound_spans.len() == bounds.len();
1749                 if drop_predicate {
1750                     dropped_predicate_count += 1;
1751                 }
1752
1753                 // If all the bounds on a predicate were inferable and there are
1754                 // further predicates, we want to eat the trailing comma.
1755                 if drop_predicate && i + 1 < num_predicates {
1756                     let next_predicate_span = hir_generics.where_clause.predicates[i + 1].span();
1757                     where_lint_spans.push(span.to(next_predicate_span.shrink_to_lo()));
1758                 } else {
1759                     where_lint_spans.extend(self.consolidate_outlives_bound_spans(
1760                         span.shrink_to_lo(),
1761                         bounds,
1762                         bound_spans,
1763                     ));
1764                 }
1765             }
1766
1767             // If all predicates are inferable, drop the entire clause
1768             // (including the `where`)
1769             if num_predicates > 0 && dropped_predicate_count == num_predicates {
1770                 let where_span = hir_generics
1771                     .where_clause
1772                     .span()
1773                     .expect("span of (nonempty) where clause should exist");
1774                 // Extend the where clause back to the closing `>` of the
1775                 // generics, except for tuple struct, which have the `where`
1776                 // after the fields of the struct.
1777                 let full_where_span =
1778                     if let hir::ItemKind::Struct(hir::VariantData::Tuple(..), _) = item.kind {
1779                         where_span
1780                     } else {
1781                         hir_generics.span.shrink_to_hi().to(where_span)
1782                     };
1783                 lint_spans.push(full_where_span);
1784             } else {
1785                 lint_spans.extend(where_lint_spans);
1786             }
1787
1788             if !lint_spans.is_empty() {
1789                 let mut err = cx.struct_span_lint(
1790                     EXPLICIT_OUTLIVES_REQUIREMENTS,
1791                     lint_spans.clone(),
1792                     "outlives requirements can be inferred",
1793                 );
1794                 err.multipart_suggestion(
1795                     if bound_count == 1 { "remove this bound" } else { "remove these bounds" },
1796                     lint_spans.into_iter().map(|span| (span, "".to_owned())).collect::<Vec<_>>(),
1797                     Applicability::MachineApplicable,
1798                 );
1799                 err.emit();
1800             }
1801         }
1802     }
1803 }
1804
1805 declare_lint! {
1806     pub INCOMPLETE_FEATURES,
1807     Warn,
1808     "incomplete features that may function improperly in some or all cases"
1809 }
1810
1811 declare_lint_pass!(
1812     /// Check for used feature gates in `INCOMPLETE_FEATURES` in `feature_gate.rs`.
1813     IncompleteFeatures => [INCOMPLETE_FEATURES]
1814 );
1815
1816 impl EarlyLintPass for IncompleteFeatures {
1817     fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
1818         let features = cx.sess.features_untracked();
1819         features
1820             .declared_lang_features
1821             .iter()
1822             .map(|(name, span, _)| (name, span))
1823             .chain(features.declared_lib_features.iter().map(|(name, span)| (name, span)))
1824             .filter(|(name, _)| rustc_feature::INCOMPLETE_FEATURES.iter().any(|f| name == &f))
1825             .for_each(|(name, &span)| {
1826                 cx.struct_span_lint(
1827                     INCOMPLETE_FEATURES,
1828                     span,
1829                     &format!(
1830                         "the feature `{}` is incomplete and may cause the compiler to crash",
1831                         name,
1832                     ),
1833                 )
1834                 .emit();
1835             });
1836     }
1837 }
1838
1839 declare_lint! {
1840     pub INVALID_VALUE,
1841     Warn,
1842     "an invalid value is being created (such as a NULL reference)"
1843 }
1844
1845 declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
1846
1847 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidValue {
1848     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>) {
1849         #[derive(Debug, Copy, Clone, PartialEq)]
1850         enum InitKind {
1851             Zeroed,
1852             Uninit,
1853         };
1854
1855         /// Information about why a type cannot be initialized this way.
1856         /// Contains an error message and optionally a span to point at.
1857         type InitError = (String, Option<Span>);
1858
1859         /// Test if this constant is all-0.
1860         fn is_zero(expr: &hir::Expr<'_>) -> bool {
1861             use hir::ExprKind::*;
1862             use syntax::ast::LitKind::*;
1863             match &expr.kind {
1864                 Lit(lit) => {
1865                     if let Int(i, _) = lit.node {
1866                         i == 0
1867                     } else {
1868                         false
1869                     }
1870                 }
1871                 Tup(tup) => tup.iter().all(is_zero),
1872                 _ => false,
1873             }
1874         }
1875
1876         /// Determine if this expression is a "dangerous initialization".
1877         fn is_dangerous_init(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) -> Option<InitKind> {
1878             // `transmute` is inside an anonymous module (the `extern` block?);
1879             // `Invalid` represents the empty string and matches that.
1880             // FIXME(#66075): use diagnostic items.  Somehow, that does not seem to work
1881             // on intrinsics right now.
1882             const TRANSMUTE_PATH: &[Symbol] =
1883                 &[sym::core, sym::intrinsics, kw::Invalid, sym::transmute];
1884
1885             if let hir::ExprKind::Call(ref path_expr, ref args) = expr.kind {
1886                 // Find calls to `mem::{uninitialized,zeroed}` methods.
1887                 if let hir::ExprKind::Path(ref qpath) = path_expr.kind {
1888                     let def_id = cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
1889
1890                     if cx.tcx.is_diagnostic_item(sym::mem_zeroed, def_id) {
1891                         return Some(InitKind::Zeroed);
1892                     } else if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, def_id) {
1893                         return Some(InitKind::Uninit);
1894                     } else if cx.match_def_path(def_id, TRANSMUTE_PATH) {
1895                         if is_zero(&args[0]) {
1896                             return Some(InitKind::Zeroed);
1897                         }
1898                     }
1899                 }
1900             } else if let hir::ExprKind::MethodCall(_, _, ref args) = expr.kind {
1901                 // Find problematic calls to `MaybeUninit::assume_init`.
1902                 let def_id = cx.tables.type_dependent_def_id(expr.hir_id)?;
1903                 if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) {
1904                     // This is a call to *some* method named `assume_init`.
1905                     // See if the `self` parameter is one of the dangerous constructors.
1906                     if let hir::ExprKind::Call(ref path_expr, _) = args[0].kind {
1907                         if let hir::ExprKind::Path(ref qpath) = path_expr.kind {
1908                             let def_id =
1909                                 cx.tables.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
1910
1911                             if cx.tcx.is_diagnostic_item(sym::maybe_uninit_zeroed, def_id) {
1912                                 return Some(InitKind::Zeroed);
1913                             } else if cx.tcx.is_diagnostic_item(sym::maybe_uninit_uninit, def_id) {
1914                                 return Some(InitKind::Uninit);
1915                             }
1916                         }
1917                     }
1918                 }
1919             }
1920
1921             None
1922         }
1923
1924         /// Return `Some` only if we are sure this type does *not*
1925         /// allow zero initialization.
1926         fn ty_find_init_error<'tcx>(
1927             tcx: TyCtxt<'tcx>,
1928             ty: Ty<'tcx>,
1929             init: InitKind,
1930         ) -> Option<InitError> {
1931             use rustc::ty::TyKind::*;
1932             match ty.kind {
1933                 // Primitive types that don't like 0 as a value.
1934                 Ref(..) => Some((format!("References must be non-null"), None)),
1935                 Adt(..) if ty.is_box() => Some((format!("`Box` must be non-null"), None)),
1936                 FnPtr(..) => Some((format!("Function pointers must be non-null"), None)),
1937                 Never => Some((format!("The never type (`!`) has no valid value"), None)),
1938                 RawPtr(tm) if matches!(tm.ty.kind, Dynamic(..)) =>
1939                 // raw ptr to dyn Trait
1940                 {
1941                     Some((format!("The vtable of a wide raw pointer must be non-null"), None))
1942                 }
1943                 // Primitive types with other constraints.
1944                 Bool if init == InitKind::Uninit => {
1945                     Some((format!("Booleans must be `true` or `false`"), None))
1946                 }
1947                 Char if init == InitKind::Uninit => {
1948                     Some((format!("Characters must be a valid unicode codepoint"), None))
1949                 }
1950                 // Recurse and checks for some compound types.
1951                 Adt(adt_def, substs) if !adt_def.is_union() => {
1952                     // First check f this ADT has a layout attribute (like `NonNull` and friends).
1953                     use std::ops::Bound;
1954                     match tcx.layout_scalar_valid_range(adt_def.did) {
1955                         // We exploit here that `layout_scalar_valid_range` will never
1956                         // return `Bound::Excluded`.  (And we have tests checking that we
1957                         // handle the attribute correctly.)
1958                         (Bound::Included(lo), _) if lo > 0 => {
1959                             return Some((format!("{} must be non-null", ty), None));
1960                         }
1961                         (Bound::Included(_), _) | (_, Bound::Included(_))
1962                             if init == InitKind::Uninit =>
1963                         {
1964                             return Some((
1965                                 format!("{} must be initialized inside its custom valid range", ty),
1966                                 None,
1967                             ));
1968                         }
1969                         _ => {}
1970                     }
1971                     // Now, recurse.
1972                     match adt_def.variants.len() {
1973                         0 => Some((format!("0-variant enums have no valid value"), None)),
1974                         1 => {
1975                             // Struct, or enum with exactly one variant.
1976                             // Proceed recursively, check all fields.
1977                             let variant = &adt_def.variants[VariantIdx::from_u32(0)];
1978                             variant.fields.iter().find_map(|field| {
1979                                 ty_find_init_error(tcx, field.ty(tcx, substs), init).map(
1980                                     |(mut msg, span)| {
1981                                         if span.is_none() {
1982                                             // Point to this field, should be helpful for figuring
1983                                             // out where the source of the error is.
1984                                             let span = tcx.def_span(field.did);
1985                                             write!(
1986                                                 &mut msg,
1987                                                 " (in this {} field)",
1988                                                 adt_def.descr()
1989                                             )
1990                                             .unwrap();
1991                                             (msg, Some(span))
1992                                         } else {
1993                                             // Just forward.
1994                                             (msg, span)
1995                                         }
1996                                     },
1997                                 )
1998                             })
1999                         }
2000                         // Multi-variant enums are tricky: if all but one variant are
2001                         // uninhabited, we might actually do layout like for a single-variant
2002                         // enum, and then even leaving them uninitialized could be okay.
2003                         _ => None, // Conservative fallback for multi-variant enum.
2004                     }
2005                 }
2006                 Tuple(..) => {
2007                     // Proceed recursively, check all fields.
2008                     ty.tuple_fields().find_map(|field| ty_find_init_error(tcx, field, init))
2009                 }
2010                 // Conservative fallback.
2011                 _ => None,
2012             }
2013         }
2014
2015         if let Some(init) = is_dangerous_init(cx, expr) {
2016             // This conjures an instance of a type out of nothing,
2017             // using zeroed or uninitialized memory.
2018             // We are extremely conservative with what we warn about.
2019             let conjured_ty = cx.tables.expr_ty(expr);
2020             if let Some((msg, span)) = ty_find_init_error(cx.tcx, conjured_ty, init) {
2021                 let mut err = cx.struct_span_lint(
2022                     INVALID_VALUE,
2023                     expr.span,
2024                     &format!(
2025                         "the type `{}` does not permit {}",
2026                         conjured_ty,
2027                         match init {
2028                             InitKind::Zeroed => "zero-initialization",
2029                             InitKind::Uninit => "being left uninitialized",
2030                         },
2031                     ),
2032                 );
2033                 err.span_label(expr.span, "this code causes undefined behavior when executed");
2034                 err.span_label(
2035                     expr.span,
2036                     "help: use `MaybeUninit<T>` instead, \
2037                     and only call `assume_init` after initialization is done",
2038                 );
2039                 if let Some(span) = span {
2040                     err.span_note(span, &msg);
2041                 } else {
2042                     err.note(&msg);
2043                 }
2044                 err.emit();
2045             }
2046         }
2047     }
2048 }