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