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