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