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