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