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