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