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