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