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