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