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