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