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