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