]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
Use ast attributes every where (remove HIR attributes).
[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 metadata::{csearch, decoder};
32 use middle::{cfg, def, infer, pat_util, stability, traits};
33 use middle::def_id::DefId;
34 use middle::subst::Substs;
35 use middle::ty::{self, Ty};
36 use middle::ty::adjustment;
37 use middle::const_eval::{eval_const_expr_partial, ConstVal};
38 use middle::const_eval::EvalHint::ExprTypeChecked;
39 use rustc::front::map as hir_map;
40 use util::nodemap::{FnvHashMap, FnvHashSet, NodeSet};
41 use lint::{Level, Context, LintPass, LintArray, Lint};
42
43 use std::collections::HashSet;
44 use std::collections::hash_map::Entry::{Occupied, Vacant};
45 use std::{cmp, slice};
46 use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
47
48 use syntax::{abi, ast};
49 use syntax::attr::{self, AttrMetaMethods};
50 use syntax::codemap::{self, Span};
51 use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType};
52 use syntax::ast::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
53 use syntax::ptr::P;
54
55 use rustc_front::hir;
56 use rustc_front::visit::{self, FnKind, Visitor};
57 use rustc_front::util::is_shift_binop;
58
59 // hardwired lints from librustc
60 pub use lint::builtin::*;
61
62 declare_lint! {
63     WHILE_TRUE,
64     Warn,
65     "suggest using `loop { }` instead of `while true { }`"
66 }
67
68 #[derive(Copy, Clone)]
69 pub struct WhileTrue;
70
71 impl LintPass for WhileTrue {
72     fn get_lints(&self) -> LintArray {
73         lint_array!(WHILE_TRUE)
74     }
75
76     fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
77         if let hir::ExprWhile(ref cond, _, _) = e.node {
78             if let hir::ExprLit(ref lit) = cond.node {
79                 if let ast::LitBool(true) = lit.node {
80                     cx.span_lint(WHILE_TRUE, e.span,
81                                  "denote infinite loops with loop { ... }");
82                 }
83             }
84         }
85     }
86 }
87
88 declare_lint! {
89     UNUSED_COMPARISONS,
90     Warn,
91     "comparisons made useless by limits of the types involved"
92 }
93
94 declare_lint! {
95     OVERFLOWING_LITERALS,
96     Warn,
97     "literal out of range for its type"
98 }
99
100 declare_lint! {
101     EXCEEDING_BITSHIFTS,
102     Deny,
103     "shift exceeds the type's number of bits"
104 }
105
106 #[derive(Copy, Clone)]
107 pub struct TypeLimits {
108     /// Id of the last visited negated expression
109     negated_expr_id: ast::NodeId,
110 }
111
112 impl TypeLimits {
113     pub fn new() -> TypeLimits {
114         TypeLimits {
115             negated_expr_id: !0,
116         }
117     }
118 }
119
120 impl LintPass for TypeLimits {
121     fn get_lints(&self) -> LintArray {
122         lint_array!(UNUSED_COMPARISONS, OVERFLOWING_LITERALS, EXCEEDING_BITSHIFTS)
123     }
124
125     fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
126         match e.node {
127             hir::ExprUnary(hir::UnNeg, ref expr) => {
128                 match expr.node  {
129                     hir::ExprLit(ref lit) => {
130                         match lit.node {
131                             ast::LitInt(_, ast::UnsignedIntLit(_)) => {
132                                 check_unsigned_negation_feature(cx, e.span);
133                             },
134                             ast::LitInt(_, ast::UnsuffixedIntLit(_)) => {
135                                 if let ty::TyUint(_) = cx.tcx.node_id_to_type(e.id).sty {
136                                     check_unsigned_negation_feature(cx, e.span);
137                                 }
138                             },
139                             _ => ()
140                         }
141                     },
142                     _ => {
143                         let t = cx.tcx.node_id_to_type(expr.id);
144                         match t.sty {
145                             ty::TyUint(_) => {
146                                 check_unsigned_negation_feature(cx, e.span);
147                             },
148                             _ => ()
149                         }
150                     }
151                 };
152                 // propagate negation, if the negation itself isn't negated
153                 if self.negated_expr_id != e.id {
154                     self.negated_expr_id = expr.id;
155                 }
156             },
157             hir::ExprParen(ref expr) if self.negated_expr_id == e.id => {
158                 self.negated_expr_id = expr.id;
159             },
160             hir::ExprBinary(binop, ref l, ref r) => {
161                 if is_comparison(binop) && !check_limits(cx.tcx, binop, &**l, &**r) {
162                     cx.span_lint(UNUSED_COMPARISONS, e.span,
163                                  "comparison is useless due to type limits");
164                 }
165
166                 if is_shift_binop(binop.node) {
167                     let opt_ty_bits = match cx.tcx.node_id_to_type(l.id).sty {
168                         ty::TyInt(t) => Some(int_ty_bits(t, cx.sess().target.int_type)),
169                         ty::TyUint(t) => Some(uint_ty_bits(t, cx.sess().target.uint_type)),
170                         _ => None
171                     };
172
173                     if let Some(bits) = opt_ty_bits {
174                         let exceeding = if let hir::ExprLit(ref lit) = r.node {
175                             if let ast::LitInt(shift, _) = lit.node { shift >= bits }
176                             else { false }
177                         } else {
178                             match eval_const_expr_partial(cx.tcx, &r, ExprTypeChecked) {
179                                 Ok(ConstVal::Int(shift)) => { shift as u64 >= bits },
180                                 Ok(ConstVal::Uint(shift)) => { shift >= bits },
181                                 _ => { false }
182                             }
183                         };
184                         if exceeding {
185                             cx.span_lint(EXCEEDING_BITSHIFTS, e.span,
186                                          "bitshift exceeds the type's number of bits");
187                         }
188                     };
189                 }
190             },
191             hir::ExprLit(ref lit) => {
192                 match cx.tcx.node_id_to_type(e.id).sty {
193                     ty::TyInt(t) => {
194                         match lit.node {
195                             ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
196                             ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
197                                 let int_type = if let ast::TyIs = t {
198                                     cx.sess().target.int_type
199                                 } else {
200                                     t
201                                 };
202                                 let (_, max) = int_ty_range(int_type);
203                                 let negative = self.negated_expr_id == e.id;
204
205                                 // Detect literal value out of range [min, max] inclusive
206                                 // avoiding use of -min to prevent overflow/panic
207                                 if (negative && v > max as u64 + 1) ||
208                                    (!negative && v > max as u64) {
209                                     cx.span_lint(OVERFLOWING_LITERALS, e.span,
210                                                  &*format!("literal out of range for {:?}", t));
211                                     return;
212                                 }
213                             }
214                             _ => panic!()
215                         };
216                     },
217                     ty::TyUint(t) => {
218                         let uint_type = if let ast::TyUs = t {
219                             cx.sess().target.uint_type
220                         } else {
221                             t
222                         };
223                         let (min, max) = uint_ty_range(uint_type);
224                         let lit_val: u64 = match lit.node {
225                             ast::LitByte(_v) => return,  // _v is u8, within range by definition
226                             ast::LitInt(v, _) => v,
227                             _ => panic!()
228                         };
229                         if lit_val < min || lit_val > max {
230                             cx.span_lint(OVERFLOWING_LITERALS, e.span,
231                                          &*format!("literal out of range for {:?}", t));
232                         }
233                     },
234                     ty::TyFloat(t) => {
235                         let (min, max) = float_ty_range(t);
236                         let lit_val: f64 = match lit.node {
237                             ast::LitFloat(ref v, _) |
238                             ast::LitFloatUnsuffixed(ref v) => {
239                                 match v.parse() {
240                                     Ok(f) => f,
241                                     Err(_) => return
242                                 }
243                             }
244                             _ => panic!()
245                         };
246                         if lit_val < min || lit_val > max {
247                             cx.span_lint(OVERFLOWING_LITERALS, e.span,
248                                          &*format!("literal out of range for {:?}", t));
249                         }
250                     },
251                     _ => ()
252                 };
253             },
254             _ => ()
255         };
256
257         fn is_valid<T:cmp::PartialOrd>(binop: hir::BinOp, v: T,
258                                 min: T, max: T) -> bool {
259             match binop.node {
260                 hir::BiLt => v >  min && v <= max,
261                 hir::BiLe => v >= min && v <  max,
262                 hir::BiGt => v >= min && v <  max,
263                 hir::BiGe => v >  min && v <= max,
264                 hir::BiEq | hir::BiNe => v >= min && v <= max,
265                 _ => panic!()
266             }
267         }
268
269         fn rev_binop(binop: hir::BinOp) -> hir::BinOp {
270             codemap::respan(binop.span, match binop.node {
271                 hir::BiLt => hir::BiGt,
272                 hir::BiLe => hir::BiGe,
273                 hir::BiGt => hir::BiLt,
274                 hir::BiGe => hir::BiLe,
275                 _ => return binop
276             })
277         }
278
279         // for isize & usize, be conservative with the warnings, so that the
280         // warnings are consistent between 32- and 64-bit platforms
281         fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
282             match int_ty {
283                 ast::TyIs => (i64::MIN,        i64::MAX),
284                 ast::TyI8 =>    (i8::MIN  as i64, i8::MAX  as i64),
285                 ast::TyI16 =>   (i16::MIN as i64, i16::MAX as i64),
286                 ast::TyI32 =>   (i32::MIN as i64, i32::MAX as i64),
287                 ast::TyI64 =>   (i64::MIN,        i64::MAX)
288             }
289         }
290
291         fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
292             match uint_ty {
293                 ast::TyUs => (u64::MIN,         u64::MAX),
294                 ast::TyU8 =>    (u8::MIN   as u64, u8::MAX   as u64),
295                 ast::TyU16 =>   (u16::MIN  as u64, u16::MAX  as u64),
296                 ast::TyU32 =>   (u32::MIN  as u64, u32::MAX  as u64),
297                 ast::TyU64 =>   (u64::MIN,         u64::MAX)
298             }
299         }
300
301         fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
302             match float_ty {
303                 ast::TyF32 => (f32::MIN as f64, f32::MAX as f64),
304                 ast::TyF64 => (f64::MIN,        f64::MAX)
305             }
306         }
307
308         fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
309             match int_ty {
310                 ast::TyIs => int_ty_bits(target_int_ty, target_int_ty),
311                 ast::TyI8 =>    i8::BITS  as u64,
312                 ast::TyI16 =>   i16::BITS as u64,
313                 ast::TyI32 =>   i32::BITS as u64,
314                 ast::TyI64 =>   i64::BITS as u64
315             }
316         }
317
318         fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
319             match uint_ty {
320                 ast::TyUs => uint_ty_bits(target_uint_ty, target_uint_ty),
321                 ast::TyU8 =>    u8::BITS  as u64,
322                 ast::TyU16 =>   u16::BITS as u64,
323                 ast::TyU32 =>   u32::BITS as u64,
324                 ast::TyU64 =>   u64::BITS as u64
325             }
326         }
327
328         fn check_limits(tcx: &ty::ctxt, binop: hir::BinOp,
329                         l: &hir::Expr, r: &hir::Expr) -> bool {
330             let (lit, expr, swap) = match (&l.node, &r.node) {
331                 (&hir::ExprLit(_), _) => (l, r, true),
332                 (_, &hir::ExprLit(_)) => (r, l, false),
333                 _ => return true
334             };
335             // Normalize the binop so that the literal is always on the RHS in
336             // the comparison
337             let norm_binop = if swap {
338                 rev_binop(binop)
339             } else {
340                 binop
341             };
342             match tcx.node_id_to_type(expr.id).sty {
343                 ty::TyInt(int_ty) => {
344                     let (min, max) = int_ty_range(int_ty);
345                     let lit_val: i64 = match lit.node {
346                         hir::ExprLit(ref li) => match li.node {
347                             ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) |
348                             ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => v as i64,
349                             ast::LitInt(v, ast::SignedIntLit(_, ast::Minus)) |
350                             ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
351                             _ => return true
352                         },
353                         _ => panic!()
354                     };
355                     is_valid(norm_binop, lit_val, min, max)
356                 }
357                 ty::TyUint(uint_ty) => {
358                     let (min, max): (u64, u64) = uint_ty_range(uint_ty);
359                     let lit_val: u64 = match lit.node {
360                         hir::ExprLit(ref li) => match li.node {
361                             ast::LitInt(v, _) => v,
362                             _ => return true
363                         },
364                         _ => panic!()
365                     };
366                     is_valid(norm_binop, lit_val, min, max)
367                 }
368                 _ => true
369             }
370         }
371
372         fn is_comparison(binop: hir::BinOp) -> bool {
373             match binop.node {
374                 hir::BiEq | hir::BiLt | hir::BiLe |
375                 hir::BiNe | hir::BiGe | hir::BiGt => true,
376                 _ => false
377             }
378         }
379
380         fn check_unsigned_negation_feature(cx: &Context, span: Span) {
381             if !cx.sess().features.borrow().negate_unsigned {
382                 // FIXME(#27141): change this to syntax::feature_gate::emit_feature_err…
383                 cx.sess().span_warn(span,
384                     "unary negation of unsigned integers will be feature gated in the future");
385                 // â€¦and remove following two expressions.
386                 if option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some() { return; }
387                 cx.sess().fileline_help(span, "add #![feature(negate_unsigned)] to the \
388                                                crate attributes to enable the gate in advance");
389             }
390         }
391     }
392 }
393
394 declare_lint! {
395     IMPROPER_CTYPES,
396     Warn,
397     "proper use of libc types in foreign modules"
398 }
399
400 struct ImproperCTypesVisitor<'a, 'tcx: 'a> {
401     cx: &'a Context<'a, 'tcx>
402 }
403
404 enum FfiResult {
405     FfiSafe,
406     FfiUnsafe(&'static str),
407     FfiBadStruct(DefId, &'static str),
408     FfiBadEnum(DefId, &'static str)
409 }
410
411 /// Check if this enum can be safely exported based on the
412 /// "nullable pointer optimization". Currently restricted
413 /// to function pointers and references, but could be
414 /// expanded to cover NonZero raw pointers and newtypes.
415 /// FIXME: This duplicates code in trans.
416 fn is_repr_nullable_ptr<'tcx>(tcx: &ty::ctxt<'tcx>,
417                               def: ty::AdtDef<'tcx>,
418                               substs: &Substs<'tcx>)
419                               -> bool {
420     if def.variants.len() == 2 {
421         let data_idx;
422
423         if def.variants[0].fields.is_empty() {
424             data_idx = 1;
425         } else if def.variants[1].fields.is_empty() {
426             data_idx = 0;
427         } else {
428             return false;
429         }
430
431         if def.variants[data_idx].fields.len() == 1 {
432             match def.variants[data_idx].fields[0].ty(tcx, substs).sty {
433                 ty::TyBareFn(None, _) => { return true; }
434                 ty::TyRef(..) => { return true; }
435                 _ => { }
436             }
437         }
438     }
439     false
440 }
441
442 fn ast_ty_to_normalized<'tcx>(tcx: &ty::ctxt<'tcx>,
443                               id: ast::NodeId)
444                               -> Ty<'tcx> {
445     let tty = match tcx.ast_ty_to_ty_cache.borrow().get(&id) {
446         Some(&t) => t,
447         None => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
448     };
449     infer::normalize_associated_type(tcx, &tty)
450 }
451
452 impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
453     /// Check if the given type is "ffi-safe" (has a stable, well-defined
454     /// representation which can be exported to C code).
455     fn check_type_for_ffi(&self,
456                           cache: &mut FnvHashSet<Ty<'tcx>>,
457                           ty: Ty<'tcx>)
458                           -> FfiResult {
459         use self::FfiResult::*;
460         let cx = &self.cx.tcx;
461
462         // Protect against infinite recursion, for example
463         // `struct S(*mut S);`.
464         // FIXME: A recursion limit is necessary as well, for irregular
465         // recusive types.
466         if !cache.insert(ty) {
467             return FfiSafe;
468         }
469
470         match ty.sty {
471             ty::TyStruct(def, substs) => {
472                 if !cx.lookup_repr_hints(def.did).contains(&attr::ReprExtern) {
473                     return FfiUnsafe(
474                         "found struct without foreign-function-safe \
475                          representation annotation in foreign module, \
476                          consider adding a #[repr(C)] attribute to \
477                          the type");
478                 }
479
480                 // We can't completely trust repr(C) markings; make sure the
481                 // fields are actually safe.
482                 if def.struct_variant().fields.is_empty() {
483                     return FfiUnsafe(
484                         "found zero-size struct in foreign module, consider \
485                          adding a member to this struct");
486                 }
487
488                 for field in &def.struct_variant().fields {
489                     let field_ty = infer::normalize_associated_type(cx, &field.ty(cx, substs));
490                     let r = self.check_type_for_ffi(cache, field_ty);
491                     match r {
492                         FfiSafe => {}
493                         FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
494                         FfiUnsafe(s) => { return FfiBadStruct(def.did, s); }
495                     }
496                 }
497                 FfiSafe
498             }
499             ty::TyEnum(def, substs) => {
500                 if def.variants.is_empty() {
501                     // Empty enums are okay... although sort of useless.
502                     return FfiSafe
503                 }
504
505                 // Check for a repr() attribute to specify the size of the
506                 // discriminant.
507                 let repr_hints = cx.lookup_repr_hints(def.did);
508                 match &**repr_hints {
509                     [] => {
510                         // Special-case types like `Option<extern fn()>`.
511                         if !is_repr_nullable_ptr(cx, def, substs) {
512                             return FfiUnsafe(
513                                 "found enum without foreign-function-safe \
514                                  representation annotation in foreign module, \
515                                  consider adding a #[repr(...)] attribute to \
516                                  the type")
517                         }
518                     }
519                     [ref hint] => {
520                         if !hint.is_ffi_safe() {
521                             // FIXME: This shouldn't be reachable: we should check
522                             // this earlier.
523                             return FfiUnsafe(
524                                 "enum has unexpected #[repr(...)] attribute")
525                         }
526
527                         // Enum with an explicitly sized discriminant; either
528                         // a C-style enum or a discriminated union.
529
530                         // The layout of enum variants is implicitly repr(C).
531                         // FIXME: Is that correct?
532                     }
533                     _ => {
534                         // FIXME: This shouldn't be reachable: we should check
535                         // this earlier.
536                         return FfiUnsafe(
537                             "enum has too many #[repr(...)] attributes");
538                     }
539                 }
540
541                 // Check the contained variants.
542                 for variant in &def.variants {
543                     for field in &variant.fields {
544                         let arg = infer::normalize_associated_type(cx, &field.ty(cx, substs));
545                         let r = self.check_type_for_ffi(cache, arg);
546                         match r {
547                             FfiSafe => {}
548                             FfiBadStruct(..) | FfiBadEnum(..) => { return r; }
549                             FfiUnsafe(s) => { return FfiBadEnum(def.did, s); }
550                         }
551                     }
552                 }
553                 FfiSafe
554             }
555
556             ty::TyInt(ast::TyIs) => {
557                 FfiUnsafe("found Rust type `isize` in foreign module, while \
558                           `libc::c_int` or `libc::c_long` should be used")
559             }
560             ty::TyUint(ast::TyUs) => {
561                 FfiUnsafe("found Rust type `usize` in foreign module, while \
562                           `libc::c_uint` or `libc::c_ulong` should be used")
563             }
564             ty::TyChar => {
565                 FfiUnsafe("found Rust type `char` in foreign module, while \
566                            `u32` or `libc::wchar_t` should be used")
567             }
568
569             // Primitive types with a stable representation.
570             ty::TyBool | ty::TyInt(..) | ty::TyUint(..) |
571             ty::TyFloat(..) => FfiSafe,
572
573             ty::TyBox(..) => {
574                 FfiUnsafe("found Rust type Box<_> in foreign module, \
575                            consider using a raw pointer instead")
576             }
577
578             ty::TySlice(_) => {
579                 FfiUnsafe("found Rust slice type in foreign module, \
580                            consider using a raw pointer instead")
581             }
582
583             ty::TyTrait(..) => {
584                 FfiUnsafe("found Rust trait type in foreign module, \
585                            consider using a raw pointer instead")
586             }
587
588             ty::TyStr => {
589                 FfiUnsafe("found Rust type `str` in foreign module; \
590                            consider using a `*const libc::c_char`")
591             }
592
593             ty::TyTuple(_) => {
594                 FfiUnsafe("found Rust tuple type in foreign module; \
595                            consider using a struct instead`")
596             }
597
598             ty::TyRawPtr(ref m) | ty::TyRef(_, ref m) => {
599                 self.check_type_for_ffi(cache, m.ty)
600             }
601
602             ty::TyArray(ty, _) => {
603                 self.check_type_for_ffi(cache, ty)
604             }
605
606             ty::TyBareFn(None, bare_fn) => {
607                 match bare_fn.abi {
608                     abi::Rust |
609                     abi::RustIntrinsic |
610                     abi::PlatformIntrinsic |
611                     abi::RustCall => {
612                         return FfiUnsafe(
613                             "found function pointer with Rust calling \
614                              convention in foreign module; consider using an \
615                              `extern` function pointer")
616                     }
617                     _ => {}
618                 }
619
620                 let sig = cx.erase_late_bound_regions(&bare_fn.sig);
621                 match sig.output {
622                     ty::FnDiverging => {}
623                     ty::FnConverging(output) => {
624                         if !output.is_nil() {
625                             let r = self.check_type_for_ffi(cache, output);
626                             match r {
627                                 FfiSafe => {}
628                                 _ => { return r; }
629                             }
630                         }
631                     }
632                 }
633                 for arg in sig.inputs {
634                     let r = self.check_type_for_ffi(cache, arg);
635                     match r {
636                         FfiSafe => {}
637                         _ => { return r; }
638                     }
639                 }
640                 FfiSafe
641             }
642
643             ty::TyParam(..) | ty::TyInfer(..) | ty::TyError |
644             ty::TyClosure(..) | ty::TyProjection(..) |
645             ty::TyBareFn(Some(_), _) => {
646                 panic!("Unexpected type in foreign function")
647             }
648         }
649     }
650
651     fn check_def(&mut self, sp: Span, id: ast::NodeId) {
652         let tty = ast_ty_to_normalized(self.cx.tcx, id);
653
654         match ImproperCTypesVisitor::check_type_for_ffi(self, &mut FnvHashSet(), tty) {
655             FfiResult::FfiSafe => {}
656             FfiResult::FfiUnsafe(s) => {
657                 self.cx.span_lint(IMPROPER_CTYPES, sp, s);
658             }
659             FfiResult::FfiBadStruct(_, s) => {
660                 // FIXME: This diagnostic is difficult to read, and doesn't
661                 // point at the relevant field.
662                 self.cx.span_lint(IMPROPER_CTYPES, sp,
663                     &format!("found non-foreign-function-safe member in \
664                               struct marked #[repr(C)]: {}", s));
665             }
666             FfiResult::FfiBadEnum(_, s) => {
667                 // FIXME: This diagnostic is difficult to read, and doesn't
668                 // point at the relevant variant.
669                 self.cx.span_lint(IMPROPER_CTYPES, sp,
670                     &format!("found non-foreign-function-safe member in \
671                               enum: {}", s));
672             }
673         }
674     }
675 }
676
677 impl<'a, 'tcx, 'v> Visitor<'v> for ImproperCTypesVisitor<'a, 'tcx> {
678     fn visit_ty(&mut self, ty: &hir::Ty) {
679         match ty.node {
680             hir::TyPath(..) |
681             hir::TyBareFn(..) => self.check_def(ty.span, ty.id),
682             hir::TyVec(..) => {
683                 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
684                     "found Rust slice type in foreign module, consider \
685                      using a raw pointer instead");
686             }
687             hir::TyFixedLengthVec(ref ty, _) => self.visit_ty(ty),
688             hir::TyTup(..) => {
689                 self.cx.span_lint(IMPROPER_CTYPES, ty.span,
690                     "found Rust tuple type in foreign module; \
691                      consider using a struct instead`")
692             }
693             _ => visit::walk_ty(self, ty)
694         }
695     }
696 }
697
698 #[derive(Copy, Clone)]
699 pub struct ImproperCTypes;
700
701 impl LintPass for ImproperCTypes {
702     fn get_lints(&self) -> LintArray {
703         lint_array!(IMPROPER_CTYPES)
704     }
705
706     fn check_item(&mut self, cx: &Context, it: &hir::Item) {
707         fn check_ty(cx: &Context, ty: &hir::Ty) {
708             let mut vis = ImproperCTypesVisitor { cx: cx };
709             vis.visit_ty(ty);
710         }
711
712         fn check_foreign_fn(cx: &Context, decl: &hir::FnDecl) {
713             for input in &decl.inputs {
714                 check_ty(cx, &*input.ty);
715             }
716             if let hir::Return(ref ret_ty) = decl.output {
717                 let tty = ast_ty_to_normalized(cx.tcx, ret_ty.id);
718                 if !tty.is_nil() {
719                     check_ty(cx, &ret_ty);
720                 }
721             }
722         }
723
724         match it.node {
725             hir::ItemForeignMod(ref nmod)
726                 if nmod.abi != abi::RustIntrinsic &&
727                    nmod.abi != abi::PlatformIntrinsic => {
728                 for ni in &nmod.items {
729                     match ni.node {
730                         hir::ForeignItemFn(ref decl, _) => check_foreign_fn(cx, &**decl),
731                         hir::ForeignItemStatic(ref t, _) => check_ty(cx, &**t)
732                     }
733                 }
734             }
735             _ => (),
736         }
737     }
738 }
739
740 declare_lint! {
741     BOX_POINTERS,
742     Allow,
743     "use of owned (Box type) heap memory"
744 }
745
746 #[derive(Copy, Clone)]
747 pub struct BoxPointers;
748
749 impl BoxPointers {
750     fn check_heap_type<'a, 'tcx>(&self, cx: &Context<'a, 'tcx>,
751                                  span: Span, ty: Ty<'tcx>) {
752         for leaf_ty in ty.walk() {
753             if let ty::TyBox(_) = leaf_ty.sty {
754                 let m = format!("type uses owned (Box type) pointers: {}", ty);
755                 cx.span_lint(BOX_POINTERS, span, &m);
756             }
757         }
758     }
759 }
760
761 impl LintPass for BoxPointers {
762     fn get_lints(&self) -> LintArray {
763         lint_array!(BOX_POINTERS)
764     }
765
766     fn check_item(&mut self, cx: &Context, it: &hir::Item) {
767         match it.node {
768             hir::ItemFn(..) |
769             hir::ItemTy(..) |
770             hir::ItemEnum(..) |
771             hir::ItemStruct(..) =>
772                 self.check_heap_type(cx, it.span,
773                                      cx.tcx.node_id_to_type(it.id)),
774             _ => ()
775         }
776
777         // If it's a struct, we also have to check the fields' types
778         match it.node {
779             hir::ItemStruct(ref struct_def, _) => {
780                 for struct_field in &struct_def.fields {
781                     self.check_heap_type(cx, struct_field.span,
782                                          cx.tcx.node_id_to_type(struct_field.node.id));
783                 }
784             }
785             _ => ()
786         }
787     }
788
789     fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
790         let ty = cx.tcx.node_id_to_type(e.id);
791         self.check_heap_type(cx, e.span, ty);
792     }
793 }
794
795 declare_lint! {
796     RAW_POINTER_DERIVE,
797     Warn,
798     "uses of #[derive] with raw pointers are rarely correct"
799 }
800
801 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
802     cx: &'a Context<'a, 'tcx>
803 }
804
805 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
806     fn visit_ty(&mut self, ty: &hir::Ty) {
807         const MSG: &'static str = "use of `#[derive]` with a raw pointer";
808         if let hir::TyPtr(..) = ty.node {
809             self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
810         }
811         visit::walk_ty(self, ty);
812     }
813     // explicit override to a no-op to reduce code bloat
814     fn visit_expr(&mut self, _: &hir::Expr) {}
815     fn visit_block(&mut self, _: &hir::Block) {}
816 }
817
818 pub struct RawPointerDerive {
819     checked_raw_pointers: NodeSet,
820 }
821
822 impl RawPointerDerive {
823     pub fn new() -> RawPointerDerive {
824         RawPointerDerive {
825             checked_raw_pointers: NodeSet(),
826         }
827     }
828 }
829
830 impl LintPass for RawPointerDerive {
831     fn get_lints(&self) -> LintArray {
832         lint_array!(RAW_POINTER_DERIVE)
833     }
834
835     fn check_item(&mut self, cx: &Context, item: &hir::Item) {
836         if !attr::contains_name(&item.attrs, "automatically_derived") {
837             return;
838         }
839         let did = match item.node {
840             hir::ItemImpl(_, _, _, ref t_ref_opt, _, _) => {
841                 // Deriving the Copy trait does not cause a warning
842                 if let &Some(ref trait_ref) = t_ref_opt {
843                     let def_id = cx.tcx.trait_ref_to_def_id(trait_ref);
844                     if Some(def_id) == cx.tcx.lang_items.copy_trait() {
845                         return;
846                     }
847                 }
848
849                 match cx.tcx.node_id_to_type(item.id).sty {
850                     ty::TyEnum(def, _) => def.did,
851                     ty::TyStruct(def, _) => def.did,
852                     _ => return,
853                 }
854             }
855             _ => return,
856         };
857         if !did.is_local() {
858             return;
859         }
860         let item = match cx.tcx.map.find(did.node) {
861             Some(hir_map::NodeItem(item)) => item,
862             _ => return,
863         };
864         if !self.checked_raw_pointers.insert(item.id) {
865             return;
866         }
867         match item.node {
868             hir::ItemStruct(..) | hir::ItemEnum(..) => {
869                 let mut visitor = RawPtrDeriveVisitor { cx: cx };
870                 visit::walk_item(&mut visitor, &item);
871             }
872             _ => {}
873         }
874     }
875 }
876
877 declare_lint! {
878     UNUSED_ATTRIBUTES,
879     Warn,
880     "detects attributes that were not used by the compiler"
881 }
882
883 #[derive(Copy, Clone)]
884 pub struct UnusedAttributes;
885
886 impl LintPass for UnusedAttributes {
887     fn get_lints(&self) -> LintArray {
888         lint_array!(UNUSED_ATTRIBUTES)
889     }
890
891     fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
892         // Note that check_name() marks the attribute as used if it matches.
893         for &(ref name, ty, _) in KNOWN_ATTRIBUTES {
894             match ty {
895                 AttributeType::Whitelisted if attr.check_name(name) => {
896                     break;
897                 },
898                 _ => ()
899             }
900         }
901
902         let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
903         for &(ref name, ty) in plugin_attributes.iter() {
904             if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
905                 break;
906             }
907         }
908
909         if !attr::is_used(attr) {
910             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
911             // Is it a builtin attribute that must be used at the crate level?
912             let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
913                 attr.name() == name &&
914                 ty == AttributeType::CrateLevel
915             }).is_some();
916
917             // Has a plugin registered this attribute as one which must be used at
918             // the crate level?
919             let plugin_crate = plugin_attributes.iter()
920                                                 .find(|&&(ref x, t)| {
921                                                         &*attr.name() == &*x &&
922                                                         AttributeType::CrateLevel == t
923                                                     }).is_some();
924             if  known_crate || plugin_crate {
925                 let msg = match attr.node.style {
926                     ast::AttrOuter => "crate-level attribute should be an inner \
927                                        attribute: add an exclamation mark: #![foo]",
928                     ast::AttrInner => "crate-level attribute should be in the \
929                                        root module",
930                 };
931                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
932             }
933         }
934     }
935 }
936
937 declare_lint! {
938     pub PATH_STATEMENTS,
939     Warn,
940     "path statements with no effect"
941 }
942
943 #[derive(Copy, Clone)]
944 pub struct PathStatements;
945
946 impl LintPass for PathStatements {
947     fn get_lints(&self) -> LintArray {
948         lint_array!(PATH_STATEMENTS)
949     }
950
951     fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
952         match s.node {
953             hir::StmtSemi(ref expr, _) => {
954                 match expr.node {
955                     hir::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
956                                                       "path statement with no effect"),
957                     _ => ()
958                 }
959             }
960             _ => ()
961         }
962     }
963 }
964
965 declare_lint! {
966     pub UNUSED_MUST_USE,
967     Warn,
968     "unused result of a type flagged as #[must_use]"
969 }
970
971 declare_lint! {
972     pub UNUSED_RESULTS,
973     Allow,
974     "unused result of an expression in a statement"
975 }
976
977 #[derive(Copy, Clone)]
978 pub struct UnusedResults;
979
980 impl LintPass for UnusedResults {
981     fn get_lints(&self) -> LintArray {
982         lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
983     }
984
985     fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
986         let expr = match s.node {
987             hir::StmtSemi(ref expr, _) => &**expr,
988             _ => return
989         };
990
991         if let hir::ExprRet(..) = expr.node {
992             return;
993         }
994
995         let t = cx.tcx.expr_ty(&expr);
996         let warned = match t.sty {
997             ty::TyTuple(ref tys) if tys.is_empty() => return,
998             ty::TyBool => return,
999             ty::TyStruct(def, _) |
1000             ty::TyEnum(def, _) => {
1001                 if def.did.is_local() {
1002                     if let hir_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
1003                         check_must_use(cx, &it.attrs, s.span)
1004                     } else {
1005                         false
1006                     }
1007                 } else {
1008                     let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
1009                     check_must_use(cx, &attrs[..], s.span)
1010                 }
1011             }
1012             _ => false,
1013         };
1014         if !warned {
1015             cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
1016         }
1017
1018         fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
1019             for attr in attrs {
1020                 if attr.check_name("must_use") {
1021                     let mut msg = "unused result which must be used".to_string();
1022                     // check for #[must_use="..."]
1023                     match attr.value_str() {
1024                         None => {}
1025                         Some(s) => {
1026                             msg.push_str(": ");
1027                             msg.push_str(&s);
1028                         }
1029                     }
1030                     cx.span_lint(UNUSED_MUST_USE, sp, &msg);
1031                     return true;
1032                 }
1033             }
1034             false
1035         }
1036     }
1037 }
1038
1039 declare_lint! {
1040     pub NON_CAMEL_CASE_TYPES,
1041     Warn,
1042     "types, variants, traits and type parameters should have camel case names"
1043 }
1044
1045 #[derive(Copy, Clone)]
1046 pub struct NonCamelCaseTypes;
1047
1048 impl NonCamelCaseTypes {
1049     fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1050         fn is_camel_case(ident: ast::Ident) -> bool {
1051             let ident = ident.name.as_str();
1052             if ident.is_empty() {
1053                 return true;
1054             }
1055             let ident = ident.trim_matches('_');
1056
1057             // start with a non-lowercase letter rather than non-uppercase
1058             // ones (some scripts don't have a concept of upper/lowercase)
1059             !ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
1060         }
1061
1062         fn to_camel_case(s: &str) -> String {
1063             s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
1064                 if i == 0 {
1065                     c.to_uppercase().collect::<String>()
1066                 } else {
1067                     c.to_lowercase().collect()
1068                 }
1069             )).collect::<Vec<_>>().concat()
1070         }
1071
1072         let s = ident.name.as_str();
1073
1074         if !is_camel_case(ident) {
1075             let c = to_camel_case(&s);
1076             let m = if c.is_empty() {
1077                 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
1078             } else {
1079                 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
1080             };
1081             cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
1082         }
1083     }
1084 }
1085
1086 impl LintPass for NonCamelCaseTypes {
1087     fn get_lints(&self) -> LintArray {
1088         lint_array!(NON_CAMEL_CASE_TYPES)
1089     }
1090
1091     fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1092         let extern_repr_count = it.attrs.iter().filter(|attr| {
1093             attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
1094                 .any(|r| r == &attr::ReprExtern)
1095         }).count();
1096         let has_extern_repr = extern_repr_count > 0;
1097
1098         if has_extern_repr {
1099             return;
1100         }
1101
1102         match it.node {
1103             hir::ItemTy(..) | hir::ItemStruct(..) => {
1104                 self.check_case(cx, "type", it.ident, it.span)
1105             }
1106             hir::ItemTrait(..) => {
1107                 self.check_case(cx, "trait", it.ident, it.span)
1108             }
1109             hir::ItemEnum(ref enum_definition, _) => {
1110                 if has_extern_repr {
1111                     return;
1112                 }
1113                 self.check_case(cx, "type", it.ident, it.span);
1114                 for variant in &enum_definition.variants {
1115                     self.check_case(cx, "variant", variant.node.name, variant.span);
1116                 }
1117             }
1118             _ => ()
1119         }
1120     }
1121
1122     fn check_generics(&mut self, cx: &Context, it: &hir::Generics) {
1123         for gen in it.ty_params.iter() {
1124             self.check_case(cx, "type parameter", gen.ident, gen.span);
1125         }
1126     }
1127 }
1128
1129 #[derive(PartialEq)]
1130 enum MethodContext {
1131     TraitDefaultImpl,
1132     TraitImpl,
1133     PlainImpl
1134 }
1135
1136 fn method_context(cx: &Context, id: ast::NodeId, span: Span) -> MethodContext {
1137     match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
1138         None => cx.sess().span_bug(span, "missing method descriptor?!"),
1139         Some(item) => match item.container() {
1140             ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
1141             ty::ImplContainer(cid) => {
1142                 match cx.tcx.impl_trait_ref(cid) {
1143                     Some(_) => MethodContext::TraitImpl,
1144                     None => MethodContext::PlainImpl
1145                 }
1146             }
1147         }
1148     }
1149 }
1150
1151 declare_lint! {
1152     pub NON_SNAKE_CASE,
1153     Warn,
1154     "methods, functions, lifetime parameters and modules should have snake case names"
1155 }
1156
1157 #[derive(Copy, Clone)]
1158 pub struct NonSnakeCase;
1159
1160 impl NonSnakeCase {
1161     fn to_snake_case(mut str: &str) -> String {
1162         let mut words = vec![];
1163         // Preserve leading underscores
1164         str = str.trim_left_matches(|c: char| {
1165             if c == '_' {
1166                 words.push(String::new());
1167                 true
1168             } else {
1169                 false
1170             }
1171         });
1172         for s in str.split('_') {
1173             let mut last_upper = false;
1174             let mut buf = String::new();
1175             if s.is_empty() {
1176                 continue;
1177             }
1178             for ch in s.chars() {
1179                 if !buf.is_empty() && buf != "'"
1180                                    && ch.is_uppercase()
1181                                    && !last_upper {
1182                     words.push(buf);
1183                     buf = String::new();
1184                 }
1185                 last_upper = ch.is_uppercase();
1186                 buf.extend(ch.to_lowercase());
1187             }
1188             words.push(buf);
1189         }
1190         words.join("_")
1191     }
1192
1193     fn check_snake_case(&self, cx: &Context, sort: &str, name: &str, span: Option<Span>) {
1194         fn is_snake_case(ident: &str) -> bool {
1195             if ident.is_empty() {
1196                 return true;
1197             }
1198             let ident = ident.trim_left_matches('\'');
1199             let ident = ident.trim_matches('_');
1200
1201             let mut allow_underscore = true;
1202             ident.chars().all(|c| {
1203                 allow_underscore = match c {
1204                     '_' if !allow_underscore => return false,
1205                     '_' => false,
1206                     // It would be more obvious to use `c.is_lowercase()`,
1207                     // but some characters do not have a lowercase form
1208                     c if !c.is_uppercase() => true,
1209                     _ => return false,
1210                 };
1211                 true
1212             })
1213         }
1214
1215         if !is_snake_case(name) {
1216             let sc = NonSnakeCase::to_snake_case(name);
1217             let msg = if sc != name {
1218                 format!("{} `{}` should have a snake case name such as `{}`",
1219                         sort, name, sc)
1220             } else {
1221                 format!("{} `{}` should have a snake case name",
1222                         sort, name)
1223             };
1224             match span {
1225                 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
1226                 None => cx.lint(NON_SNAKE_CASE, &msg),
1227             }
1228         }
1229     }
1230 }
1231
1232 impl LintPass for NonSnakeCase {
1233     fn get_lints(&self) -> LintArray {
1234         lint_array!(NON_SNAKE_CASE)
1235     }
1236
1237     fn check_crate(&mut self, cx: &Context, cr: &hir::Crate) {
1238         let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
1239                                       .and_then(|at| at.value_str().map(|s| (at, s)));
1240         if let Some(ref name) = cx.tcx.sess.opts.crate_name {
1241             self.check_snake_case(cx, "crate", name, None);
1242         } else if let Some((attr, ref name)) = attr_crate_name {
1243             self.check_snake_case(cx, "crate", name, Some(attr.span));
1244         }
1245     }
1246
1247     fn check_fn(&mut self, cx: &Context,
1248                 fk: FnKind, _: &hir::FnDecl,
1249                 _: &hir::Block, span: Span, id: ast::NodeId) {
1250         match fk {
1251             FnKind::Method(ident, _, _) => match method_context(cx, id, span) {
1252                 MethodContext::PlainImpl => {
1253                     self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
1254                 },
1255                 MethodContext::TraitDefaultImpl => {
1256                     self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
1257                 },
1258                 _ => (),
1259             },
1260             FnKind::ItemFn(ident, _, _, _, _, _) => {
1261                 self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
1262             },
1263             _ => (),
1264         }
1265     }
1266
1267     fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1268         if let hir::ItemMod(_) = it.node {
1269             self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
1270         }
1271     }
1272
1273     fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1274         if let hir::MethodTraitItem(_, None) = trait_item.node {
1275             self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
1276                                   Some(trait_item.span));
1277         }
1278     }
1279
1280     fn check_lifetime_def(&mut self, cx: &Context, t: &hir::LifetimeDef) {
1281         self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
1282                               Some(t.lifetime.span));
1283     }
1284
1285     fn check_pat(&mut self, cx: &Context, p: &hir::Pat) {
1286         if let &hir::PatIdent(_, ref path1, _) = &p.node {
1287             let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
1288             if let Some(def::DefLocal(_)) = def {
1289                 self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
1290             }
1291         }
1292     }
1293
1294     fn check_struct_def(&mut self, cx: &Context, s: &hir::StructDef,
1295                         _: ast::Ident, _: &hir::Generics, _: ast::NodeId) {
1296         for sf in &s.fields {
1297             if let hir::StructField_ { kind: hir::NamedField(ident, _), .. } = sf.node {
1298                 self.check_snake_case(cx, "structure field", &ident.name.as_str(),
1299                                       Some(sf.span));
1300             }
1301         }
1302     }
1303 }
1304
1305 declare_lint! {
1306     pub NON_UPPER_CASE_GLOBALS,
1307     Warn,
1308     "static constants should have uppercase identifiers"
1309 }
1310
1311 #[derive(Copy, Clone)]
1312 pub struct NonUpperCaseGlobals;
1313
1314 impl NonUpperCaseGlobals {
1315     fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1316         let s = ident.name.as_str();
1317
1318         if s.chars().any(|c| c.is_lowercase()) {
1319             let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
1320             if uc != &s[..] {
1321                 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1322                     &format!("{} `{}` should have an upper case name such as `{}`",
1323                              sort, s, uc));
1324             } else {
1325                 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1326                     &format!("{} `{}` should have an upper case name",
1327                              sort, s));
1328             }
1329         }
1330     }
1331 }
1332
1333 impl LintPass for NonUpperCaseGlobals {
1334     fn get_lints(&self) -> LintArray {
1335         lint_array!(NON_UPPER_CASE_GLOBALS)
1336     }
1337
1338     fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1339         match it.node {
1340             // only check static constants
1341             hir::ItemStatic(_, hir::MutImmutable, _) => {
1342                 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1343             }
1344             hir::ItemConst(..) => {
1345                 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1346             }
1347             _ => {}
1348         }
1349     }
1350
1351     fn check_trait_item(&mut self, cx: &Context, ti: &hir::TraitItem) {
1352         match ti.node {
1353             hir::ConstTraitItem(..) => {
1354                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1355                                                       ti.ident, ti.span);
1356             }
1357             _ => {}
1358         }
1359     }
1360
1361     fn check_impl_item(&mut self, cx: &Context, ii: &hir::ImplItem) {
1362         match ii.node {
1363             hir::ConstImplItem(..) => {
1364                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1365                                                       ii.ident, ii.span);
1366             }
1367             _ => {}
1368         }
1369     }
1370
1371     fn check_pat(&mut self, cx: &Context, p: &hir::Pat) {
1372         // Lint for constants that look like binding identifiers (#7526)
1373         match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
1374             (&hir::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
1375                 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1376                                                       path1.node, p.span);
1377             }
1378             _ => {}
1379         }
1380     }
1381 }
1382
1383 declare_lint! {
1384     UNUSED_PARENS,
1385     Warn,
1386     "`if`, `match`, `while` and `return` do not need parentheses"
1387 }
1388
1389 #[derive(Copy, Clone)]
1390 pub struct UnusedParens;
1391
1392 impl UnusedParens {
1393     fn check_unused_parens_core(&self, cx: &Context, value: &hir::Expr, msg: &str,
1394                                 struct_lit_needs_parens: bool) {
1395         if let hir::ExprParen(ref inner) = value.node {
1396             let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1397             if !necessary {
1398                 cx.span_lint(UNUSED_PARENS, value.span,
1399                              &format!("unnecessary parentheses around {}", msg))
1400             }
1401         }
1402
1403         /// Expressions that syntactically contain an "exterior" struct
1404         /// literal i.e. not surrounded by any parens or other
1405         /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1406         /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1407         /// y: 1 }) == foo` does not.
1408         fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
1409             match value.node {
1410                 hir::ExprStruct(..) => true,
1411
1412                 hir::ExprAssign(ref lhs, ref rhs) |
1413                 hir::ExprAssignOp(_, ref lhs, ref rhs) |
1414                 hir::ExprBinary(_, ref lhs, ref rhs) => {
1415                     // X { y: 1 } + X { y: 2 }
1416                     contains_exterior_struct_lit(&**lhs) ||
1417                         contains_exterior_struct_lit(&**rhs)
1418                 }
1419                 hir::ExprUnary(_, ref x) |
1420                 hir::ExprCast(ref x, _) |
1421                 hir::ExprField(ref x, _) |
1422                 hir::ExprTupField(ref x, _) |
1423                 hir::ExprIndex(ref x, _) => {
1424                     // &X { y: 1 }, X { y: 1 }.y
1425                     contains_exterior_struct_lit(&**x)
1426                 }
1427
1428                 hir::ExprMethodCall(_, _, ref exprs) => {
1429                     // X { y: 1 }.bar(...)
1430                     contains_exterior_struct_lit(&*exprs[0])
1431                 }
1432
1433                 _ => false
1434             }
1435         }
1436     }
1437 }
1438
1439 impl LintPass for UnusedParens {
1440     fn get_lints(&self) -> LintArray {
1441         lint_array!(UNUSED_PARENS)
1442     }
1443
1444     fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1445         let (value, msg, struct_lit_needs_parens) = match e.node {
1446             hir::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1447             hir::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1448             hir::ExprMatch(ref head, _, source) => match source {
1449                 hir::MatchSource::Normal => (head, "`match` head expression", true),
1450                 hir::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1451                 hir::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1452                 hir::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1453             },
1454             hir::ExprRet(Some(ref value)) => (value, "`return` value", false),
1455             hir::ExprAssign(_, ref value) => (value, "assigned value", false),
1456             hir::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1457             _ => return
1458         };
1459         self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1460     }
1461
1462     fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
1463         let (value, msg) = match s.node {
1464             hir::StmtDecl(ref decl, _) => match decl.node {
1465                 hir::DeclLocal(ref local) => match local.init {
1466                     Some(ref value) => (value, "assigned value"),
1467                     None => return
1468                 },
1469                 _ => return
1470             },
1471             _ => return
1472         };
1473         self.check_unused_parens_core(cx, &**value, msg, false);
1474     }
1475 }
1476
1477 declare_lint! {
1478     UNUSED_IMPORT_BRACES,
1479     Allow,
1480     "unnecessary braces around an imported item"
1481 }
1482
1483 #[derive(Copy, Clone)]
1484 pub struct UnusedImportBraces;
1485
1486 impl LintPass for UnusedImportBraces {
1487     fn get_lints(&self) -> LintArray {
1488         lint_array!(UNUSED_IMPORT_BRACES)
1489     }
1490
1491     fn check_item(&mut self, cx: &Context, item: &hir::Item) {
1492         if let hir::ItemUse(ref view_path) = item.node {
1493             if let hir::ViewPathList(_, ref items) = view_path.node {
1494                 if items.len() == 1 {
1495                     if let hir::PathListIdent {ref name, ..} = items[0].node {
1496                         let m = format!("braces around {} is unnecessary",
1497                                         name);
1498                         cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1499                                      &m[..]);
1500                     }
1501                 }
1502             }
1503         }
1504     }
1505 }
1506
1507 declare_lint! {
1508     NON_SHORTHAND_FIELD_PATTERNS,
1509     Warn,
1510     "using `Struct { x: x }` instead of `Struct { x }`"
1511 }
1512
1513 #[derive(Copy, Clone)]
1514 pub struct NonShorthandFieldPatterns;
1515
1516 impl LintPass for NonShorthandFieldPatterns {
1517     fn get_lints(&self) -> LintArray {
1518         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1519     }
1520
1521     fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) {
1522         let def_map = cx.tcx.def_map.borrow();
1523         if let hir::PatStruct(_, ref v, _) = pat.node {
1524             let field_pats = v.iter().filter(|fieldpat| {
1525                 if fieldpat.node.is_shorthand {
1526                     return false;
1527                 }
1528                 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
1529                 def == Some(def::DefLocal(fieldpat.node.pat.id))
1530             });
1531             for fieldpat in field_pats {
1532                 if let hir::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1533                     if ident.node.name == fieldpat.node.ident.name {
1534                         // FIXME: should this comparison really be done on the name?
1535                         // doing it on the ident will fail during compilation of libcore
1536                         cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1537                                      &format!("the `{}:` in this pattern is redundant and can \
1538                                               be removed", ident.node))
1539                     }
1540                 }
1541             }
1542         }
1543     }
1544 }
1545
1546 declare_lint! {
1547     pub UNUSED_UNSAFE,
1548     Warn,
1549     "unnecessary use of an `unsafe` block"
1550 }
1551
1552 #[derive(Copy, Clone)]
1553 pub struct UnusedUnsafe;
1554
1555 impl LintPass for UnusedUnsafe {
1556     fn get_lints(&self) -> LintArray {
1557         lint_array!(UNUSED_UNSAFE)
1558     }
1559
1560     fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1561         if let hir::ExprBlock(ref blk) = e.node {
1562             // Don't warn about generated blocks, that'll just pollute the output.
1563             if blk.rules == hir::UnsafeBlock(hir::UserProvided) &&
1564                 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1565                     cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1566             }
1567         }
1568     }
1569 }
1570
1571 declare_lint! {
1572     UNSAFE_CODE,
1573     Allow,
1574     "usage of `unsafe` code"
1575 }
1576
1577 #[derive(Copy, Clone)]
1578 pub struct UnsafeCode;
1579
1580 impl LintPass for UnsafeCode {
1581     fn get_lints(&self) -> LintArray {
1582         lint_array!(UNSAFE_CODE)
1583     }
1584
1585     fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1586         if let hir::ExprBlock(ref blk) = e.node {
1587             // Don't warn about generated blocks, that'll just pollute the output.
1588             if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
1589                 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
1590             }
1591         }
1592     }
1593
1594     fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1595         match it.node {
1596             hir::ItemTrait(hir::Unsafety::Unsafe, _, _, _) =>
1597                 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
1598
1599             hir::ItemImpl(hir::Unsafety::Unsafe, _, _, _, _, _) =>
1600                 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
1601
1602             _ => return,
1603         }
1604     }
1605
1606     fn check_fn(&mut self, cx: &Context, fk: FnKind, _: &hir::FnDecl,
1607                 _: &hir::Block, span: Span, _: ast::NodeId) {
1608         match fk {
1609             FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, _, _, _) =>
1610                 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
1611
1612             FnKind::Method(_, sig, _) => {
1613                 if sig.unsafety == hir::Unsafety::Unsafe {
1614                     cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
1615                 }
1616             },
1617
1618             _ => (),
1619         }
1620     }
1621
1622     fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1623         if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
1624             if sig.unsafety == hir::Unsafety::Unsafe {
1625                 cx.span_lint(UNSAFE_CODE, trait_item.span,
1626                              "declaration of an `unsafe` method")
1627             }
1628         }
1629     }
1630 }
1631
1632 declare_lint! {
1633     pub UNUSED_MUT,
1634     Warn,
1635     "detect mut variables which don't need to be mutable"
1636 }
1637
1638 #[derive(Copy, Clone)]
1639 pub struct UnusedMut;
1640
1641 impl UnusedMut {
1642     fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<hir::Pat>]) {
1643         // collect all mutable pattern and group their NodeIDs by their Identifier to
1644         // avoid false warnings in match arms with multiple patterns
1645
1646         let mut mutables = FnvHashMap();
1647         for p in pats {
1648             pat_util::pat_bindings(&cx.tcx.def_map, p, |mode, id, _, path1| {
1649                 let ident = path1.node;
1650                 if let hir::BindByValue(hir::MutMutable) = mode {
1651                     if !ident.name.as_str().starts_with("_") {
1652                         match mutables.entry(ident.name.usize()) {
1653                             Vacant(entry) => { entry.insert(vec![id]); },
1654                             Occupied(mut entry) => { entry.get_mut().push(id); },
1655                         }
1656                     }
1657                 }
1658             });
1659         }
1660
1661         let used_mutables = cx.tcx.used_mut_nodes.borrow();
1662         for (_, v) in &mutables {
1663             if !v.iter().any(|e| used_mutables.contains(e)) {
1664                 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1665                              "variable does not need to be mutable");
1666             }
1667         }
1668     }
1669 }
1670
1671 impl LintPass for UnusedMut {
1672     fn get_lints(&self) -> LintArray {
1673         lint_array!(UNUSED_MUT)
1674     }
1675
1676     fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1677         if let hir::ExprMatch(_, ref arms, _) = e.node {
1678             for a in arms {
1679                 self.check_unused_mut_pat(cx, &a.pats)
1680             }
1681         }
1682     }
1683
1684     fn check_stmt(&mut self, cx: &Context, s: &hir::Stmt) {
1685         if let hir::StmtDecl(ref d, _) = s.node {
1686             if let hir::DeclLocal(ref l) = d.node {
1687                 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1688             }
1689         }
1690     }
1691
1692     fn check_fn(&mut self, cx: &Context,
1693                 _: FnKind, decl: &hir::FnDecl,
1694                 _: &hir::Block, _: Span, _: ast::NodeId) {
1695         for a in &decl.inputs {
1696             self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1697         }
1698     }
1699 }
1700
1701 declare_lint! {
1702     UNUSED_ALLOCATION,
1703     Warn,
1704     "detects unnecessary allocations that can be eliminated"
1705 }
1706
1707 #[derive(Copy, Clone)]
1708 pub struct UnusedAllocation;
1709
1710 impl LintPass for UnusedAllocation {
1711     fn get_lints(&self) -> LintArray {
1712         lint_array!(UNUSED_ALLOCATION)
1713     }
1714
1715     fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
1716         match e.node {
1717             hir::ExprUnary(hir::UnUniq, _) => (),
1718             _ => return
1719         }
1720
1721         if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
1722             if let adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
1723                 ref autoref, ..
1724             }) = *adjustment {
1725                 match autoref {
1726                     &Some(adjustment::AutoPtr(_, hir::MutImmutable)) => {
1727                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1728                                      "unnecessary allocation, use & instead");
1729                     }
1730                     &Some(adjustment::AutoPtr(_, hir::MutMutable)) => {
1731                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1732                                      "unnecessary allocation, use &mut instead");
1733                     }
1734                     _ => ()
1735                 }
1736             }
1737         }
1738     }
1739 }
1740
1741 declare_lint! {
1742     MISSING_DOCS,
1743     Allow,
1744     "detects missing documentation for public members"
1745 }
1746
1747 pub struct MissingDoc {
1748     /// Stack of IDs of struct definitions.
1749     struct_def_stack: Vec<ast::NodeId>,
1750
1751     /// True if inside variant definition
1752     in_variant: bool,
1753
1754     /// Stack of whether #[doc(hidden)] is set
1755     /// at each level which has lint attributes.
1756     doc_hidden_stack: Vec<bool>,
1757
1758     /// Private traits or trait items that leaked through. Don't check their methods.
1759     private_traits: HashSet<ast::NodeId>,
1760 }
1761
1762 impl MissingDoc {
1763     pub fn new() -> MissingDoc {
1764         MissingDoc {
1765             struct_def_stack: vec!(),
1766             in_variant: false,
1767             doc_hidden_stack: vec!(false),
1768             private_traits: HashSet::new(),
1769         }
1770     }
1771
1772     fn doc_hidden(&self) -> bool {
1773         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1774     }
1775
1776     fn check_missing_docs_attrs(&self,
1777                                cx: &Context,
1778                                id: Option<ast::NodeId>,
1779                                attrs: &[ast::Attribute],
1780                                sp: Span,
1781                                desc: &'static str) {
1782         // If we're building a test harness, then warning about
1783         // documentation is probably not really relevant right now.
1784         if cx.sess().opts.test {
1785             return;
1786         }
1787
1788         // `#[doc(hidden)]` disables missing_docs check.
1789         if self.doc_hidden() {
1790             return;
1791         }
1792
1793         // Only check publicly-visible items, using the result from the privacy pass.
1794         // It's an option so the crate root can also use this function (it doesn't
1795         // have a NodeId).
1796         if let Some(ref id) = id {
1797             if !cx.exported_items.contains(id) {
1798                 return;
1799             }
1800         }
1801
1802         let has_doc = attrs.iter().any(|a| {
1803             match a.node.value.node {
1804                 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1805                 _ => false
1806             }
1807         });
1808         if !has_doc {
1809             cx.span_lint(MISSING_DOCS, sp,
1810                          &format!("missing documentation for {}", desc));
1811         }
1812     }
1813 }
1814
1815 impl LintPass for MissingDoc {
1816     fn get_lints(&self) -> LintArray {
1817         lint_array!(MISSING_DOCS)
1818     }
1819
1820     fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1821         let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1822             attr.check_name("doc") && match attr.meta_item_list() {
1823                 None => false,
1824                 Some(l) => attr::contains_name(&l[..], "hidden"),
1825             }
1826         });
1827         self.doc_hidden_stack.push(doc_hidden);
1828     }
1829
1830     fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1831         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1832     }
1833
1834     fn check_struct_def(&mut self, _: &Context, _: &hir::StructDef,
1835                         _: ast::Ident, _: &hir::Generics, id: ast::NodeId) {
1836         self.struct_def_stack.push(id);
1837     }
1838
1839     fn check_struct_def_post(&mut self, _: &Context, _: &hir::StructDef,
1840                              _: ast::Ident, _: &hir::Generics, id: ast::NodeId) {
1841         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1842         assert!(popped == id);
1843     }
1844
1845     fn check_crate(&mut self, cx: &Context, krate: &hir::Crate) {
1846         self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
1847     }
1848
1849     fn check_item(&mut self, cx: &Context, it: &hir::Item) {
1850         let desc = match it.node {
1851             hir::ItemFn(..) => "a function",
1852             hir::ItemMod(..) => "a module",
1853             hir::ItemEnum(..) => "an enum",
1854             hir::ItemStruct(..) => "a struct",
1855             hir::ItemTrait(_, _, _, ref items) => {
1856                 // Issue #11592, traits are always considered exported, even when private.
1857                 if it.vis == hir::Visibility::Inherited {
1858                     self.private_traits.insert(it.id);
1859                     for itm in items {
1860                         self.private_traits.insert(itm.id);
1861                     }
1862                     return
1863                 }
1864                 "a trait"
1865             },
1866             hir::ItemTy(..) => "a type alias",
1867             hir::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
1868                 // If the trait is private, add the impl items to private_traits so they don't get
1869                 // reported for missing docs.
1870                 let real_trait = cx.tcx.trait_ref_to_def_id(trait_ref);
1871                 match cx.tcx.map.find(real_trait.node) {
1872                     Some(hir_map::NodeItem(item)) => if item.vis == hir::Visibility::Inherited {
1873                         for itm in impl_items {
1874                             self.private_traits.insert(itm.id);
1875                         }
1876                     },
1877                     _ => { }
1878                 }
1879                 return
1880             },
1881             hir::ItemConst(..) => "a constant",
1882             hir::ItemStatic(..) => "a static",
1883             _ => return
1884         };
1885
1886         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
1887     }
1888
1889     fn check_trait_item(&mut self, cx: &Context, trait_item: &hir::TraitItem) {
1890         if self.private_traits.contains(&trait_item.id) { return }
1891
1892         let desc = match trait_item.node {
1893             hir::ConstTraitItem(..) => "an associated constant",
1894             hir::MethodTraitItem(..) => "a trait method",
1895             hir::TypeTraitItem(..) => "an associated type",
1896         };
1897
1898         self.check_missing_docs_attrs(cx, Some(trait_item.id),
1899                                       &trait_item.attrs,
1900                                       trait_item.span, desc);
1901     }
1902
1903     fn check_impl_item(&mut self, cx: &Context, impl_item: &hir::ImplItem) {
1904         // If the method is an impl for a trait, don't doc.
1905         if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl {
1906             return;
1907         }
1908
1909         let desc = match impl_item.node {
1910             hir::ConstImplItem(..) => "an associated constant",
1911             hir::MethodImplItem(..) => "a method",
1912             hir::TypeImplItem(_) => "an associated type",
1913         };
1914         self.check_missing_docs_attrs(cx, Some(impl_item.id),
1915                                       &impl_item.attrs,
1916                                       impl_item.span, desc);
1917     }
1918
1919     fn check_struct_field(&mut self, cx: &Context, sf: &hir::StructField) {
1920         if let hir::NamedField(_, vis) = sf.node.kind {
1921             if vis == hir::Public || self.in_variant {
1922                 let cur_struct_def = *self.struct_def_stack.last()
1923                     .expect("empty struct_def_stack");
1924                 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1925                                               &sf.node.attrs, sf.span,
1926                                               "a struct field")
1927             }
1928         }
1929     }
1930
1931     fn check_variant(&mut self, cx: &Context, v: &hir::Variant, _: &hir::Generics) {
1932         self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
1933         assert!(!self.in_variant);
1934         self.in_variant = true;
1935     }
1936
1937     fn check_variant_post(&mut self, _: &Context, _: &hir::Variant, _: &hir::Generics) {
1938         assert!(self.in_variant);
1939         self.in_variant = false;
1940     }
1941 }
1942
1943 declare_lint! {
1944     pub MISSING_COPY_IMPLEMENTATIONS,
1945     Allow,
1946     "detects potentially-forgotten implementations of `Copy`"
1947 }
1948
1949 #[derive(Copy, Clone)]
1950 pub struct MissingCopyImplementations;
1951
1952 impl LintPass for MissingCopyImplementations {
1953     fn get_lints(&self) -> LintArray {
1954         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1955     }
1956
1957     fn check_item(&mut self, cx: &Context, item: &hir::Item) {
1958         if !cx.exported_items.contains(&item.id) {
1959             return;
1960         }
1961         let (def, ty) = match item.node {
1962             hir::ItemStruct(_, ref ast_generics) => {
1963                 if ast_generics.is_parameterized() {
1964                     return;
1965                 }
1966                 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1967                 (def, cx.tcx.mk_struct(def,
1968                                        cx.tcx.mk_substs(Substs::empty())))
1969             }
1970             hir::ItemEnum(_, ref ast_generics) => {
1971                 if ast_generics.is_parameterized() {
1972                     return;
1973                 }
1974                 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1975                 (def, cx.tcx.mk_enum(def,
1976                                      cx.tcx.mk_substs(Substs::empty())))
1977             }
1978             _ => return,
1979         };
1980         if def.has_dtor() { return; }
1981         let parameter_environment = cx.tcx.empty_parameter_environment();
1982         // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
1983         // method
1984         if !ty.moves_by_default(&parameter_environment, item.span) {
1985             return;
1986         }
1987         if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
1988             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1989                          item.span,
1990                          "type could implement `Copy`; consider adding `impl \
1991                           Copy`")
1992         }
1993     }
1994 }
1995
1996 declare_lint! {
1997     MISSING_DEBUG_IMPLEMENTATIONS,
1998     Allow,
1999     "detects missing implementations of fmt::Debug"
2000 }
2001
2002 pub struct MissingDebugImplementations {
2003     impling_types: Option<NodeSet>,
2004 }
2005
2006 impl MissingDebugImplementations {
2007     pub fn new() -> MissingDebugImplementations {
2008         MissingDebugImplementations {
2009             impling_types: None,
2010         }
2011     }
2012 }
2013
2014 impl LintPass for MissingDebugImplementations {
2015     fn get_lints(&self) -> LintArray {
2016         lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
2017     }
2018
2019     fn check_item(&mut self, cx: &Context, item: &hir::Item) {
2020         if !cx.exported_items.contains(&item.id) {
2021             return;
2022         }
2023
2024         match item.node {
2025             hir::ItemStruct(..) | hir::ItemEnum(..) => {},
2026             _ => return,
2027         }
2028
2029         let debug = match cx.tcx.lang_items.debug_trait() {
2030             Some(debug) => debug,
2031             None => return,
2032         };
2033
2034         if self.impling_types.is_none() {
2035             let debug_def = cx.tcx.lookup_trait_def(debug);
2036             let mut impls = NodeSet();
2037             debug_def.for_each_impl(cx.tcx, |d| {
2038                 if d.is_local() {
2039                     if let Some(ty_def) = cx.tcx.node_id_to_type(d.node).ty_to_def_id() {
2040                         impls.insert(ty_def.node);
2041                     }
2042                 }
2043             });
2044
2045             self.impling_types = Some(impls);
2046             debug!("{:?}", self.impling_types);
2047         }
2048
2049         if !self.impling_types.as_ref().unwrap().contains(&item.id) {
2050             cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
2051                          item.span,
2052                          "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
2053                           or a manual implementation")
2054         }
2055     }
2056 }
2057
2058 declare_lint! {
2059     DEPRECATED,
2060     Warn,
2061     "detects use of #[deprecated] items"
2062 }
2063
2064 /// Checks for use of items with `#[deprecated]` attributes
2065 #[derive(Copy, Clone)]
2066 pub struct Stability;
2067
2068 impl Stability {
2069     fn lint(&self, cx: &Context, _id: DefId,
2070             span: Span, stability: &Option<&attr::Stability>) {
2071         // Deprecated attributes apply in-crate and cross-crate.
2072         let (lint, label) = match *stability {
2073             Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
2074                 (DEPRECATED, "deprecated"),
2075             _ => return
2076         };
2077
2078         output(cx, span, stability, lint, label);
2079
2080         fn output(cx: &Context, span: Span, stability: &Option<&attr::Stability>,
2081                   lint: &'static Lint, label: &'static str) {
2082             let msg = match *stability {
2083                 Some(&attr::Stability { reason: Some(ref s), .. }) => {
2084                     format!("use of {} item: {}", label, *s)
2085                 }
2086                 _ => format!("use of {} item", label)
2087             };
2088
2089             cx.span_lint(lint, span, &msg[..]);
2090         }
2091     }
2092 }
2093
2094 fn hir_to_ast_stability(stab: &attr::Stability) -> attr::Stability {
2095     attr::Stability {
2096         level: match stab.level {
2097             attr::Unstable => attr::Unstable,
2098             attr::Stable => attr::Stable,
2099         },
2100         feature: stab.feature.clone(),
2101         since: stab.since.clone(),
2102         deprecated_since: stab.deprecated_since.clone(),
2103         reason: stab.reason.clone(),
2104         issue: stab.issue,
2105     }
2106 }
2107
2108 impl LintPass for Stability {
2109     fn get_lints(&self) -> LintArray {
2110         lint_array!(DEPRECATED)
2111     }
2112
2113     fn check_item(&mut self, cx: &Context, item: &hir::Item) {
2114         stability::check_item(cx.tcx, item, false,
2115                               &mut |id, sp, stab|
2116                                 self.lint(cx, id, sp,
2117                                           &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2118     }
2119
2120     fn check_expr(&mut self, cx: &Context, e: &hir::Expr) {
2121         stability::check_expr(cx.tcx, e,
2122                               &mut |id, sp, stab|
2123                                 self.lint(cx, id, sp,
2124                                           &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2125     }
2126
2127     fn check_path(&mut self, cx: &Context, path: &hir::Path, id: ast::NodeId) {
2128         stability::check_path(cx.tcx, path, id,
2129                               &mut |id, sp, stab|
2130                                 self.lint(cx, id, sp,
2131                                           &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2132     }
2133
2134     fn check_pat(&mut self, cx: &Context, pat: &hir::Pat) {
2135         stability::check_pat(cx.tcx, pat,
2136                              &mut |id, sp, stab|
2137                                 self.lint(cx, id, sp,
2138                                           &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
2139     }
2140 }
2141
2142 declare_lint! {
2143     pub UNCONDITIONAL_RECURSION,
2144     Warn,
2145     "functions that cannot return without calling themselves"
2146 }
2147
2148 #[derive(Copy, Clone)]
2149 pub struct UnconditionalRecursion;
2150
2151
2152 impl LintPass for UnconditionalRecursion {
2153     fn get_lints(&self) -> LintArray {
2154         lint_array![UNCONDITIONAL_RECURSION]
2155     }
2156
2157     fn check_fn(&mut self, cx: &Context, fn_kind: FnKind, _: &hir::FnDecl,
2158                 blk: &hir::Block, sp: Span, id: ast::NodeId) {
2159         type F = for<'tcx> fn(&ty::ctxt<'tcx>,
2160                               ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
2161
2162         let method = match fn_kind {
2163             FnKind::ItemFn(..) => None,
2164             FnKind::Method(..) => {
2165                 cx.tcx.impl_or_trait_item(DefId::local(id)).as_opt_method()
2166             }
2167             // closures can't recur, so they don't matter.
2168             FnKind::Closure => return
2169         };
2170
2171         // Walk through this function (say `f`) looking to see if
2172         // every possible path references itself, i.e. the function is
2173         // called recursively unconditionally. This is done by trying
2174         // to find a path from the entry node to the exit node that
2175         // *doesn't* call `f` by traversing from the entry while
2176         // pretending that calls of `f` are sinks (i.e. ignoring any
2177         // exit edges from them).
2178         //
2179         // NB. this has an edge case with non-returning statements,
2180         // like `loop {}` or `panic!()`: control flow never reaches
2181         // the exit node through these, so one can have a function
2182         // that never actually calls itselfs but is still picked up by
2183         // this lint:
2184         //
2185         //     fn f(cond: bool) {
2186         //         if !cond { panic!() } // could come from `assert!(cond)`
2187         //         f(false)
2188         //     }
2189         //
2190         // In general, functions of that form may be able to call
2191         // itself a finite number of times and then diverge. The lint
2192         // considers this to be an error for two reasons, (a) it is
2193         // easier to implement, and (b) it seems rare to actually want
2194         // to have behaviour like the above, rather than
2195         // e.g. accidentally recurring after an assert.
2196
2197         let cfg = cfg::CFG::new(cx.tcx, blk);
2198
2199         let mut work_queue = vec![cfg.entry];
2200         let mut reached_exit_without_self_call = false;
2201         let mut self_call_spans = vec![];
2202         let mut visited = HashSet::new();
2203
2204         while let Some(idx) = work_queue.pop() {
2205             if idx == cfg.exit {
2206                 // found a path!
2207                 reached_exit_without_self_call = true;
2208                 break;
2209             }
2210
2211             let cfg_id = idx.node_id();
2212             if visited.contains(&cfg_id) {
2213                 // already done
2214                 continue;
2215             }
2216             visited.insert(cfg_id);
2217
2218             let node_id = cfg.graph.node_data(idx).id();
2219
2220             // is this a recursive call?
2221             let self_recursive = if node_id != ast::DUMMY_NODE_ID {
2222                 match method {
2223                     Some(ref method) => {
2224                         expr_refers_to_this_method(cx.tcx, method, node_id)
2225                     }
2226                     None => expr_refers_to_this_fn(cx.tcx, id, node_id)
2227                 }
2228             } else {
2229                 false
2230             };
2231             if self_recursive {
2232                 self_call_spans.push(cx.tcx.map.span(node_id));
2233                 // this is a self call, so we shouldn't explore past
2234                 // this node in the CFG.
2235                 continue;
2236             }
2237             // add the successors of this node to explore the graph further.
2238             for (_, edge) in cfg.graph.outgoing_edges(idx) {
2239                 let target_idx = edge.target();
2240                 let target_cfg_id = target_idx.node_id();
2241                 if !visited.contains(&target_cfg_id) {
2242                     work_queue.push(target_idx)
2243                 }
2244             }
2245         }
2246
2247         // Check the number of self calls because a function that
2248         // doesn't return (e.g. calls a `-> !` function or `loop { /*
2249         // no break */ }`) shouldn't be linted unless it actually
2250         // recurs.
2251         if !reached_exit_without_self_call && !self_call_spans.is_empty() {
2252             cx.span_lint(UNCONDITIONAL_RECURSION, sp,
2253                          "function cannot return without recurring");
2254
2255             // FIXME #19668: these could be span_lint_note's instead of this manual guard.
2256             if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
2257                 let sess = cx.sess();
2258                 // offer some help to the programmer.
2259                 for call in &self_call_spans {
2260                     sess.span_note(*call, "recursive call site")
2261                 }
2262                 sess.fileline_help(sp, "a `loop` may express intention \
2263                                         better if this is on purpose")
2264             }
2265         }
2266
2267         // all done
2268         return;
2269
2270         // Functions for identifying if the given Expr NodeId `id`
2271         // represents a call to the function `fn_id`/method `method`.
2272
2273         fn expr_refers_to_this_fn(tcx: &ty::ctxt,
2274                                   fn_id: ast::NodeId,
2275                                   id: ast::NodeId) -> bool {
2276             match tcx.map.get(id) {
2277                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2278                     tcx.def_map.borrow().get(&callee.id)
2279                         .map_or(false, |def| def.def_id() == DefId::local(fn_id))
2280                 }
2281                 _ => false
2282             }
2283         }
2284
2285         // Check if the expression `id` performs a call to `method`.
2286         fn expr_refers_to_this_method(tcx: &ty::ctxt,
2287                                       method: &ty::Method,
2288                                       id: ast::NodeId) -> bool {
2289             let tables = tcx.tables.borrow();
2290
2291             // Check for method calls and overloaded operators.
2292             if let Some(m) = tables.method_map.get(&ty::MethodCall::expr(id)) {
2293                 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2294                     return true;
2295                 }
2296             }
2297
2298             // Check for overloaded autoderef method calls.
2299             if let Some(&adjustment::AdjustDerefRef(ref adj)) = tables.adjustments.get(&id) {
2300                 for i in 0..adj.autoderefs {
2301                     let method_call = ty::MethodCall::autoderef(id, i as u32);
2302                     if let Some(m) = tables.method_map.get(&method_call) {
2303                         if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2304                             return true;
2305                         }
2306                     }
2307                 }
2308             }
2309
2310             // Check for calls to methods via explicit paths (e.g. `T::method()`).
2311             match tcx.map.get(id) {
2312                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
2313                     match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
2314                         Some(def::DefMethod(def_id)) => {
2315                             let no_substs = &ty::ItemSubsts::empty();
2316                             let ts = tables.item_substs.get(&callee.id).unwrap_or(no_substs);
2317                             method_call_refers_to_method(tcx, method, def_id, &ts.substs, id)
2318                         }
2319                         _ => false
2320                     }
2321                 }
2322                 _ => false
2323             }
2324         }
2325
2326         // Check if the method call to the method with the ID `callee_id`
2327         // and instantiated with `callee_substs` refers to method `method`.
2328         fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
2329                                               method: &ty::Method,
2330                                               callee_id: DefId,
2331                                               callee_substs: &Substs<'tcx>,
2332                                               expr_id: ast::NodeId) -> bool {
2333             let callee_item = tcx.impl_or_trait_item(callee_id);
2334
2335             match callee_item.container() {
2336                 // This is an inherent method, so the `def_id` refers
2337                 // directly to the method definition.
2338                 ty::ImplContainer(_) => {
2339                     callee_id == method.def_id
2340                 }
2341
2342                 // A trait method, from any number of possible sources.
2343                 // Attempt to select a concrete impl before checking.
2344                 ty::TraitContainer(trait_def_id) => {
2345                     let trait_substs = callee_substs.clone().method_to_trait();
2346                     let trait_substs = tcx.mk_substs(trait_substs);
2347                     let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
2348                     let trait_ref = ty::Binder(trait_ref);
2349                     let span = tcx.map.span(expr_id);
2350                     let obligation =
2351                         traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
2352                                                 trait_ref.to_poly_trait_predicate());
2353
2354                     let param_env = ty::ParameterEnvironment::for_item(tcx, method.def_id.node);
2355                     let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
2356                     let mut selcx = traits::SelectionContext::new(&infcx);
2357                     match selcx.select(&obligation) {
2358                         // The method comes from a `T: Trait` bound.
2359                         // If `T` is `Self`, then this call is inside
2360                         // a default method definition.
2361                         Ok(Some(traits::VtableParam(_))) => {
2362                             let self_ty = callee_substs.self_ty();
2363                             let on_self = self_ty.map_or(false, |t| t.is_self());
2364                             // We can only be recurring in a default
2365                             // method if we're being called literally
2366                             // on the `Self` type.
2367                             on_self && callee_id == method.def_id
2368                         }
2369
2370                         // The `impl` is known, so we check that with a
2371                         // special case:
2372                         Ok(Some(traits::VtableImpl(vtable_impl))) => {
2373                             let container = ty::ImplContainer(vtable_impl.impl_def_id);
2374                             // It matches if it comes from the same impl,
2375                             // and has the same method name.
2376                             container == method.container
2377                                 && callee_item.name() == method.name
2378                         }
2379
2380                         // There's no way to know if this call is
2381                         // recursive, so we assume it's not.
2382                         _ => return false
2383                     }
2384                 }
2385             }
2386         }
2387     }
2388 }
2389
2390 declare_lint! {
2391     PLUGIN_AS_LIBRARY,
2392     Warn,
2393     "compiler plugin used as ordinary library in non-plugin crate"
2394 }
2395
2396 #[derive(Copy, Clone)]
2397 pub struct PluginAsLibrary;
2398
2399 impl LintPass for PluginAsLibrary {
2400     fn get_lints(&self) -> LintArray {
2401         lint_array![PLUGIN_AS_LIBRARY]
2402     }
2403
2404     fn check_item(&mut self, cx: &Context, it: &hir::Item) {
2405         if cx.sess().plugin_registrar_fn.get().is_some() {
2406             // We're compiling a plugin; it's fine to link other plugins.
2407             return;
2408         }
2409
2410         match it.node {
2411             hir::ItemExternCrate(..) => (),
2412             _ => return,
2413         };
2414
2415         let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
2416             Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
2417             None => {
2418                 // Probably means we aren't linking the crate for some reason.
2419                 //
2420                 // Not sure if / when this could happen.
2421                 return;
2422             }
2423         };
2424
2425         if decoder::get_plugin_registrar_fn(md.data()).is_some() {
2426             cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
2427                          "compiler plugin used as an ordinary library");
2428         }
2429     }
2430 }
2431
2432 declare_lint! {
2433     PRIVATE_NO_MANGLE_FNS,
2434     Warn,
2435     "functions marked #[no_mangle] should be exported"
2436 }
2437
2438 declare_lint! {
2439     PRIVATE_NO_MANGLE_STATICS,
2440     Warn,
2441     "statics marked #[no_mangle] should be exported"
2442 }
2443
2444 declare_lint! {
2445     NO_MANGLE_CONST_ITEMS,
2446     Deny,
2447     "const items will not have their symbols exported"
2448 }
2449
2450 #[derive(Copy, Clone)]
2451 pub struct InvalidNoMangleItems;
2452
2453 impl LintPass for InvalidNoMangleItems {
2454     fn get_lints(&self) -> LintArray {
2455         lint_array!(PRIVATE_NO_MANGLE_FNS,
2456                     PRIVATE_NO_MANGLE_STATICS,
2457                     NO_MANGLE_CONST_ITEMS)
2458     }
2459
2460     fn check_item(&mut self, cx: &Context, it: &hir::Item) {
2461         match it.node {
2462             hir::ItemFn(..) => {
2463                 if attr::contains_name(&it.attrs, "no_mangle") &&
2464                        !cx.exported_items.contains(&it.id) {
2465                     let msg = format!("function {} is marked #[no_mangle], but not exported",
2466                                       it.ident);
2467                     cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
2468                 }
2469             },
2470             hir::ItemStatic(..) => {
2471                 if attr::contains_name(&it.attrs, "no_mangle") &&
2472                        !cx.exported_items.contains(&it.id) {
2473                     let msg = format!("static {} is marked #[no_mangle], but not exported",
2474                                       it.ident);
2475                     cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
2476                 }
2477             },
2478             hir::ItemConst(..) => {
2479                 if attr::contains_name(&it.attrs, "no_mangle") {
2480                     // Const items do not refer to a particular location in memory, and therefore
2481                     // don't have anything to attach a symbol to
2482                     let msg = "const items should never be #[no_mangle], consider instead using \
2483                                `pub static`";
2484                     cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
2485                 }
2486             }
2487             _ => {},
2488         }
2489     }
2490 }
2491
2492 #[derive(Clone, Copy)]
2493 pub struct MutableTransmutes;
2494
2495 declare_lint! {
2496     MUTABLE_TRANSMUTES,
2497     Deny,
2498     "mutating transmuted &mut T from &T may cause undefined behavior"
2499 }
2500
2501 impl LintPass for MutableTransmutes {
2502     fn get_lints(&self) -> LintArray {
2503         lint_array!(MUTABLE_TRANSMUTES)
2504     }
2505
2506     fn check_expr(&mut self, cx: &Context, expr: &hir::Expr) {
2507         use syntax::abi::RustIntrinsic;
2508
2509         let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
2510                    consider instead using an UnsafeCell";
2511         match get_transmute_from_to(cx, expr) {
2512             Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
2513                 if to_mt.mutbl == hir::Mutability::MutMutable
2514                     && from_mt.mutbl == hir::Mutability::MutImmutable {
2515                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
2516                 }
2517             }
2518             _ => ()
2519         }
2520
2521         fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &hir::Expr)
2522             -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
2523             match expr.node {
2524                 hir::ExprPath(..) => (),
2525                 _ => return None
2526             }
2527             if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
2528                 if !def_id_is_transmute(cx, did) {
2529                     return None;
2530                 }
2531                 let typ = cx.tcx.node_id_to_type(expr.id);
2532                 match typ.sty {
2533                     ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
2534                         if let ty::FnConverging(to) = bare_fn.sig.0.output {
2535                             let from = bare_fn.sig.0.inputs[0];
2536                             return Some((&from.sty, &to.sty));
2537                         }
2538                     },
2539                     _ => ()
2540                 }
2541             }
2542             None
2543         }
2544
2545         fn def_id_is_transmute(cx: &Context, def_id: DefId) -> bool {
2546             match cx.tcx.lookup_item_type(def_id).ty.sty {
2547                 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
2548                 _ => return false
2549             }
2550             cx.tcx.with_path(def_id, |path| match path.last() {
2551                 Some(ref last) => last.name().as_str() == "transmute",
2552                 _ => false
2553             })
2554         }
2555     }
2556 }
2557
2558 /// Forbids using the `#[feature(...)]` attribute
2559 #[derive(Copy, Clone)]
2560 pub struct UnstableFeatures;
2561
2562 declare_lint! {
2563     UNSTABLE_FEATURES,
2564     Allow,
2565     "enabling unstable features (deprecated. do not use)"
2566 }
2567
2568 impl LintPass for UnstableFeatures {
2569     fn get_lints(&self) -> LintArray {
2570         lint_array!(UNSTABLE_FEATURES)
2571     }
2572     fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
2573         if attr::contains_name(&[attr.node.value.clone()], "feature") {
2574             if let Some(items) = attr.node.value.meta_item_list() {
2575                 for item in items {
2576                     ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
2577                 }
2578             }
2579         }
2580     }
2581 }
2582
2583 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
2584 /// attribute (see issue #24585).
2585 #[derive(Copy, Clone)]
2586 pub struct DropWithReprExtern;
2587
2588 declare_lint! {
2589     DROP_WITH_REPR_EXTERN,
2590     Warn,
2591     "use of #[repr(C)] on a type that implements Drop"
2592 }
2593
2594 impl LintPass for DropWithReprExtern {
2595     fn get_lints(&self) -> LintArray {
2596         lint_array!(DROP_WITH_REPR_EXTERN)
2597     }
2598     fn check_crate(&mut self, ctx: &Context, _: &hir::Crate) {
2599         for dtor_did in ctx.tcx.destructors.borrow().iter() {
2600             let (drop_impl_did, dtor_self_type) =
2601                 if dtor_did.is_local() {
2602                     let impl_did = ctx.tcx.map.get_parent_did(dtor_did.node);
2603                     let ty = ctx.tcx.lookup_item_type(impl_did).ty;
2604                     (impl_did, ty)
2605                 } else {
2606                     continue;
2607                 };
2608
2609             match dtor_self_type.sty {
2610                 ty::TyEnum(self_type_def, _) |
2611                 ty::TyStruct(self_type_def, _) => {
2612                     let self_type_did = self_type_def.did;
2613                     let hints = ctx.tcx.lookup_repr_hints(self_type_did);
2614                     if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
2615                         self_type_def.dtor_kind().has_drop_flag() {
2616                         let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
2617                                                                      codemap::DUMMY_SP);
2618                         let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
2619                                                                      codemap::DUMMY_SP);
2620                         ctx.span_lint(DROP_WITH_REPR_EXTERN,
2621                                       drop_impl_span,
2622                                       "implementing Drop adds hidden state to types, \
2623                                        possibly conflicting with `#[repr(C)]`");
2624                         // FIXME #19668: could be span_lint_note instead of manual guard.
2625                         if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
2626                             ctx.sess().span_note(self_defn_span,
2627                                                "the `#[repr(C)]` attribute is attached here");
2628                         }
2629                     }
2630                 }
2631                 _ => {}
2632             }
2633         }
2634     }
2635 }