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