]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
Rollup merge of #34175 - rwz:patch-2, r=alexcrichton
[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 middle::stability;
34 use rustc::cfg;
35 use rustc::ty::subst::Substs;
36 use rustc::ty::{self, Ty, TyCtxt};
37 use rustc::ty::adjustment;
38 use rustc::traits::{self, ProjectionMode};
39 use rustc::hir::map as hir_map;
40 use util::nodemap::{NodeSet};
41 use lint::{Level, LateContext, LintContext, LintArray, Lint};
42 use lint::{LintPass, LateLintPass};
43
44 use std::collections::HashSet;
45
46 use syntax::{ast};
47 use syntax::attr::{self, AttrMetaMethods};
48 use syntax::codemap::{self, Span};
49
50 use rustc::hir::{self, PatKind};
51 use rustc::hir::intravisit::FnKind;
52
53 use bad_style::{MethodLateContext, method_context};
54
55 // hardwired lints from librustc
56 pub use lint::builtin::*;
57
58 declare_lint! {
59     WHILE_TRUE,
60     Warn,
61     "suggest using `loop { }` instead of `while true { }`"
62 }
63
64 #[derive(Copy, Clone)]
65 pub struct WhileTrue;
66
67 impl LintPass for WhileTrue {
68     fn get_lints(&self) -> LintArray {
69         lint_array!(WHILE_TRUE)
70     }
71 }
72
73 impl LateLintPass for WhileTrue {
74     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
75         if let hir::ExprWhile(ref cond, _, _) = e.node {
76             if let hir::ExprLit(ref lit) = cond.node {
77                 if let ast::LitKind::Bool(true) = lit.node {
78                     cx.span_lint(WHILE_TRUE, e.span,
79                                  "denote infinite loops with loop { ... }");
80                 }
81             }
82         }
83     }
84 }
85
86 declare_lint! {
87     BOX_POINTERS,
88     Allow,
89     "use of owned (Box type) heap memory"
90 }
91
92 #[derive(Copy, Clone)]
93 pub struct BoxPointers;
94
95 impl BoxPointers {
96     fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext<'a, 'tcx>,
97                                  span: Span, ty: Ty<'tcx>) {
98         for leaf_ty in ty.walk() {
99             if let ty::TyBox(_) = leaf_ty.sty {
100                 let m = format!("type uses owned (Box type) pointers: {}", ty);
101                 cx.span_lint(BOX_POINTERS, span, &m);
102             }
103         }
104     }
105 }
106
107 impl LintPass for BoxPointers {
108     fn get_lints(&self) -> LintArray {
109         lint_array!(BOX_POINTERS)
110     }
111 }
112
113 impl LateLintPass for BoxPointers {
114     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
115         match it.node {
116             hir::ItemFn(..) |
117             hir::ItemTy(..) |
118             hir::ItemEnum(..) |
119             hir::ItemStruct(..) =>
120                 self.check_heap_type(cx, it.span,
121                                      cx.tcx.node_id_to_type(it.id)),
122             _ => ()
123         }
124
125         // If it's a struct, we also have to check the fields' types
126         match it.node {
127             hir::ItemStruct(ref struct_def, _) => {
128                 for struct_field in struct_def.fields() {
129                     self.check_heap_type(cx, struct_field.span,
130                                          cx.tcx.node_id_to_type(struct_field.id));
131                 }
132             }
133             _ => ()
134         }
135     }
136
137     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
138         let ty = cx.tcx.node_id_to_type(e.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 }`"
147 }
148
149 #[derive(Copy, Clone)]
150 pub struct NonShorthandFieldPatterns;
151
152 impl LintPass for NonShorthandFieldPatterns {
153     fn get_lints(&self) -> LintArray {
154         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
155     }
156 }
157
158 impl LateLintPass for NonShorthandFieldPatterns {
159     fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
160         if let PatKind::Struct(_, ref field_pats, _) = pat.node {
161             for fieldpat in field_pats {
162                 if fieldpat.node.is_shorthand {
163                     continue;
164                 }
165                 if let PatKind::Binding(_, ident, None) = fieldpat.node.pat.node {
166                     if ident.node.unhygienize() == fieldpat.node.name {
167                         cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
168                                      &format!("the `{}:` in this pattern is redundant and can \
169                                               be removed", ident.node))
170                     }
171                 }
172             }
173         }
174     }
175 }
176
177 declare_lint! {
178     UNSAFE_CODE,
179     Allow,
180     "usage of `unsafe` code"
181 }
182
183 #[derive(Copy, Clone)]
184 pub struct UnsafeCode;
185
186 impl LintPass for UnsafeCode {
187     fn get_lints(&self) -> LintArray {
188         lint_array!(UNSAFE_CODE)
189     }
190 }
191
192 impl LateLintPass for UnsafeCode {
193     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
194         if let hir::ExprBlock(ref blk) = e.node {
195             // Don't warn about generated blocks, that'll just pollute the output.
196             if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
197                 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
198             }
199         }
200     }
201
202     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
203         match it.node {
204             hir::ItemTrait(hir::Unsafety::Unsafe, _, _, _) =>
205                 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
206
207             hir::ItemImpl(hir::Unsafety::Unsafe, _, _, _, _, _) =>
208                 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
209
210             _ => return,
211         }
212     }
213
214     fn check_fn(&mut self, cx: &LateContext, fk: FnKind, _: &hir::FnDecl,
215                 _: &hir::Block, span: Span, _: ast::NodeId) {
216         match fk {
217             FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, _, _, _, _) =>
218                 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
219
220             FnKind::Method(_, sig, _, _) => {
221                 if sig.unsafety == hir::Unsafety::Unsafe {
222                     cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
223                 }
224             },
225
226             _ => (),
227         }
228     }
229
230     fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
231         if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
232             if sig.unsafety == hir::Unsafety::Unsafe {
233                 cx.span_lint(UNSAFE_CODE, trait_item.span,
234                              "declaration of an `unsafe` method")
235             }
236         }
237     }
238 }
239
240 declare_lint! {
241     MISSING_DOCS,
242     Allow,
243     "detects missing documentation for public members"
244 }
245
246 pub struct MissingDoc {
247     /// Stack of IDs of struct definitions.
248     struct_def_stack: Vec<ast::NodeId>,
249
250     /// True if inside variant definition
251     in_variant: bool,
252
253     /// Stack of whether #[doc(hidden)] is set
254     /// at each level which has lint attributes.
255     doc_hidden_stack: Vec<bool>,
256
257     /// Private traits or trait items that leaked through. Don't check their methods.
258     private_traits: HashSet<ast::NodeId>,
259 }
260
261 impl MissingDoc {
262     pub fn new() -> MissingDoc {
263         MissingDoc {
264             struct_def_stack: vec!(),
265             in_variant: false,
266             doc_hidden_stack: vec!(false),
267             private_traits: HashSet::new(),
268         }
269     }
270
271     fn doc_hidden(&self) -> bool {
272         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
273     }
274
275     fn check_missing_docs_attrs(&self,
276                                cx: &LateContext,
277                                id: Option<ast::NodeId>,
278                                attrs: &[ast::Attribute],
279                                sp: Span,
280                                desc: &'static str) {
281         // If we're building a test harness, then warning about
282         // documentation is probably not really relevant right now.
283         if cx.sess().opts.test {
284             return;
285         }
286
287         // `#[doc(hidden)]` disables missing_docs check.
288         if self.doc_hidden() {
289             return;
290         }
291
292         // Only check publicly-visible items, using the result from the privacy pass.
293         // It's an option so the crate root can also use this function (it doesn't
294         // have a NodeId).
295         if let Some(id) = id {
296             if !cx.access_levels.is_exported(id) {
297                 return;
298             }
299         }
300
301         let has_doc = attrs.iter().any(|a| {
302             match a.node.value.node {
303                 ast::MetaItemKind::NameValue(ref name, _) if *name == "doc" => true,
304                 _ => false
305             }
306         });
307         if !has_doc {
308             cx.span_lint(MISSING_DOCS, sp,
309                          &format!("missing documentation for {}", desc));
310         }
311     }
312 }
313
314 impl LintPass for MissingDoc {
315     fn get_lints(&self) -> LintArray {
316         lint_array!(MISSING_DOCS)
317     }
318 }
319
320 impl LateLintPass for MissingDoc {
321     fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
322         let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
323             attr.check_name("doc") && match attr.meta_item_list() {
324                 None => false,
325                 Some(l) => attr::contains_name(&l[..], "hidden"),
326             }
327         });
328         self.doc_hidden_stack.push(doc_hidden);
329     }
330
331     fn exit_lint_attrs(&mut self, _: &LateContext, _: &[ast::Attribute]) {
332         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
333     }
334
335     fn check_struct_def(&mut self, _: &LateContext, _: &hir::VariantData,
336                         _: ast::Name, _: &hir::Generics, item_id: ast::NodeId) {
337         self.struct_def_stack.push(item_id);
338     }
339
340     fn check_struct_def_post(&mut self, _: &LateContext, _: &hir::VariantData,
341                              _: ast::Name, _: &hir::Generics, item_id: ast::NodeId) {
342         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
343         assert!(popped == item_id);
344     }
345
346     fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
347         self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
348     }
349
350     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
351         let desc = match it.node {
352             hir::ItemFn(..) => "a function",
353             hir::ItemMod(..) => "a module",
354             hir::ItemEnum(..) => "an enum",
355             hir::ItemStruct(..) => "a struct",
356             hir::ItemTrait(_, _, _, ref items) => {
357                 // Issue #11592, traits are always considered exported, even when private.
358                 if it.vis == hir::Visibility::Inherited {
359                     self.private_traits.insert(it.id);
360                     for itm in items {
361                         self.private_traits.insert(itm.id);
362                     }
363                     return
364                 }
365                 "a trait"
366             },
367             hir::ItemTy(..) => "a type alias",
368             hir::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
369                 // If the trait is private, add the impl items to private_traits so they don't get
370                 // reported for missing docs.
371                 let real_trait = cx.tcx.expect_def(trait_ref.ref_id).def_id();
372                 if let Some(node_id) = cx.tcx.map.as_local_node_id(real_trait) {
373                     match cx.tcx.map.find(node_id) {
374                         Some(hir_map::NodeItem(item)) => if item.vis == hir::Visibility::Inherited {
375                             for itm in impl_items {
376                                 self.private_traits.insert(itm.id);
377                             }
378                         },
379                         _ => { }
380                     }
381                 }
382                 return
383             },
384             hir::ItemConst(..) => "a constant",
385             hir::ItemStatic(..) => "a static",
386             _ => return
387         };
388
389         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
390     }
391
392     fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
393         if self.private_traits.contains(&trait_item.id) { return }
394
395         let desc = match trait_item.node {
396             hir::ConstTraitItem(..) => "an associated constant",
397             hir::MethodTraitItem(..) => "a trait method",
398             hir::TypeTraitItem(..) => "an associated type",
399         };
400
401         self.check_missing_docs_attrs(cx, Some(trait_item.id),
402                                       &trait_item.attrs,
403                                       trait_item.span, desc);
404     }
405
406     fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
407         // If the method is an impl for a trait, don't doc.
408         if method_context(cx, impl_item.id, impl_item.span) == MethodLateContext::TraitImpl {
409             return;
410         }
411
412         let desc = match impl_item.node {
413             hir::ImplItemKind::Const(..) => "an associated constant",
414             hir::ImplItemKind::Method(..) => "a method",
415             hir::ImplItemKind::Type(_) => "an associated type",
416         };
417         self.check_missing_docs_attrs(cx, Some(impl_item.id),
418                                       &impl_item.attrs,
419                                       impl_item.span, desc);
420     }
421
422     fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
423         if !sf.is_positional() {
424             if sf.vis == hir::Public || self.in_variant {
425                 let cur_struct_def = *self.struct_def_stack.last()
426                     .expect("empty struct_def_stack");
427                 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
428                                               &sf.attrs, sf.span,
429                                               "a struct field")
430             }
431         }
432     }
433
434     fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
435         self.check_missing_docs_attrs(cx, Some(v.node.data.id()),
436                                       &v.node.attrs, v.span, "a variant");
437         assert!(!self.in_variant);
438         self.in_variant = true;
439     }
440
441     fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) {
442         assert!(self.in_variant);
443         self.in_variant = false;
444     }
445 }
446
447 declare_lint! {
448     pub MISSING_COPY_IMPLEMENTATIONS,
449     Allow,
450     "detects potentially-forgotten implementations of `Copy`"
451 }
452
453 #[derive(Copy, Clone)]
454 pub struct MissingCopyImplementations;
455
456 impl LintPass for MissingCopyImplementations {
457     fn get_lints(&self) -> LintArray {
458         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
459     }
460 }
461
462 impl LateLintPass for MissingCopyImplementations {
463     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
464         if !cx.access_levels.is_reachable(item.id) {
465             return;
466         }
467         let (def, ty) = match item.node {
468             hir::ItemStruct(_, ref ast_generics) => {
469                 if ast_generics.is_parameterized() {
470                     return;
471                 }
472                 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
473                 (def, cx.tcx.mk_struct(def,
474                                        cx.tcx.mk_substs(Substs::empty())))
475             }
476             hir::ItemEnum(_, ref ast_generics) => {
477                 if ast_generics.is_parameterized() {
478                     return;
479                 }
480                 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
481                 (def, cx.tcx.mk_enum(def,
482                                      cx.tcx.mk_substs(Substs::empty())))
483             }
484             _ => return,
485         };
486         if def.has_dtor() { return; }
487         let parameter_environment = cx.tcx.empty_parameter_environment();
488         // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
489         // method
490         if !ty.moves_by_default(cx.tcx, &parameter_environment, item.span) {
491             return;
492         }
493         if parameter_environment.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
494             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
495                          item.span,
496                          "type could implement `Copy`; consider adding `impl \
497                           Copy`")
498         }
499     }
500 }
501
502 declare_lint! {
503     MISSING_DEBUG_IMPLEMENTATIONS,
504     Allow,
505     "detects missing implementations of fmt::Debug"
506 }
507
508 pub struct MissingDebugImplementations {
509     impling_types: Option<NodeSet>,
510 }
511
512 impl MissingDebugImplementations {
513     pub fn new() -> MissingDebugImplementations {
514         MissingDebugImplementations {
515             impling_types: None,
516         }
517     }
518 }
519
520 impl LintPass for MissingDebugImplementations {
521     fn get_lints(&self) -> LintArray {
522         lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
523     }
524 }
525
526 impl LateLintPass for MissingDebugImplementations {
527     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
528         if !cx.access_levels.is_reachable(item.id) {
529             return;
530         }
531
532         match item.node {
533             hir::ItemStruct(..) | hir::ItemEnum(..) => {},
534             _ => return,
535         }
536
537         let debug = match cx.tcx.lang_items.debug_trait() {
538             Some(debug) => debug,
539             None => return,
540         };
541
542         if self.impling_types.is_none() {
543             let debug_def = cx.tcx.lookup_trait_def(debug);
544             let mut impls = NodeSet();
545             debug_def.for_each_impl(cx.tcx, |d| {
546                 if let Some(n) = cx.tcx.map.as_local_node_id(d) {
547                     if let Some(ty_def) = cx.tcx.node_id_to_type(n).ty_to_def_id() {
548                         if let Some(node_id) = cx.tcx.map.as_local_node_id(ty_def) {
549                             impls.insert(node_id);
550                         }
551                     }
552                 }
553             });
554
555             self.impling_types = Some(impls);
556             debug!("{:?}", self.impling_types);
557         }
558
559         if !self.impling_types.as_ref().unwrap().contains(&item.id) {
560             cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
561                          item.span,
562                          "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
563                           or a manual implementation")
564         }
565     }
566 }
567
568 declare_lint! {
569     DEPRECATED,
570     Warn,
571     "detects use of deprecated items"
572 }
573
574 /// Checks for use of items with `#[deprecated]` or `#[rustc_deprecated]` attributes
575 #[derive(Copy, Clone)]
576 pub struct Deprecated;
577
578 impl Deprecated {
579     fn lint(&self, cx: &LateContext, _id: DefId, span: Span,
580             stability: &Option<&attr::Stability>, deprecation: &Option<attr::Deprecation>) {
581         // Deprecated attributes apply in-crate and cross-crate.
582         if let Some(&attr::Stability{rustc_depr: Some(attr::RustcDeprecation{ref reason, ..}), ..})
583                 = *stability {
584             output(cx, DEPRECATED, span, Some(&reason))
585         } else if let Some(attr::Deprecation{ref note, ..}) = *deprecation {
586             output(cx, DEPRECATED, span, note.as_ref().map(|x| &**x))
587         }
588
589         fn output(cx: &LateContext, lint: &'static Lint, span: Span, note: Option<&str>) {
590             let msg = if let Some(note) = note {
591                 format!("use of deprecated item: {}", note)
592             } else {
593                 format!("use of deprecated item")
594             };
595
596             cx.span_lint(lint, span, &msg);
597         }
598     }
599 }
600
601 impl LintPass for Deprecated {
602     fn get_lints(&self) -> LintArray {
603         lint_array!(DEPRECATED)
604     }
605 }
606
607 impl LateLintPass for Deprecated {
608     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
609         stability::check_item(cx.tcx, item, false,
610                               &mut |id, sp, stab, depr|
611                                 self.lint(cx, id, sp, &stab, &depr));
612     }
613
614     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
615         stability::check_expr(cx.tcx, e,
616                               &mut |id, sp, stab, depr|
617                                 self.lint(cx, id, sp, &stab, &depr));
618     }
619
620     fn check_path(&mut self, cx: &LateContext, path: &hir::Path, id: ast::NodeId) {
621         stability::check_path(cx.tcx, path, id,
622                               &mut |id, sp, stab, depr|
623                                 self.lint(cx, id, sp, &stab, &depr));
624     }
625
626     fn check_path_list_item(&mut self, cx: &LateContext, item: &hir::PathListItem) {
627         stability::check_path_list_item(cx.tcx, item,
628                                          &mut |id, sp, stab, depr|
629                                            self.lint(cx, id, sp, &stab, &depr));
630     }
631
632     fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
633         stability::check_pat(cx.tcx, pat,
634                              &mut |id, sp, stab, depr|
635                                 self.lint(cx, id, sp, &stab, &depr));
636     }
637 }
638
639 declare_lint! {
640     pub UNCONDITIONAL_RECURSION,
641     Warn,
642     "functions that cannot return without calling themselves"
643 }
644
645 #[derive(Copy, Clone)]
646 pub struct UnconditionalRecursion;
647
648
649 impl LintPass for UnconditionalRecursion {
650     fn get_lints(&self) -> LintArray {
651         lint_array![UNCONDITIONAL_RECURSION]
652     }
653 }
654
655 impl LateLintPass for UnconditionalRecursion {
656     fn check_fn(&mut self, cx: &LateContext, fn_kind: FnKind, _: &hir::FnDecl,
657                 blk: &hir::Block, sp: Span, id: ast::NodeId) {
658         let method = match fn_kind {
659             FnKind::ItemFn(..) => None,
660             FnKind::Method(..) => {
661                 cx.tcx.impl_or_trait_item(cx.tcx.map.local_def_id(id)).as_opt_method()
662             }
663             // closures can't recur, so they don't matter.
664             FnKind::Closure(_) => return
665         };
666
667         // Walk through this function (say `f`) looking to see if
668         // every possible path references itself, i.e. the function is
669         // called recursively unconditionally. This is done by trying
670         // to find a path from the entry node to the exit node that
671         // *doesn't* call `f` by traversing from the entry while
672         // pretending that calls of `f` are sinks (i.e. ignoring any
673         // exit edges from them).
674         //
675         // NB. this has an edge case with non-returning statements,
676         // like `loop {}` or `panic!()`: control flow never reaches
677         // the exit node through these, so one can have a function
678         // that never actually calls itselfs but is still picked up by
679         // this lint:
680         //
681         //     fn f(cond: bool) {
682         //         if !cond { panic!() } // could come from `assert!(cond)`
683         //         f(false)
684         //     }
685         //
686         // In general, functions of that form may be able to call
687         // itself a finite number of times and then diverge. The lint
688         // considers this to be an error for two reasons, (a) it is
689         // easier to implement, and (b) it seems rare to actually want
690         // to have behaviour like the above, rather than
691         // e.g. accidentally recurring after an assert.
692
693         let cfg = cfg::CFG::new(cx.tcx, blk);
694
695         let mut work_queue = vec![cfg.entry];
696         let mut reached_exit_without_self_call = false;
697         let mut self_call_spans = vec![];
698         let mut visited = HashSet::new();
699
700         while let Some(idx) = work_queue.pop() {
701             if idx == cfg.exit {
702                 // found a path!
703                 reached_exit_without_self_call = true;
704                 break;
705             }
706
707             let cfg_id = idx.node_id();
708             if visited.contains(&cfg_id) {
709                 // already done
710                 continue;
711             }
712             visited.insert(cfg_id);
713
714             let node_id = cfg.graph.node_data(idx).id();
715
716             // is this a recursive call?
717             let self_recursive = if node_id != ast::DUMMY_NODE_ID {
718                 match method {
719                     Some(ref method) => {
720                         expr_refers_to_this_method(cx.tcx, method, node_id)
721                     }
722                     None => expr_refers_to_this_fn(cx.tcx, id, node_id)
723                 }
724             } else {
725                 false
726             };
727             if self_recursive {
728                 self_call_spans.push(cx.tcx.map.span(node_id));
729                 // this is a self call, so we shouldn't explore past
730                 // this node in the CFG.
731                 continue;
732             }
733             // add the successors of this node to explore the graph further.
734             for (_, edge) in cfg.graph.outgoing_edges(idx) {
735                 let target_idx = edge.target();
736                 let target_cfg_id = target_idx.node_id();
737                 if !visited.contains(&target_cfg_id) {
738                     work_queue.push(target_idx)
739                 }
740             }
741         }
742
743         // Check the number of self calls because a function that
744         // doesn't return (e.g. calls a `-> !` function or `loop { /*
745         // no break */ }`) shouldn't be linted unless it actually
746         // recurs.
747         if !reached_exit_without_self_call && !self_call_spans.is_empty() {
748             let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION, sp,
749                                              "function cannot return without recurring");
750
751             // FIXME #19668: these could be span_lint_note's instead of this manual guard.
752             if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
753                 // offer some help to the programmer.
754                 for call in &self_call_spans {
755                     db.span_note(*call, "recursive call site");
756                 }
757                 db.help("a `loop` may express intention \
758                          better if this is on purpose");
759             }
760             db.emit();
761         }
762
763         // all done
764         return;
765
766         // Functions for identifying if the given Expr NodeId `id`
767         // represents a call to the function `fn_id`/method `method`.
768
769         fn expr_refers_to_this_fn(tcx: TyCtxt,
770                                   fn_id: ast::NodeId,
771                                   id: ast::NodeId) -> bool {
772             match tcx.map.get(id) {
773                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
774                     tcx.expect_def_or_none(callee.id).map_or(false, |def| {
775                         def.def_id() == tcx.map.local_def_id(fn_id)
776                     })
777                 }
778                 _ => false
779             }
780         }
781
782         // Check if the expression `id` performs a call to `method`.
783         fn expr_refers_to_this_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
784                                                 method: &ty::Method,
785                                                 id: ast::NodeId) -> bool {
786             // Check for method calls and overloaded operators.
787             let opt_m = tcx.tables.borrow().method_map.get(&ty::MethodCall::expr(id)).cloned();
788             if let Some(m) = opt_m {
789                 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
790                     return true;
791                 }
792             }
793
794             // Check for overloaded autoderef method calls.
795             let opt_adj = tcx.tables.borrow().adjustments.get(&id).cloned();
796             if let Some(adjustment::AdjustDerefRef(adj)) = opt_adj {
797                 for i in 0..adj.autoderefs {
798                     let method_call = ty::MethodCall::autoderef(id, i as u32);
799                     if let Some(m) = tcx.tables.borrow().method_map
800                                                         .get(&method_call)
801                                                         .cloned() {
802                         if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
803                             return true;
804                         }
805                     }
806                 }
807             }
808
809             // Check for calls to methods via explicit paths (e.g. `T::method()`).
810             match tcx.map.get(id) {
811                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
812                     // The callee is an arbitrary expression,
813                     // it doesn't necessarily have a definition.
814                     match tcx.expect_def_or_none(callee.id) {
815                         Some(Def::Method(def_id)) => {
816                             let item_substs = tcx.node_id_item_substs(callee.id);
817                             method_call_refers_to_method(
818                                 tcx, method, def_id, &item_substs.substs, id)
819                         }
820                         _ => false
821                     }
822                 }
823                 _ => false
824             }
825         }
826
827         // Check if the method call to the method with the ID `callee_id`
828         // and instantiated with `callee_substs` refers to method `method`.
829         fn method_call_refers_to_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
830                                                   method: &ty::Method,
831                                                   callee_id: DefId,
832                                                   callee_substs: &Substs<'tcx>,
833                                                   expr_id: ast::NodeId) -> bool {
834             let callee_item = tcx.impl_or_trait_item(callee_id);
835
836             match callee_item.container() {
837                 // This is an inherent method, so the `def_id` refers
838                 // directly to the method definition.
839                 ty::ImplContainer(_) => {
840                     callee_id == method.def_id
841                 }
842
843                 // A trait method, from any number of possible sources.
844                 // Attempt to select a concrete impl before checking.
845                 ty::TraitContainer(trait_def_id) => {
846                     let trait_ref = callee_substs.to_trait_ref(tcx, trait_def_id);
847                     let trait_ref = ty::Binder(trait_ref);
848                     let span = tcx.map.span(expr_id);
849                     let obligation =
850                         traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
851                                                 trait_ref.to_poly_trait_predicate());
852
853                     // unwrap() is ok here b/c `method` is the method
854                     // defined in this crate whose body we are
855                     // checking, so it's always local
856                     let node_id = tcx.map.as_local_node_id(method.def_id).unwrap();
857
858                     let param_env = Some(ty::ParameterEnvironment::for_item(tcx, node_id));
859                     tcx.infer_ctxt(None, param_env, ProjectionMode::AnyFinal).enter(|infcx| {
860                         let mut selcx = traits::SelectionContext::new(&infcx);
861                         match selcx.select(&obligation) {
862                             // The method comes from a `T: Trait` bound.
863                             // If `T` is `Self`, then this call is inside
864                             // a default method definition.
865                             Ok(Some(traits::VtableParam(_))) => {
866                                 let self_ty = callee_substs.self_ty();
867                                 let on_self = self_ty.map_or(false, |t| t.is_self());
868                                 // We can only be recurring in a default
869                                 // method if we're being called literally
870                                 // on the `Self` type.
871                                 on_self && callee_id == method.def_id
872                             }
873
874                             // The `impl` is known, so we check that with a
875                             // special case:
876                             Ok(Some(traits::VtableImpl(vtable_impl))) => {
877                                 let container = ty::ImplContainer(vtable_impl.impl_def_id);
878                                 // It matches if it comes from the same impl,
879                                 // and has the same method name.
880                                 container == method.container
881                                     && callee_item.name() == method.name
882                             }
883
884                             // There's no way to know if this call is
885                             // recursive, so we assume it's not.
886                             _ => false
887                         }
888                     })
889                 }
890             }
891         }
892     }
893 }
894
895 declare_lint! {
896     PLUGIN_AS_LIBRARY,
897     Warn,
898     "compiler plugin used as ordinary library in non-plugin crate"
899 }
900
901 #[derive(Copy, Clone)]
902 pub struct PluginAsLibrary;
903
904 impl LintPass for PluginAsLibrary {
905     fn get_lints(&self) -> LintArray {
906         lint_array![PLUGIN_AS_LIBRARY]
907     }
908 }
909
910 impl LateLintPass for PluginAsLibrary {
911     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
912         if cx.sess().plugin_registrar_fn.get().is_some() {
913             // We're compiling a plugin; it's fine to link other plugins.
914             return;
915         }
916
917         match it.node {
918             hir::ItemExternCrate(..) => (),
919             _ => return,
920         };
921
922         let prfn = match cx.sess().cstore.extern_mod_stmt_cnum(it.id) {
923             Some(cnum) => cx.sess().cstore.plugin_registrar_fn(cnum),
924             None => {
925                 // Probably means we aren't linking the crate for some reason.
926                 //
927                 // Not sure if / when this could happen.
928                 return;
929             }
930         };
931
932         if prfn.is_some() {
933             cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
934                          "compiler plugin used as an ordinary library");
935         }
936     }
937 }
938
939 declare_lint! {
940     PRIVATE_NO_MANGLE_FNS,
941     Warn,
942     "functions marked #[no_mangle] should be exported"
943 }
944
945 declare_lint! {
946     PRIVATE_NO_MANGLE_STATICS,
947     Warn,
948     "statics marked #[no_mangle] should be exported"
949 }
950
951 declare_lint! {
952     NO_MANGLE_CONST_ITEMS,
953     Deny,
954     "const items will not have their symbols exported"
955 }
956
957 declare_lint! {
958     NO_MANGLE_GENERIC_ITEMS,
959     Warn,
960     "generic items must be mangled"
961 }
962
963 #[derive(Copy, Clone)]
964 pub struct InvalidNoMangleItems;
965
966 impl LintPass for InvalidNoMangleItems {
967     fn get_lints(&self) -> LintArray {
968         lint_array!(PRIVATE_NO_MANGLE_FNS,
969                     PRIVATE_NO_MANGLE_STATICS,
970                     NO_MANGLE_CONST_ITEMS,
971                     NO_MANGLE_GENERIC_ITEMS)
972     }
973 }
974
975 impl LateLintPass for InvalidNoMangleItems {
976     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
977         match it.node {
978             hir::ItemFn(_, _, _, _, ref generics, _) => {
979                 if attr::contains_name(&it.attrs, "no_mangle") {
980                     if !cx.access_levels.is_reachable(it.id) {
981                         let msg = format!("function {} is marked #[no_mangle], but not exported",
982                                           it.name);
983                         cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
984                     }
985                     if generics.is_parameterized() {
986                         cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
987                                      it.span,
988                                      "generic functions must be mangled");
989                     }
990                 }
991             },
992             hir::ItemStatic(..) => {
993                 if attr::contains_name(&it.attrs, "no_mangle") &&
994                        !cx.access_levels.is_reachable(it.id) {
995                     let msg = format!("static {} is marked #[no_mangle], but not exported",
996                                       it.name);
997                     cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
998                 }
999             },
1000             hir::ItemConst(..) => {
1001                 if attr::contains_name(&it.attrs, "no_mangle") {
1002                     // Const items do not refer to a particular location in memory, and therefore
1003                     // don't have anything to attach a symbol to
1004                     let msg = "const items should never be #[no_mangle], consider instead using \
1005                                `pub static`";
1006                     cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1007                 }
1008             }
1009             _ => {},
1010         }
1011     }
1012 }
1013
1014 #[derive(Clone, Copy)]
1015 pub struct MutableTransmutes;
1016
1017 declare_lint! {
1018     MUTABLE_TRANSMUTES,
1019     Deny,
1020     "mutating transmuted &mut T from &T may cause undefined behavior"
1021 }
1022
1023 impl LintPass for MutableTransmutes {
1024     fn get_lints(&self) -> LintArray {
1025         lint_array!(MUTABLE_TRANSMUTES)
1026     }
1027 }
1028
1029 impl LateLintPass for MutableTransmutes {
1030     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1031         use syntax::abi::Abi::RustIntrinsic;
1032
1033         let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
1034                    consider instead using an UnsafeCell";
1035         match get_transmute_from_to(cx, expr) {
1036             Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1037                 if to_mt.mutbl == hir::Mutability::MutMutable
1038                     && from_mt.mutbl == hir::Mutability::MutImmutable {
1039                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1040                 }
1041             }
1042             _ => ()
1043         }
1044
1045         fn get_transmute_from_to<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr)
1046             -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1047             match expr.node {
1048                 hir::ExprPath(..) => (),
1049                 _ => return None
1050             }
1051             if let Def::Fn(did) = cx.tcx.expect_def(expr.id) {
1052                 if !def_id_is_transmute(cx, did) {
1053                     return None;
1054                 }
1055                 let typ = cx.tcx.node_id_to_type(expr.id);
1056                 match typ.sty {
1057                     ty::TyFnDef(_, _, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
1058                         if let ty::FnConverging(to) = bare_fn.sig.0.output {
1059                             let from = bare_fn.sig.0.inputs[0];
1060                             return Some((&from.sty, &to.sty));
1061                         }
1062                     },
1063                     _ => ()
1064                 }
1065             }
1066             None
1067         }
1068
1069         fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1070             match cx.tcx.lookup_item_type(def_id).ty.sty {
1071                 ty::TyFnDef(_, _, ref bfty) if bfty.abi == RustIntrinsic => (),
1072                 _ => return false
1073             }
1074             cx.tcx.item_name(def_id).as_str() == "transmute"
1075         }
1076     }
1077 }
1078
1079 /// Forbids using the `#[feature(...)]` attribute
1080 #[derive(Copy, Clone)]
1081 pub struct UnstableFeatures;
1082
1083 declare_lint! {
1084     UNSTABLE_FEATURES,
1085     Allow,
1086     "enabling unstable features (deprecated. do not use)"
1087 }
1088
1089 impl LintPass for UnstableFeatures {
1090     fn get_lints(&self) -> LintArray {
1091         lint_array!(UNSTABLE_FEATURES)
1092     }
1093 }
1094
1095 impl LateLintPass for UnstableFeatures {
1096     fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1097         if attr::contains_name(&[attr.node.value.clone()], "feature") {
1098             if let Some(items) = attr.node.value.meta_item_list() {
1099                 for item in items {
1100                     ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
1101                 }
1102             }
1103         }
1104     }
1105 }
1106
1107 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
1108 /// attribute (see issue #24585).
1109 #[derive(Copy, Clone)]
1110 pub struct DropWithReprExtern;
1111
1112 declare_lint! {
1113     DROP_WITH_REPR_EXTERN,
1114     Warn,
1115     "use of #[repr(C)] on a type that implements Drop"
1116 }
1117
1118 impl LintPass for DropWithReprExtern {
1119     fn get_lints(&self) -> LintArray {
1120         lint_array!(DROP_WITH_REPR_EXTERN)
1121     }
1122 }
1123
1124 impl LateLintPass for DropWithReprExtern {
1125     fn check_crate(&mut self, ctx: &LateContext, _: &hir::Crate) {
1126         let drop_trait = match ctx.tcx.lang_items.drop_trait() {
1127             Some(id) => ctx.tcx.lookup_trait_def(id), None => { return }
1128         };
1129         drop_trait.for_each_impl(ctx.tcx, |drop_impl_did| {
1130             if !drop_impl_did.is_local() {
1131                 return;
1132             }
1133             let dtor_self_type = ctx.tcx.lookup_item_type(drop_impl_did).ty;
1134
1135             match dtor_self_type.sty {
1136                 ty::TyEnum(self_type_def, _) |
1137                 ty::TyStruct(self_type_def, _) => {
1138                     let self_type_did = self_type_def.did;
1139                     let hints = ctx.tcx.lookup_repr_hints(self_type_did);
1140                     if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
1141                         self_type_def.dtor_kind().has_drop_flag() {
1142                         let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
1143                                                                      codemap::DUMMY_SP);
1144                         let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
1145                                                                      codemap::DUMMY_SP);
1146                         ctx.span_lint_note(DROP_WITH_REPR_EXTERN,
1147                                            drop_impl_span,
1148                                            "implementing Drop adds hidden state to types, \
1149                                             possibly conflicting with `#[repr(C)]`",
1150                                             self_defn_span,
1151                                             "the `#[repr(C)]` attribute is attached here");
1152                     }
1153                 }
1154                 _ => {}
1155             }
1156         })
1157     }
1158 }