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