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