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