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