]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
move projection mode into parameter environment
[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, TyCtxt};
36 use rustc::traits::{self, Reveal};
37 use rustc::hir::map as hir_map;
38 use util::nodemap::NodeSet;
39 use lint::{Level, LateContext, LintContext, LintArray};
40 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
41
42 use std::collections::HashSet;
43
44 use syntax::ast;
45 use syntax::attr;
46 use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
47 use syntax_pos::Span;
48 use syntax::symbol::keywords;
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<'a, 'tcx> LateLintPass<'a, 'tcx> 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,
79                                  e.span,
80                                  "denote infinite loops with loop { ... }");
81                 }
82             }
83         }
84     }
85 }
86
87 declare_lint! {
88     BOX_POINTERS,
89     Allow,
90     "use of owned (Box type) heap memory"
91 }
92
93 #[derive(Copy, Clone)]
94 pub struct BoxPointers;
95
96 impl BoxPointers {
97     fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
98         for leaf_ty in ty.walk() {
99             if leaf_ty.is_box() {
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<'a, 'tcx> LateLintPass<'a, 'tcx> 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             hir::ItemUnion(..) => {
121                 let def_id = cx.tcx.hir.local_def_id(it.id);
122                 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
123             }
124             _ => ()
125         }
126
127         // If it's a struct, we also have to check the fields' types
128         match it.node {
129             hir::ItemStruct(ref struct_def, _) |
130             hir::ItemUnion(ref struct_def, _) => {
131                 for struct_field in struct_def.fields() {
132                     let def_id = cx.tcx.hir.local_def_id(struct_field.id);
133                     self.check_heap_type(cx, struct_field.span,
134                                          cx.tcx.type_of(def_id));
135                 }
136             }
137             _ => (),
138         }
139     }
140
141     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
142         let ty = cx.tables.node_id_to_type(e.id);
143         self.check_heap_type(cx, e.span, ty);
144     }
145 }
146
147 declare_lint! {
148     NON_SHORTHAND_FIELD_PATTERNS,
149     Warn,
150     "using `Struct { x: x }` instead of `Struct { x }`"
151 }
152
153 #[derive(Copy, Clone)]
154 pub struct NonShorthandFieldPatterns;
155
156 impl LintPass for NonShorthandFieldPatterns {
157     fn get_lints(&self) -> LintArray {
158         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
159     }
160 }
161
162 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
163     fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
164         if let PatKind::Struct(_, ref field_pats, _) = pat.node {
165             for fieldpat in field_pats {
166                 if fieldpat.node.is_shorthand {
167                     continue;
168                 }
169                 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
170                     if ident.node == fieldpat.node.name {
171                         cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS,
172                                      fieldpat.span,
173                                      &format!("the `{}:` in this pattern is redundant and can \
174                                               be removed",
175                                               ident.node))
176                     }
177                 }
178             }
179         }
180     }
181 }
182
183 declare_lint! {
184     UNSAFE_CODE,
185     Allow,
186     "usage of `unsafe` code"
187 }
188
189 #[derive(Copy, Clone)]
190 pub struct UnsafeCode;
191
192 impl LintPass for UnsafeCode {
193     fn get_lints(&self) -> LintArray {
194         lint_array!(UNSAFE_CODE)
195     }
196 }
197
198 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
199     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
200         if let hir::ExprBlock(ref blk) = e.node {
201             // Don't warn about generated blocks, that'll just pollute the output.
202             if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
203                 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
204             }
205         }
206     }
207
208     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
209         match it.node {
210             hir::ItemTrait(hir::Unsafety::Unsafe, ..) => {
211                 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait")
212             }
213
214             hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
215                 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait")
216             }
217
218             _ => return,
219         }
220     }
221
222     fn check_fn(&mut self,
223                 cx: &LateContext,
224                 fk: FnKind<'tcx>,
225                 _: &hir::FnDecl,
226                 _: &hir::Body,
227                 span: Span,
228                 _: ast::NodeId) {
229         match fk {
230             FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, ..) => {
231                 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function")
232             }
233
234             FnKind::Method(_, sig, ..) => {
235                 if sig.unsafety == hir::Unsafety::Unsafe {
236                     cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
237                 }
238             }
239
240             _ => (),
241         }
242     }
243
244     fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
245         if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
246             if sig.unsafety == hir::Unsafety::Unsafe {
247                 cx.span_lint(UNSAFE_CODE,
248                              item.span,
249                              "declaration of an `unsafe` method")
250             }
251         }
252     }
253 }
254
255 declare_lint! {
256     MISSING_DOCS,
257     Allow,
258     "detects missing documentation for public members"
259 }
260
261 pub struct MissingDoc {
262     /// Stack of whether #[doc(hidden)] is set
263     /// at each level which has lint attributes.
264     doc_hidden_stack: Vec<bool>,
265
266     /// Private traits or trait items that leaked through. Don't check their methods.
267     private_traits: HashSet<ast::NodeId>,
268 }
269
270 impl MissingDoc {
271     pub fn new() -> MissingDoc {
272         MissingDoc {
273             doc_hidden_stack: vec![false],
274             private_traits: HashSet::new(),
275         }
276     }
277
278     fn doc_hidden(&self) -> bool {
279         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
280     }
281
282     fn check_missing_docs_attrs(&self,
283                                 cx: &LateContext,
284                                 id: Option<ast::NodeId>,
285                                 attrs: &[ast::Attribute],
286                                 sp: Span,
287                                 desc: &'static str) {
288         // If we're building a test harness, then warning about
289         // documentation is probably not really relevant right now.
290         if cx.sess().opts.test {
291             return;
292         }
293
294         // `#[doc(hidden)]` disables missing_docs check.
295         if self.doc_hidden() {
296             return;
297         }
298
299         // Only check publicly-visible items, using the result from the privacy pass.
300         // It's an option so the crate root can also use this function (it doesn't
301         // have a NodeId).
302         if let Some(id) = id {
303             if !cx.access_levels.is_exported(id) {
304                 return;
305             }
306         }
307
308         let has_doc = attrs.iter().any(|a| a.is_value_str() && a.check_name("doc"));
309         if !has_doc {
310             cx.span_lint(MISSING_DOCS,
311                          sp,
312                          &format!("missing documentation for {}", desc));
313         }
314     }
315 }
316
317 impl LintPass for MissingDoc {
318     fn get_lints(&self) -> LintArray {
319         lint_array!(MISSING_DOCS)
320     }
321 }
322
323 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
324     fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
325         let doc_hidden = self.doc_hidden() ||
326                          attrs.iter().any(|attr| {
327             attr.check_name("doc") &&
328             match attr.meta_item_list() {
329                 None => false,
330                 Some(l) => attr::list_contains_name(&l, "hidden"),
331             }
332         });
333         self.doc_hidden_stack.push(doc_hidden);
334     }
335
336     fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
337         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
338     }
339
340     fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
341         self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
342     }
343
344     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
345         let desc = match it.node {
346             hir::ItemFn(..) => "a function",
347             hir::ItemMod(..) => "a module",
348             hir::ItemEnum(..) => "an enum",
349             hir::ItemStruct(..) => "a struct",
350             hir::ItemUnion(..) => "a union",
351             hir::ItemTrait(.., ref trait_item_refs) => {
352                 // Issue #11592, traits are always considered exported, even when private.
353                 if it.vis == hir::Visibility::Inherited {
354                     self.private_traits.insert(it.id);
355                     for trait_item_ref in trait_item_refs {
356                         self.private_traits.insert(trait_item_ref.id.node_id);
357                     }
358                     return;
359                 }
360                 "a trait"
361             }
362             hir::ItemTy(..) => "a type alias",
363             hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
364                 // If the trait is private, add the impl items to private_traits so they don't get
365                 // reported for missing docs.
366                 let real_trait = trait_ref.path.def.def_id();
367                 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
368                     match cx.tcx.hir.find(node_id) {
369                         Some(hir_map::NodeItem(item)) => {
370                             if item.vis == hir::Visibility::Inherited {
371                                 for impl_item_ref in impl_item_refs {
372                                     self.private_traits.insert(impl_item_ref.id.node_id);
373                                 }
374                             }
375                         }
376                         _ => {}
377                     }
378                 }
379                 return;
380             }
381             hir::ItemConst(..) => "a constant",
382             hir::ItemStatic(..) => "a static",
383             _ => return,
384         };
385
386         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
387     }
388
389     fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
390         if self.private_traits.contains(&trait_item.id) {
391             return;
392         }
393
394         let desc = match trait_item.node {
395             hir::TraitItemKind::Const(..) => "an associated constant",
396             hir::TraitItemKind::Method(..) => "a trait method",
397             hir::TraitItemKind::Type(..) => "an associated type",
398         };
399
400         self.check_missing_docs_attrs(cx,
401                                       Some(trait_item.id),
402                                       &trait_item.attrs,
403                                       trait_item.span,
404                                       desc);
405     }
406
407     fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
408         // If the method is an impl for a trait, don't doc.
409         if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
410             return;
411         }
412
413         let desc = match impl_item.node {
414             hir::ImplItemKind::Const(..) => "an associated constant",
415             hir::ImplItemKind::Method(..) => "a method",
416             hir::ImplItemKind::Type(_) => "an associated type",
417         };
418         self.check_missing_docs_attrs(cx,
419                                       Some(impl_item.id),
420                                       &impl_item.attrs,
421                                       impl_item.span,
422                                       desc);
423     }
424
425     fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
426         if !sf.is_positional() {
427             self.check_missing_docs_attrs(cx,
428                                           Some(sf.id),
429                                           &sf.attrs,
430                                           sf.span,
431                                           "a struct field")
432         }
433     }
434
435     fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
436         self.check_missing_docs_attrs(cx,
437                                       Some(v.node.data.id()),
438                                       &v.node.attrs,
439                                       v.span,
440                                       "a variant");
441     }
442 }
443
444 declare_lint! {
445     pub MISSING_COPY_IMPLEMENTATIONS,
446     Allow,
447     "detects potentially-forgotten implementations of `Copy`"
448 }
449
450 #[derive(Copy, Clone)]
451 pub struct MissingCopyImplementations;
452
453 impl LintPass for MissingCopyImplementations {
454     fn get_lints(&self) -> LintArray {
455         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
456     }
457 }
458
459 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
460     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
461         if !cx.access_levels.is_reachable(item.id) {
462             return;
463         }
464         let (def, ty) = match item.node {
465             hir::ItemStruct(_, ref ast_generics) => {
466                 if ast_generics.is_parameterized() {
467                     return;
468                 }
469                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
470                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
471             }
472             hir::ItemUnion(_, ref ast_generics) => {
473                 if ast_generics.is_parameterized() {
474                     return;
475                 }
476                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
477                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
478             }
479             hir::ItemEnum(_, ref ast_generics) => {
480                 if ast_generics.is_parameterized() {
481                     return;
482                 }
483                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
484                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
485             }
486             _ => return,
487         };
488         if def.has_dtor(cx.tcx) {
489             return;
490         }
491         let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
492         if !ty.moves_by_default(cx.tcx, param_env, item.span) {
493             return;
494         }
495         if param_env.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
496             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
497                          item.span,
498                          "type could implement `Copy`; consider adding `impl \
499                           Copy`")
500         }
501     }
502 }
503
504 declare_lint! {
505     MISSING_DEBUG_IMPLEMENTATIONS,
506     Allow,
507     "detects missing implementations of fmt::Debug"
508 }
509
510 pub struct MissingDebugImplementations {
511     impling_types: Option<NodeSet>,
512 }
513
514 impl MissingDebugImplementations {
515     pub fn new() -> MissingDebugImplementations {
516         MissingDebugImplementations { impling_types: None }
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<'a, 'tcx> LateLintPass<'a, 'tcx> 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(..) |
534             hir::ItemUnion(..) |
535             hir::ItemEnum(..) => {}
536             _ => return,
537         }
538
539         let debug = match cx.tcx.lang_items.debug_trait() {
540             Some(debug) => debug,
541             None => return,
542         };
543
544         if self.impling_types.is_none() {
545             let debug_def = cx.tcx.trait_def(debug);
546             let mut impls = NodeSet();
547             debug_def.for_each_impl(cx.tcx, |d| {
548                 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
549                     if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
550                         impls.insert(node_id);
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     pub ANONYMOUS_PARAMETERS,
570     Allow,
571     "detects anonymous parameters"
572 }
573
574 /// Checks for use of anonymous parameters (RFC 1685)
575 #[derive(Clone)]
576 pub struct AnonymousParameters;
577
578 impl LintPass for AnonymousParameters {
579     fn get_lints(&self) -> LintArray {
580         lint_array!(ANONYMOUS_PARAMETERS)
581     }
582 }
583
584 impl EarlyLintPass for AnonymousParameters {
585     fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
586         match it.node {
587             ast::TraitItemKind::Method(ref sig, _) => {
588                 for arg in sig.decl.inputs.iter() {
589                     match arg.pat.node {
590                         ast::PatKind::Ident(_, ident, None) => {
591                             if ident.node.name == keywords::Invalid.name() {
592                                 cx.span_lint(ANONYMOUS_PARAMETERS,
593                                              arg.pat.span,
594                                              "use of deprecated anonymous parameter");
595                             }
596                         }
597                         _ => (),
598                     }
599                 }
600             },
601             _ => (),
602         }
603     }
604 }
605
606 declare_lint! {
607     DEPRECATED_ATTR,
608     Warn,
609     "detects use of deprecated attributes"
610 }
611
612 /// Checks for use of attributes which have been deprecated.
613 #[derive(Clone)]
614 pub struct DeprecatedAttr {
615     // This is not free to compute, so we want to keep it around, rather than
616     // compute it for every attribute.
617     depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
618 }
619
620 impl DeprecatedAttr {
621     pub fn new() -> DeprecatedAttr {
622         DeprecatedAttr {
623             depr_attrs: deprecated_attributes(),
624         }
625     }
626 }
627
628 impl LintPass for DeprecatedAttr {
629     fn get_lints(&self) -> LintArray {
630         lint_array!(DEPRECATED_ATTR)
631     }
632 }
633
634 impl EarlyLintPass for DeprecatedAttr {
635     fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
636         let name = unwrap_or!(attr.name(), return);
637         for &&(n, _, ref g) in &self.depr_attrs {
638             if name == n {
639                 if let &AttributeGate::Gated(Stability::Deprecated(link),
640                                              ref name,
641                                              ref reason,
642                                              _) = g {
643                     cx.span_lint(DEPRECATED,
644                                  attr.span,
645                                  &format!("use of deprecated attribute `{}`: {}. See {}",
646                                           name, reason, link));
647                 }
648                 return;
649             }
650         }
651     }
652 }
653
654 declare_lint! {
655     pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
656     Warn,
657     "floating-point literals cannot be used in patterns"
658 }
659
660 /// Checks for floating point literals in patterns.
661 #[derive(Clone)]
662 pub struct IllegalFloatLiteralPattern;
663
664 impl LintPass for IllegalFloatLiteralPattern {
665     fn get_lints(&self) -> LintArray {
666         lint_array!(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN)
667     }
668 }
669
670 fn fl_lit_check_expr(cx: &EarlyContext, expr: &ast::Expr) {
671     use self::ast::{ExprKind, LitKind};
672     match expr.node {
673         ExprKind::Lit(ref l) => {
674             match l.node {
675                 LitKind::FloatUnsuffixed(..) |
676                 LitKind::Float(..) => {
677                     cx.span_lint(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
678                                  l.span,
679                                  "floating-point literals cannot be used in patterns");
680                     },
681                 _ => (),
682             }
683         }
684         // These may occur in patterns
685         // and can maybe contain float literals
686         ExprKind::Unary(_, ref f) => fl_lit_check_expr(cx, f),
687         // These may occur in patterns
688         // and can't contain float literals
689         ExprKind::Path(..) => (),
690         // If something unhandled is encountered, we need to expand the
691         // search or ignore more ExprKinds.
692         _ => span_bug!(expr.span, "Unhandled expression {:?} in float lit pattern lint",
693                        expr.node),
694     }
695 }
696
697 impl EarlyLintPass for IllegalFloatLiteralPattern {
698     fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
699         use self::ast::PatKind;
700         pat.walk(&mut |p| {
701             match p.node {
702                 // Wildcard patterns and paths are uninteresting for the lint
703                 PatKind::Wild |
704                 PatKind::Path(..) => (),
705
706                 // The walk logic recurses inside these
707                 PatKind::Ident(..) |
708                 PatKind::Struct(..) |
709                 PatKind::Tuple(..) |
710                 PatKind::TupleStruct(..) |
711                 PatKind::Ref(..) |
712                 PatKind::Box(..) |
713                 PatKind::Slice(..) => (),
714
715                 // Extract the expressions and check them
716                 PatKind::Lit(ref e) => fl_lit_check_expr(cx, e),
717                 PatKind::Range(ref st, ref en, _) => {
718                     fl_lit_check_expr(cx, st);
719                     fl_lit_check_expr(cx, en);
720                 },
721
722                 PatKind::Mac(_) => bug!("lint must run post-expansion"),
723             }
724             true
725         });
726     }
727 }
728
729 declare_lint! {
730     pub UNCONDITIONAL_RECURSION,
731     Warn,
732     "functions that cannot return without calling themselves"
733 }
734
735 #[derive(Copy, Clone)]
736 pub struct UnconditionalRecursion;
737
738
739 impl LintPass for UnconditionalRecursion {
740     fn get_lints(&self) -> LintArray {
741         lint_array![UNCONDITIONAL_RECURSION]
742     }
743 }
744
745 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
746     fn check_fn(&mut self,
747                 cx: &LateContext,
748                 fn_kind: FnKind,
749                 _: &hir::FnDecl,
750                 body: &hir::Body,
751                 sp: Span,
752                 id: ast::NodeId) {
753         let method = match fn_kind {
754             FnKind::ItemFn(..) => None,
755             FnKind::Method(..) => {
756                 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
757             }
758             // closures can't recur, so they don't matter.
759             FnKind::Closure(_) => return,
760         };
761
762         // Walk through this function (say `f`) looking to see if
763         // every possible path references itself, i.e. the function is
764         // called recursively unconditionally. This is done by trying
765         // to find a path from the entry node to the exit node that
766         // *doesn't* call `f` by traversing from the entry while
767         // pretending that calls of `f` are sinks (i.e. ignoring any
768         // exit edges from them).
769         //
770         // NB. this has an edge case with non-returning statements,
771         // like `loop {}` or `panic!()`: control flow never reaches
772         // the exit node through these, so one can have a function
773         // that never actually calls itselfs but is still picked up by
774         // this lint:
775         //
776         //     fn f(cond: bool) {
777         //         if !cond { panic!() } // could come from `assert!(cond)`
778         //         f(false)
779         //     }
780         //
781         // In general, functions of that form may be able to call
782         // itself a finite number of times and then diverge. The lint
783         // considers this to be an error for two reasons, (a) it is
784         // easier to implement, and (b) it seems rare to actually want
785         // to have behaviour like the above, rather than
786         // e.g. accidentally recurring after an assert.
787
788         let cfg = cfg::CFG::new(cx.tcx, &body);
789
790         let mut work_queue = vec![cfg.entry];
791         let mut reached_exit_without_self_call = false;
792         let mut self_call_spans = vec![];
793         let mut visited = HashSet::new();
794
795         while let Some(idx) = work_queue.pop() {
796             if idx == cfg.exit {
797                 // found a path!
798                 reached_exit_without_self_call = true;
799                 break;
800             }
801
802             let cfg_id = idx.node_id();
803             if visited.contains(&cfg_id) {
804                 // already done
805                 continue;
806             }
807             visited.insert(cfg_id);
808
809             let node_id = cfg.graph.node_data(idx).id();
810
811             // is this a recursive call?
812             let self_recursive = if node_id != ast::DUMMY_NODE_ID {
813                 match method {
814                     Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
815                     None => expr_refers_to_this_fn(cx, id, node_id),
816                 }
817             } else {
818                 false
819             };
820             if self_recursive {
821                 self_call_spans.push(cx.tcx.hir.span(node_id));
822                 // this is a self call, so we shouldn't explore past
823                 // this node in the CFG.
824                 continue;
825             }
826             // add the successors of this node to explore the graph further.
827             for (_, edge) in cfg.graph.outgoing_edges(idx) {
828                 let target_idx = edge.target();
829                 let target_cfg_id = target_idx.node_id();
830                 if !visited.contains(&target_cfg_id) {
831                     work_queue.push(target_idx)
832                 }
833             }
834         }
835
836         // Check the number of self calls because a function that
837         // doesn't return (e.g. calls a `-> !` function or `loop { /*
838         // no break */ }`) shouldn't be linted unless it actually
839         // recurs.
840         if !reached_exit_without_self_call && !self_call_spans.is_empty() {
841             let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
842                                              sp,
843                                              "function cannot return without recurring");
844
845             // FIXME #19668: these could be span_lint_note's instead of this manual guard.
846             if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
847                 // offer some help to the programmer.
848                 for call in &self_call_spans {
849                     db.span_note(*call, "recursive call site");
850                 }
851                 db.help("a `loop` may express intention \
852                          better if this is on purpose");
853             }
854             db.emit();
855         }
856
857         // all done
858         return;
859
860         // Functions for identifying if the given Expr NodeId `id`
861         // represents a call to the function `fn_id`/method `method`.
862
863         fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
864             match cx.tcx.hir.get(id) {
865                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
866                     let def = if let hir::ExprPath(ref qpath) = callee.node {
867                         cx.tables.qpath_def(qpath, callee.id)
868                     } else {
869                         return false;
870                     };
871                     def.def_id() == cx.tcx.hir.local_def_id(fn_id)
872                 }
873                 _ => false,
874             }
875         }
876
877         // Check if the expression `id` performs a call to `method`.
878         fn expr_refers_to_this_method(cx: &LateContext,
879                                       method: &ty::AssociatedItem,
880                                       id: ast::NodeId)
881                                       -> bool {
882             use rustc::ty::adjustment::*;
883
884             // Ignore non-expressions.
885             let expr = if let hir_map::NodeExpr(e) = cx.tcx.hir.get(id) {
886                 e
887             } else {
888                 return false;
889             };
890
891             // Check for overloaded autoderef method calls.
892             let mut source = cx.tables.expr_ty(expr);
893             for adjustment in cx.tables.expr_adjustments(expr) {
894                 if let Adjust::Deref(Some(deref)) = adjustment.kind {
895                     let (def_id, substs) = deref.method_call(cx.tcx, source);
896                     if method_call_refers_to_method(cx.tcx, method, def_id, substs, id) {
897                         return true;
898                     }
899                 }
900                 source = adjustment.target;
901             }
902
903             // Check for method calls and overloaded operators.
904             if cx.tables.is_method_call(expr) {
905                 let def_id = cx.tables.type_dependent_defs[&id].def_id();
906                 let substs = cx.tables.node_substs(id);
907                 if method_call_refers_to_method(cx.tcx, method, def_id, substs, id) {
908                     return true;
909                 }
910             }
911
912             // Check for calls to methods via explicit paths (e.g. `T::method()`).
913             match expr.node {
914                 hir::ExprCall(ref callee, _) => {
915                     let def = if let hir::ExprPath(ref qpath) = callee.node {
916                         cx.tables.qpath_def(qpath, callee.id)
917                     } else {
918                         return false;
919                     };
920                     match def {
921                         Def::Method(def_id) => {
922                             let substs = cx.tables.node_substs(callee.id);
923                             method_call_refers_to_method(
924                                 cx.tcx, method, def_id, substs, id)
925                         }
926                         _ => false,
927                     }
928                 }
929                 _ => false,
930             }
931         }
932
933         // Check if the method call to the method with the ID `callee_id`
934         // and instantiated with `callee_substs` refers to method `method`.
935         fn method_call_refers_to_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
936                                                   method: &ty::AssociatedItem,
937                                                   callee_id: DefId,
938                                                   callee_substs: &Substs<'tcx>,
939                                                   expr_id: ast::NodeId)
940                                                   -> bool {
941             let callee_item = tcx.associated_item(callee_id);
942
943             match callee_item.container {
944                 // This is an inherent method, so the `def_id` refers
945                 // directly to the method definition.
946                 ty::ImplContainer(_) => callee_id == method.def_id,
947
948                 // A trait method, from any number of possible sources.
949                 // Attempt to select a concrete impl before checking.
950                 ty::TraitContainer(trait_def_id) => {
951                     let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
952                     let trait_ref = ty::Binder(trait_ref);
953                     let span = tcx.hir.span(expr_id);
954                     let obligation =
955                         traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
956                                                 trait_ref.to_poly_trait_predicate());
957
958                     let param_env = tcx.param_env(method.def_id);
959                     tcx.infer_ctxt(param_env).enter(|infcx| {
960                         let mut selcx = traits::SelectionContext::new(&infcx);
961                         match selcx.select(&obligation) {
962                             // The method comes from a `T: Trait` bound.
963                             // If `T` is `Self`, then this call is inside
964                             // a default method definition.
965                             Ok(Some(traits::VtableParam(_))) => {
966                                 let on_self = trait_ref.self_ty().is_self();
967                                 // We can only be recurring in a default
968                                 // method if we're being called literally
969                                 // on the `Self` type.
970                                 on_self && callee_id == method.def_id
971                             }
972
973                             // The `impl` is known, so we check that with a
974                             // special case:
975                             Ok(Some(traits::VtableImpl(vtable_impl))) => {
976                                 let container = ty::ImplContainer(vtable_impl.impl_def_id);
977                                 // It matches if it comes from the same impl,
978                                 // and has the same method name.
979                                 container == method.container && callee_item.name == method.name
980                             }
981
982                             // There's no way to know if this call is
983                             // recursive, so we assume it's not.
984                             _ => false,
985                         }
986                     })
987                 }
988             }
989         }
990     }
991 }
992
993 declare_lint! {
994     PLUGIN_AS_LIBRARY,
995     Warn,
996     "compiler plugin used as ordinary library in non-plugin crate"
997 }
998
999 #[derive(Copy, Clone)]
1000 pub struct PluginAsLibrary;
1001
1002 impl LintPass for PluginAsLibrary {
1003     fn get_lints(&self) -> LintArray {
1004         lint_array![PLUGIN_AS_LIBRARY]
1005     }
1006 }
1007
1008 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1009     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1010         if cx.sess().plugin_registrar_fn.get().is_some() {
1011             // We're compiling a plugin; it's fine to link other plugins.
1012             return;
1013         }
1014
1015         match it.node {
1016             hir::ItemExternCrate(..) => (),
1017             _ => return,
1018         };
1019
1020         let prfn = match cx.sess().cstore.extern_mod_stmt_cnum(it.id) {
1021             Some(cnum) => cx.sess().cstore.plugin_registrar_fn(cnum),
1022             None => {
1023                 // Probably means we aren't linking the crate for some reason.
1024                 //
1025                 // Not sure if / when this could happen.
1026                 return;
1027             }
1028         };
1029
1030         if prfn.is_some() {
1031             cx.span_lint(PLUGIN_AS_LIBRARY,
1032                          it.span,
1033                          "compiler plugin used as an ordinary library");
1034         }
1035     }
1036 }
1037
1038 declare_lint! {
1039     PRIVATE_NO_MANGLE_FNS,
1040     Warn,
1041     "functions marked #[no_mangle] should be exported"
1042 }
1043
1044 declare_lint! {
1045     PRIVATE_NO_MANGLE_STATICS,
1046     Warn,
1047     "statics marked #[no_mangle] should be exported"
1048 }
1049
1050 declare_lint! {
1051     NO_MANGLE_CONST_ITEMS,
1052     Deny,
1053     "const items will not have their symbols exported"
1054 }
1055
1056 declare_lint! {
1057     NO_MANGLE_GENERIC_ITEMS,
1058     Warn,
1059     "generic items must be mangled"
1060 }
1061
1062 #[derive(Copy, Clone)]
1063 pub struct InvalidNoMangleItems;
1064
1065 impl LintPass for InvalidNoMangleItems {
1066     fn get_lints(&self) -> LintArray {
1067         lint_array!(PRIVATE_NO_MANGLE_FNS,
1068                     PRIVATE_NO_MANGLE_STATICS,
1069                     NO_MANGLE_CONST_ITEMS,
1070                     NO_MANGLE_GENERIC_ITEMS)
1071     }
1072 }
1073
1074 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1075     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1076         match it.node {
1077             hir::ItemFn(.., ref generics, _) => {
1078                 if attr::contains_name(&it.attrs, "no_mangle") {
1079                     if !cx.access_levels.is_reachable(it.id) {
1080                         let msg = format!("function {} is marked #[no_mangle], but not exported",
1081                                           it.name);
1082                         cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1083                     }
1084                     if generics.is_type_parameterized() {
1085                         cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
1086                                      it.span,
1087                                      "functions generic over types must be mangled");
1088                     }
1089                 }
1090             }
1091             hir::ItemStatic(..) => {
1092                 if attr::contains_name(&it.attrs, "no_mangle") &&
1093                    !cx.access_levels.is_reachable(it.id) {
1094                     let msg = format!("static {} is marked #[no_mangle], but not exported",
1095                                       it.name);
1096                     cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1097                 }
1098             }
1099             hir::ItemConst(..) => {
1100                 if attr::contains_name(&it.attrs, "no_mangle") {
1101                     // Const items do not refer to a particular location in memory, and therefore
1102                     // don't have anything to attach a symbol to
1103                     let msg = "const items should never be #[no_mangle], consider instead using \
1104                                `pub static`";
1105                     cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1106                 }
1107             }
1108             _ => {}
1109         }
1110     }
1111 }
1112
1113 #[derive(Clone, Copy)]
1114 pub struct MutableTransmutes;
1115
1116 declare_lint! {
1117     MUTABLE_TRANSMUTES,
1118     Deny,
1119     "mutating transmuted &mut T from &T may cause undefined behavior"
1120 }
1121
1122 impl LintPass for MutableTransmutes {
1123     fn get_lints(&self) -> LintArray {
1124         lint_array!(MUTABLE_TRANSMUTES)
1125     }
1126 }
1127
1128 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1129     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1130         use syntax::abi::Abi::RustIntrinsic;
1131
1132         let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1133                    consider instead using an UnsafeCell";
1134         match get_transmute_from_to(cx, expr) {
1135             Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1136                 if to_mt.mutbl == hir::Mutability::MutMutable &&
1137                    from_mt.mutbl == hir::Mutability::MutImmutable {
1138                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1139                 }
1140             }
1141             _ => (),
1142         }
1143
1144         fn get_transmute_from_to<'a, 'tcx>
1145             (cx: &LateContext<'a, 'tcx>,
1146              expr: &hir::Expr)
1147              -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1148             let def = if let hir::ExprPath(ref qpath) = expr.node {
1149                 cx.tables.qpath_def(qpath, expr.id)
1150             } else {
1151                 return None;
1152             };
1153             if let Def::Fn(did) = def {
1154                 if !def_id_is_transmute(cx, did) {
1155                     return None;
1156                 }
1157                 let typ = cx.tables.node_id_to_type(expr.id);
1158                 match typ.sty {
1159                     ty::TyFnDef(.., bare_fn) if bare_fn.abi() == RustIntrinsic => {
1160                         let from = bare_fn.inputs().skip_binder()[0];
1161                         let to = *bare_fn.output().skip_binder();
1162                         return Some((&from.sty, &to.sty));
1163                     }
1164                     _ => (),
1165                 }
1166             }
1167             None
1168         }
1169
1170         fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1171             match cx.tcx.type_of(def_id).sty {
1172                 ty::TyFnDef(.., bfty) if bfty.abi() == RustIntrinsic => (),
1173                 _ => return false,
1174             }
1175             cx.tcx.item_name(def_id) == "transmute"
1176         }
1177     }
1178 }
1179
1180 /// Forbids using the `#[feature(...)]` attribute
1181 #[derive(Copy, Clone)]
1182 pub struct UnstableFeatures;
1183
1184 declare_lint! {
1185     UNSTABLE_FEATURES,
1186     Allow,
1187     "enabling unstable features (deprecated. do not use)"
1188 }
1189
1190 impl LintPass for UnstableFeatures {
1191     fn get_lints(&self) -> LintArray {
1192         lint_array!(UNSTABLE_FEATURES)
1193     }
1194 }
1195
1196 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1197     fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1198         if attr.check_name("feature") {
1199             if let Some(items) = attr.meta_item_list() {
1200                 for item in items {
1201                     ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1202                 }
1203             }
1204         }
1205     }
1206 }
1207
1208 /// Lint for unions that contain fields with possibly non-trivial destructors.
1209 pub struct UnionsWithDropFields;
1210
1211 declare_lint! {
1212     UNIONS_WITH_DROP_FIELDS,
1213     Warn,
1214     "use of unions that contain fields with possibly non-trivial drop code"
1215 }
1216
1217 impl LintPass for UnionsWithDropFields {
1218     fn get_lints(&self) -> LintArray {
1219         lint_array!(UNIONS_WITH_DROP_FIELDS)
1220     }
1221 }
1222
1223 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1224     fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1225         if let hir::ItemUnion(ref vdata, _) = item.node {
1226             let item_def_id = ctx.tcx.hir.local_def_id(item.id);
1227             let param_env = ctx.tcx.param_env(item_def_id);
1228             for field in vdata.fields() {
1229                 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1230                 if field_ty.needs_drop(ctx.tcx, param_env) {
1231                     ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1232                                   field.span,
1233                                   "union contains a field with possibly non-trivial drop code, \
1234                                    drop code of union fields is ignored when dropping the union");
1235                     return;
1236                 }
1237             }
1238         }
1239     }
1240 }