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