]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
Auto merge of #28009 - GuillaumeGomez:patch-1, r=Manishearth
[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, FnKind, 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 if attr.check_name(name) => {
893                     break;
894                 },
895                 _ => ()
896             }
897         }
898
899         let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
900         for &(ref name, ty) in plugin_attributes.iter() {
901             if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
902                 break;
903             }
904         }
905
906         if !attr::is_used(attr) {
907             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
908             // Is it a builtin attribute that must be used at the crate level?
909             let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
910                 attr.name() == name &&
911                 ty == AttributeType::CrateLevel
912             }).is_some();
913
914             // Has a plugin registered this attribute as one which must be used at
915             // the crate level?
916             let plugin_crate = plugin_attributes.iter()
917                                                 .find(|&&(ref x, t)| {
918                                                         &*attr.name() == &*x &&
919                                                         AttributeType::CrateLevel == t
920                                                     }).is_some();
921             if  known_crate || plugin_crate {
922                 let msg = match attr.node.style {
923                     ast::AttrOuter => "crate-level attribute should be an inner \
924                                        attribute: add an exclamation mark: #![foo]",
925                     ast::AttrInner => "crate-level attribute should be in the \
926                                        root module",
927                 };
928                 cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
929             }
930         }
931     }
932 }
933
934 declare_lint! {
935     pub PATH_STATEMENTS,
936     Warn,
937     "path statements with no effect"
938 }
939
940 #[derive(Copy, Clone)]
941 pub struct PathStatements;
942
943 impl LintPass for PathStatements {
944     fn get_lints(&self) -> LintArray {
945         lint_array!(PATH_STATEMENTS)
946     }
947
948     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
949         match s.node {
950             ast::StmtSemi(ref expr, _) => {
951                 match expr.node {
952                     ast::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
953                                                       "path statement with no effect"),
954                     _ => ()
955                 }
956             }
957             _ => ()
958         }
959     }
960 }
961
962 declare_lint! {
963     pub UNUSED_MUST_USE,
964     Warn,
965     "unused result of a type flagged as #[must_use]"
966 }
967
968 declare_lint! {
969     pub UNUSED_RESULTS,
970     Allow,
971     "unused result of an expression in a statement"
972 }
973
974 #[derive(Copy, Clone)]
975 pub struct UnusedResults;
976
977 impl LintPass for UnusedResults {
978     fn get_lints(&self) -> LintArray {
979         lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
980     }
981
982     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
983         let expr = match s.node {
984             ast::StmtSemi(ref expr, _) => &**expr,
985             _ => return
986         };
987
988         if let ast::ExprRet(..) = expr.node {
989             return;
990         }
991
992         let t = cx.tcx.expr_ty(expr);
993         let warned = match t.sty {
994             ty::TyTuple(ref tys) if tys.is_empty() => return,
995             ty::TyBool => return,
996             ty::TyStruct(def, _) |
997             ty::TyEnum(def, _) => {
998                 if def.did.is_local() {
999                     if let ast_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
1000                         check_must_use(cx, &it.attrs, s.span)
1001                     } else {
1002                         false
1003                     }
1004                 } else {
1005                     let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
1006                     check_must_use(cx, &attrs[..], s.span)
1007                 }
1008             }
1009             _ => false,
1010         };
1011         if !warned {
1012             cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
1013         }
1014
1015         fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
1016             for attr in attrs {
1017                 if attr.check_name("must_use") {
1018                     let mut msg = "unused result which must be used".to_string();
1019                     // check for #[must_use="..."]
1020                     match attr.value_str() {
1021                         None => {}
1022                         Some(s) => {
1023                             msg.push_str(": ");
1024                             msg.push_str(&s);
1025                         }
1026                     }
1027                     cx.span_lint(UNUSED_MUST_USE, sp, &msg);
1028                     return true;
1029                 }
1030             }
1031             false
1032         }
1033     }
1034 }
1035
1036 declare_lint! {
1037     pub NON_CAMEL_CASE_TYPES,
1038     Warn,
1039     "types, variants, traits and type parameters should have camel case names"
1040 }
1041
1042 #[derive(Copy, Clone)]
1043 pub struct NonCamelCaseTypes;
1044
1045 impl NonCamelCaseTypes {
1046     fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1047         fn is_camel_case(ident: ast::Ident) -> bool {
1048             let ident = ident.name.as_str();
1049             if ident.is_empty() {
1050                 return true;
1051             }
1052             let ident = ident.trim_matches('_');
1053
1054             // start with a non-lowercase letter rather than non-uppercase
1055             // ones (some scripts don't have a concept of upper/lowercase)
1056             !ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
1057         }
1058
1059         fn to_camel_case(s: &str) -> String {
1060             s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
1061                 if i == 0 {
1062                     c.to_uppercase().collect::<String>()
1063                 } else {
1064                     c.to_lowercase().collect()
1065                 }
1066             )).collect::<Vec<_>>().concat()
1067         }
1068
1069         let s = ident.name.as_str();
1070
1071         if !is_camel_case(ident) {
1072             let c = to_camel_case(&s);
1073             let m = if c.is_empty() {
1074                 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
1075             } else {
1076                 format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
1077             };
1078             cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
1079         }
1080     }
1081 }
1082
1083 impl LintPass for NonCamelCaseTypes {
1084     fn get_lints(&self) -> LintArray {
1085         lint_array!(NON_CAMEL_CASE_TYPES)
1086     }
1087
1088     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1089         let extern_repr_count = it.attrs.iter().filter(|attr| {
1090             attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
1091                 .any(|r| r == &attr::ReprExtern)
1092         }).count();
1093         let has_extern_repr = extern_repr_count > 0;
1094
1095         if has_extern_repr {
1096             return;
1097         }
1098
1099         match it.node {
1100             ast::ItemTy(..) | ast::ItemStruct(..) => {
1101                 self.check_case(cx, "type", it.ident, it.span)
1102             }
1103             ast::ItemTrait(..) => {
1104                 self.check_case(cx, "trait", it.ident, it.span)
1105             }
1106             ast::ItemEnum(ref enum_definition, _) => {
1107                 if has_extern_repr {
1108                     return;
1109                 }
1110                 self.check_case(cx, "type", it.ident, it.span);
1111                 for variant in &enum_definition.variants {
1112                     self.check_case(cx, "variant", variant.node.name, variant.span);
1113                 }
1114             }
1115             _ => ()
1116         }
1117     }
1118
1119     fn check_generics(&mut self, cx: &Context, it: &ast::Generics) {
1120         for gen in it.ty_params.iter() {
1121             self.check_case(cx, "type parameter", gen.ident, gen.span);
1122         }
1123     }
1124 }
1125
1126 #[derive(PartialEq)]
1127 enum MethodContext {
1128     TraitDefaultImpl,
1129     TraitImpl,
1130     PlainImpl
1131 }
1132
1133 fn method_context(cx: &Context, id: ast::NodeId, span: Span) -> MethodContext {
1134     match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
1135         None => cx.sess().span_bug(span, "missing method descriptor?!"),
1136         Some(item) => match item.container() {
1137             ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
1138             ty::ImplContainer(cid) => {
1139                 match cx.tcx.impl_trait_ref(cid) {
1140                     Some(_) => MethodContext::TraitImpl,
1141                     None => MethodContext::PlainImpl
1142                 }
1143             }
1144         }
1145     }
1146 }
1147
1148 declare_lint! {
1149     pub NON_SNAKE_CASE,
1150     Warn,
1151     "methods, functions, lifetime parameters and modules should have snake case names"
1152 }
1153
1154 #[derive(Copy, Clone)]
1155 pub struct NonSnakeCase;
1156
1157 impl NonSnakeCase {
1158     fn to_snake_case(mut str: &str) -> String {
1159         let mut words = vec![];
1160         // Preserve leading underscores
1161         str = str.trim_left_matches(|c: char| {
1162             if c == '_' {
1163                 words.push(String::new());
1164                 true
1165             } else {
1166                 false
1167             }
1168         });
1169         for s in str.split('_') {
1170             let mut last_upper = false;
1171             let mut buf = String::new();
1172             if s.is_empty() {
1173                 continue;
1174             }
1175             for ch in s.chars() {
1176                 if !buf.is_empty() && buf != "'"
1177                                    && ch.is_uppercase()
1178                                    && !last_upper {
1179                     words.push(buf);
1180                     buf = String::new();
1181                 }
1182                 last_upper = ch.is_uppercase();
1183                 buf.extend(ch.to_lowercase());
1184             }
1185             words.push(buf);
1186         }
1187         words.join("_")
1188     }
1189
1190     fn check_snake_case(&self, cx: &Context, sort: &str, name: &str, span: Option<Span>) {
1191         fn is_snake_case(ident: &str) -> bool {
1192             if ident.is_empty() {
1193                 return true;
1194             }
1195             let ident = ident.trim_left_matches('\'');
1196             let ident = ident.trim_matches('_');
1197
1198             let mut allow_underscore = true;
1199             ident.chars().all(|c| {
1200                 allow_underscore = match c {
1201                     '_' if !allow_underscore => return false,
1202                     '_' => false,
1203                     // It would be more obvious to use `c.is_lowercase()`,
1204                     // but some characters do not have a lowercase form
1205                     c if !c.is_uppercase() => true,
1206                     _ => return false,
1207                 };
1208                 true
1209             })
1210         }
1211
1212         if !is_snake_case(name) {
1213             let sc = NonSnakeCase::to_snake_case(name);
1214             let msg = if sc != name {
1215                 format!("{} `{}` should have a snake case name such as `{}`",
1216                         sort, name, sc)
1217             } else {
1218                 format!("{} `{}` should have a snake case name",
1219                         sort, name)
1220             };
1221             match span {
1222                 Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
1223                 None => cx.lint(NON_SNAKE_CASE, &msg),
1224             }
1225         }
1226     }
1227 }
1228
1229 impl LintPass for NonSnakeCase {
1230     fn get_lints(&self) -> LintArray {
1231         lint_array!(NON_SNAKE_CASE)
1232     }
1233
1234     fn check_crate(&mut self, cx: &Context, cr: &ast::Crate) {
1235         let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
1236                                       .and_then(|at| at.value_str().map(|s| (at, s)));
1237         if let Some(ref name) = cx.tcx.sess.opts.crate_name {
1238             self.check_snake_case(cx, "crate", name, None);
1239         } else if let Some((attr, ref name)) = attr_crate_name {
1240             self.check_snake_case(cx, "crate", name, Some(attr.span));
1241         }
1242     }
1243
1244     fn check_fn(&mut self, cx: &Context,
1245                 fk: FnKind, _: &ast::FnDecl,
1246                 _: &ast::Block, span: Span, id: ast::NodeId) {
1247         match fk {
1248             FnKind::Method(ident, _, _) => match method_context(cx, id, span) {
1249                 MethodContext::PlainImpl => {
1250                     self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
1251                 },
1252                 MethodContext::TraitDefaultImpl => {
1253                     self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
1254                 },
1255                 _ => (),
1256             },
1257             FnKind::ItemFn(ident, _, _, _, _, _) => {
1258                 self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
1259             },
1260             _ => (),
1261         }
1262     }
1263
1264     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1265         if let ast::ItemMod(_) = it.node {
1266             self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
1267         }
1268     }
1269
1270     fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1271         if let ast::MethodTraitItem(_, None) = trait_item.node {
1272             self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
1273                                   Some(trait_item.span));
1274         }
1275     }
1276
1277     fn check_lifetime_def(&mut self, cx: &Context, t: &ast::LifetimeDef) {
1278         self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
1279                               Some(t.lifetime.span));
1280     }
1281
1282     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1283         if let &ast::PatIdent(_, ref path1, _) = &p.node {
1284             let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
1285             if let Some(def::DefLocal(_)) = def {
1286                 self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
1287             }
1288         }
1289     }
1290
1291     fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
1292                         _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
1293         for sf in &s.fields {
1294             if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
1295                 self.check_snake_case(cx, "structure field", &ident.name.as_str(),
1296                                       Some(sf.span));
1297             }
1298         }
1299     }
1300 }
1301
1302 declare_lint! {
1303     pub NON_UPPER_CASE_GLOBALS,
1304     Warn,
1305     "static constants should have uppercase identifiers"
1306 }
1307
1308 #[derive(Copy, Clone)]
1309 pub struct NonUpperCaseGlobals;
1310
1311 impl NonUpperCaseGlobals {
1312     fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1313         let s = ident.name.as_str();
1314
1315         if s.chars().any(|c| c.is_lowercase()) {
1316             let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
1317             if uc != &s[..] {
1318                 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1319                     &format!("{} `{}` should have an upper case name such as `{}`",
1320                              sort, s, uc));
1321             } else {
1322                 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
1323                     &format!("{} `{}` should have an upper case name",
1324                              sort, s));
1325             }
1326         }
1327     }
1328 }
1329
1330 impl LintPass for NonUpperCaseGlobals {
1331     fn get_lints(&self) -> LintArray {
1332         lint_array!(NON_UPPER_CASE_GLOBALS)
1333     }
1334
1335     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1336         match it.node {
1337             // only check static constants
1338             ast::ItemStatic(_, ast::MutImmutable, _) => {
1339                 NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
1340             }
1341             ast::ItemConst(..) => {
1342                 NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
1343             }
1344             _ => {}
1345         }
1346     }
1347
1348     fn check_trait_item(&mut self, cx: &Context, ti: &ast::TraitItem) {
1349         match ti.node {
1350             ast::ConstTraitItem(..) => {
1351                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1352                                                       ti.ident, ti.span);
1353             }
1354             _ => {}
1355         }
1356     }
1357
1358     fn check_impl_item(&mut self, cx: &Context, ii: &ast::ImplItem) {
1359         match ii.node {
1360             ast::ConstImplItem(..) => {
1361                 NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
1362                                                       ii.ident, ii.span);
1363             }
1364             _ => {}
1365         }
1366     }
1367
1368     fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
1369         // Lint for constants that look like binding identifiers (#7526)
1370         match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
1371             (&ast::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
1372                 NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
1373                                                       path1.node, p.span);
1374             }
1375             _ => {}
1376         }
1377     }
1378 }
1379
1380 declare_lint! {
1381     UNUSED_PARENS,
1382     Warn,
1383     "`if`, `match`, `while` and `return` do not need parentheses"
1384 }
1385
1386 #[derive(Copy, Clone)]
1387 pub struct UnusedParens;
1388
1389 impl UnusedParens {
1390     fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
1391                                 struct_lit_needs_parens: bool) {
1392         if let ast::ExprParen(ref inner) = value.node {
1393             let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
1394             if !necessary {
1395                 cx.span_lint(UNUSED_PARENS, value.span,
1396                              &format!("unnecessary parentheses around {}", msg))
1397             }
1398         }
1399
1400         /// Expressions that syntactically contain an "exterior" struct
1401         /// literal i.e. not surrounded by any parens or other
1402         /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
1403         /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
1404         /// y: 1 }) == foo` does not.
1405         fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
1406             match value.node {
1407                 ast::ExprStruct(..) => true,
1408
1409                 ast::ExprAssign(ref lhs, ref rhs) |
1410                 ast::ExprAssignOp(_, ref lhs, ref rhs) |
1411                 ast::ExprBinary(_, ref lhs, ref rhs) => {
1412                     // X { y: 1 } + X { y: 2 }
1413                     contains_exterior_struct_lit(&**lhs) ||
1414                         contains_exterior_struct_lit(&**rhs)
1415                 }
1416                 ast::ExprUnary(_, ref x) |
1417                 ast::ExprCast(ref x, _) |
1418                 ast::ExprField(ref x, _) |
1419                 ast::ExprTupField(ref x, _) |
1420                 ast::ExprIndex(ref x, _) => {
1421                     // &X { y: 1 }, X { y: 1 }.y
1422                     contains_exterior_struct_lit(&**x)
1423                 }
1424
1425                 ast::ExprMethodCall(_, _, ref exprs) => {
1426                     // X { y: 1 }.bar(...)
1427                     contains_exterior_struct_lit(&*exprs[0])
1428                 }
1429
1430                 _ => false
1431             }
1432         }
1433     }
1434 }
1435
1436 impl LintPass for UnusedParens {
1437     fn get_lints(&self) -> LintArray {
1438         lint_array!(UNUSED_PARENS)
1439     }
1440
1441     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1442         let (value, msg, struct_lit_needs_parens) = match e.node {
1443             ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
1444             ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
1445             ast::ExprMatch(ref head, _, source) => match source {
1446                 ast::MatchSource::Normal => (head, "`match` head expression", true),
1447                 ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
1448                 ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
1449                 ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
1450             },
1451             ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
1452             ast::ExprAssign(_, ref value) => (value, "assigned value", false),
1453             ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
1454             _ => return
1455         };
1456         self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
1457     }
1458
1459     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1460         let (value, msg) = match s.node {
1461             ast::StmtDecl(ref decl, _) => match decl.node {
1462                 ast::DeclLocal(ref local) => match local.init {
1463                     Some(ref value) => (value, "assigned value"),
1464                     None => return
1465                 },
1466                 _ => return
1467             },
1468             _ => return
1469         };
1470         self.check_unused_parens_core(cx, &**value, msg, false);
1471     }
1472 }
1473
1474 declare_lint! {
1475     UNUSED_IMPORT_BRACES,
1476     Allow,
1477     "unnecessary braces around an imported item"
1478 }
1479
1480 #[derive(Copy, Clone)]
1481 pub struct UnusedImportBraces;
1482
1483 impl LintPass for UnusedImportBraces {
1484     fn get_lints(&self) -> LintArray {
1485         lint_array!(UNUSED_IMPORT_BRACES)
1486     }
1487
1488     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1489         if let ast::ItemUse(ref view_path) = item.node {
1490             if let ast::ViewPathList(_, ref items) = view_path.node {
1491                 if items.len() == 1 {
1492                     if let ast::PathListIdent {ref name, ..} = items[0].node {
1493                         let m = format!("braces around {} is unnecessary",
1494                                         name);
1495                         cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
1496                                      &m[..]);
1497                     }
1498                 }
1499             }
1500         }
1501     }
1502 }
1503
1504 declare_lint! {
1505     NON_SHORTHAND_FIELD_PATTERNS,
1506     Warn,
1507     "using `Struct { x: x }` instead of `Struct { x }`"
1508 }
1509
1510 #[derive(Copy, Clone)]
1511 pub struct NonShorthandFieldPatterns;
1512
1513 impl LintPass for NonShorthandFieldPatterns {
1514     fn get_lints(&self) -> LintArray {
1515         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
1516     }
1517
1518     fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
1519         let def_map = cx.tcx.def_map.borrow();
1520         if let ast::PatStruct(_, ref v, _) = pat.node {
1521             let field_pats = v.iter().filter(|fieldpat| {
1522                 if fieldpat.node.is_shorthand {
1523                     return false;
1524                 }
1525                 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
1526                 def == Some(def::DefLocal(fieldpat.node.pat.id))
1527             });
1528             for fieldpat in field_pats {
1529                 if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node {
1530                     if ident.node.name == fieldpat.node.ident.name {
1531                         // FIXME: should this comparison really be done on the name?
1532                         // doing it on the ident will fail during compilation of libcore
1533                         cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
1534                                      &format!("the `{}:` in this pattern is redundant and can \
1535                                               be removed", ident.node))
1536                     }
1537                 }
1538             }
1539         }
1540     }
1541 }
1542
1543 declare_lint! {
1544     pub UNUSED_UNSAFE,
1545     Warn,
1546     "unnecessary use of an `unsafe` block"
1547 }
1548
1549 #[derive(Copy, Clone)]
1550 pub struct UnusedUnsafe;
1551
1552 impl LintPass for UnusedUnsafe {
1553     fn get_lints(&self) -> LintArray {
1554         lint_array!(UNUSED_UNSAFE)
1555     }
1556
1557     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1558         if let ast::ExprBlock(ref blk) = e.node {
1559             // Don't warn about generated blocks, that'll just pollute the output.
1560             if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1561                 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1562                     cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
1563             }
1564         }
1565     }
1566 }
1567
1568 declare_lint! {
1569     UNSAFE_CODE,
1570     Allow,
1571     "usage of `unsafe` code"
1572 }
1573
1574 #[derive(Copy, Clone)]
1575 pub struct UnsafeCode;
1576
1577 impl LintPass for UnsafeCode {
1578     fn get_lints(&self) -> LintArray {
1579         lint_array!(UNSAFE_CODE)
1580     }
1581
1582     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1583         if let ast::ExprBlock(ref blk) = e.node {
1584             // Don't warn about generated blocks, that'll just pollute the output.
1585             if blk.rules == ast::UnsafeBlock(ast::UserProvided) {
1586                 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
1587             }
1588         }
1589     }
1590
1591     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1592         match it.node {
1593             ast::ItemTrait(ast::Unsafety::Unsafe, _, _, _) =>
1594                 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
1595
1596             ast::ItemImpl(ast::Unsafety::Unsafe, _, _, _, _, _) =>
1597                 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
1598
1599             _ => return,
1600         }
1601     }
1602
1603     fn check_fn(&mut self, cx: &Context, fk: FnKind, _: &ast::FnDecl,
1604                 _: &ast::Block, span: Span, _: ast::NodeId) {
1605         match fk {
1606             FnKind::ItemFn(_, _, ast::Unsafety::Unsafe, _, _, _) =>
1607                 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
1608
1609             FnKind::Method(_, sig, _) => {
1610                 if sig.unsafety == ast::Unsafety::Unsafe {
1611                     cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
1612                 }
1613             },
1614
1615             _ => (),
1616         }
1617     }
1618
1619     fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1620         if let ast::MethodTraitItem(ref sig, None) = trait_item.node {
1621             if sig.unsafety == ast::Unsafety::Unsafe {
1622                 cx.span_lint(UNSAFE_CODE, trait_item.span,
1623                              "declaration of an `unsafe` method")
1624             }
1625         }
1626     }
1627 }
1628
1629 declare_lint! {
1630     pub UNUSED_MUT,
1631     Warn,
1632     "detect mut variables which don't need to be mutable"
1633 }
1634
1635 #[derive(Copy, Clone)]
1636 pub struct UnusedMut;
1637
1638 impl UnusedMut {
1639     fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
1640         // collect all mutable pattern and group their NodeIDs by their Identifier to
1641         // avoid false warnings in match arms with multiple patterns
1642
1643         let mut mutables = FnvHashMap();
1644         for p in pats {
1645             pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
1646                 let ident = path1.node;
1647                 if let ast::BindByValue(ast::MutMutable) = mode {
1648                     if !ident.name.as_str().starts_with("_") {
1649                         match mutables.entry(ident.name.usize()) {
1650                             Vacant(entry) => { entry.insert(vec![id]); },
1651                             Occupied(mut entry) => { entry.get_mut().push(id); },
1652                         }
1653                     }
1654                 }
1655             });
1656         }
1657
1658         let used_mutables = cx.tcx.used_mut_nodes.borrow();
1659         for (_, v) in &mutables {
1660             if !v.iter().any(|e| used_mutables.contains(e)) {
1661                 cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
1662                              "variable does not need to be mutable");
1663             }
1664         }
1665     }
1666 }
1667
1668 impl LintPass for UnusedMut {
1669     fn get_lints(&self) -> LintArray {
1670         lint_array!(UNUSED_MUT)
1671     }
1672
1673     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1674         if let ast::ExprMatch(_, ref arms, _) = e.node {
1675             for a in arms {
1676                 self.check_unused_mut_pat(cx, &a.pats)
1677             }
1678         }
1679     }
1680
1681     fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
1682         if let ast::StmtDecl(ref d, _) = s.node {
1683             if let ast::DeclLocal(ref l) = d.node {
1684                 self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
1685             }
1686         }
1687     }
1688
1689     fn check_fn(&mut self, cx: &Context,
1690                 _: FnKind, decl: &ast::FnDecl,
1691                 _: &ast::Block, _: Span, _: ast::NodeId) {
1692         for a in &decl.inputs {
1693             self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
1694         }
1695     }
1696 }
1697
1698 declare_lint! {
1699     UNUSED_ALLOCATION,
1700     Warn,
1701     "detects unnecessary allocations that can be eliminated"
1702 }
1703
1704 #[derive(Copy, Clone)]
1705 pub struct UnusedAllocation;
1706
1707 impl LintPass for UnusedAllocation {
1708     fn get_lints(&self) -> LintArray {
1709         lint_array!(UNUSED_ALLOCATION)
1710     }
1711
1712     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
1713         match e.node {
1714             ast::ExprUnary(ast::UnUniq, _) => (),
1715             _ => return
1716         }
1717
1718         if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
1719             if let ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) = *adjustment {
1720                 match autoref {
1721                     &Some(ty::AutoPtr(_, ast::MutImmutable)) => {
1722                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1723                                      "unnecessary allocation, use & instead");
1724                     }
1725                     &Some(ty::AutoPtr(_, ast::MutMutable)) => {
1726                         cx.span_lint(UNUSED_ALLOCATION, e.span,
1727                                      "unnecessary allocation, use &mut instead");
1728                     }
1729                     _ => ()
1730                 }
1731             }
1732         }
1733     }
1734 }
1735
1736 declare_lint! {
1737     MISSING_DOCS,
1738     Allow,
1739     "detects missing documentation for public members"
1740 }
1741
1742 pub struct MissingDoc {
1743     /// Stack of IDs of struct definitions.
1744     struct_def_stack: Vec<ast::NodeId>,
1745
1746     /// True if inside variant definition
1747     in_variant: bool,
1748
1749     /// Stack of whether #[doc(hidden)] is set
1750     /// at each level which has lint attributes.
1751     doc_hidden_stack: Vec<bool>,
1752
1753     /// Private traits or trait items that leaked through. Don't check their methods.
1754     private_traits: HashSet<ast::NodeId>,
1755 }
1756
1757 impl MissingDoc {
1758     pub fn new() -> MissingDoc {
1759         MissingDoc {
1760             struct_def_stack: vec!(),
1761             in_variant: false,
1762             doc_hidden_stack: vec!(false),
1763             private_traits: HashSet::new(),
1764         }
1765     }
1766
1767     fn doc_hidden(&self) -> bool {
1768         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
1769     }
1770
1771     fn check_missing_docs_attrs(&self,
1772                                cx: &Context,
1773                                id: Option<ast::NodeId>,
1774                                attrs: &[ast::Attribute],
1775                                sp: Span,
1776                                desc: &'static str) {
1777         // If we're building a test harness, then warning about
1778         // documentation is probably not really relevant right now.
1779         if cx.sess().opts.test {
1780             return;
1781         }
1782
1783         // `#[doc(hidden)]` disables missing_docs check.
1784         if self.doc_hidden() {
1785             return;
1786         }
1787
1788         // Only check publicly-visible items, using the result from the privacy pass.
1789         // It's an option so the crate root can also use this function (it doesn't
1790         // have a NodeId).
1791         if let Some(ref id) = id {
1792             if !cx.exported_items.contains(id) {
1793                 return;
1794             }
1795         }
1796
1797         let has_doc = attrs.iter().any(|a| {
1798             match a.node.value.node {
1799                 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
1800                 _ => false
1801             }
1802         });
1803         if !has_doc {
1804             cx.span_lint(MISSING_DOCS, sp,
1805                          &format!("missing documentation for {}", desc));
1806         }
1807     }
1808 }
1809
1810 impl LintPass for MissingDoc {
1811     fn get_lints(&self) -> LintArray {
1812         lint_array!(MISSING_DOCS)
1813     }
1814
1815     fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
1816         let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
1817             attr.check_name("doc") && match attr.meta_item_list() {
1818                 None => false,
1819                 Some(l) => attr::contains_name(&l[..], "hidden"),
1820             }
1821         });
1822         self.doc_hidden_stack.push(doc_hidden);
1823     }
1824
1825     fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
1826         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
1827     }
1828
1829     fn check_struct_def(&mut self, _: &Context, _: &ast::StructDef,
1830                         _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1831         self.struct_def_stack.push(id);
1832     }
1833
1834     fn check_struct_def_post(&mut self, _: &Context, _: &ast::StructDef,
1835                              _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
1836         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
1837         assert!(popped == id);
1838     }
1839
1840     fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
1841         self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
1842     }
1843
1844     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
1845         let desc = match it.node {
1846             ast::ItemFn(..) => "a function",
1847             ast::ItemMod(..) => "a module",
1848             ast::ItemEnum(..) => "an enum",
1849             ast::ItemStruct(..) => "a struct",
1850             ast::ItemTrait(_, _, _, ref items) => {
1851                 // Issue #11592, traits are always considered exported, even when private.
1852                 if it.vis == ast::Visibility::Inherited {
1853                     self.private_traits.insert(it.id);
1854                     for itm in items {
1855                         self.private_traits.insert(itm.id);
1856                     }
1857                     return
1858                 }
1859                 "a trait"
1860             },
1861             ast::ItemTy(..) => "a type alias",
1862             ast::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
1863                 // If the trait is private, add the impl items to private_traits so they don't get
1864                 // reported for missing docs.
1865                 let real_trait = cx.tcx.trait_ref_to_def_id(trait_ref);
1866                 match cx.tcx.map.find(real_trait.node) {
1867                     Some(ast_map::NodeItem(item)) => if item.vis == ast::Visibility::Inherited {
1868                         for itm in impl_items {
1869                             self.private_traits.insert(itm.id);
1870                         }
1871                     },
1872                     _ => { }
1873                 }
1874                 return
1875             },
1876             ast::ItemConst(..) => "a constant",
1877             ast::ItemStatic(..) => "a static",
1878             _ => return
1879         };
1880
1881         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
1882     }
1883
1884     fn check_trait_item(&mut self, cx: &Context, trait_item: &ast::TraitItem) {
1885         if self.private_traits.contains(&trait_item.id) { return }
1886
1887         let desc = match trait_item.node {
1888             ast::ConstTraitItem(..) => "an associated constant",
1889             ast::MethodTraitItem(..) => "a trait method",
1890             ast::TypeTraitItem(..) => "an associated type",
1891         };
1892
1893         self.check_missing_docs_attrs(cx, Some(trait_item.id),
1894                                       &trait_item.attrs,
1895                                       trait_item.span, desc);
1896     }
1897
1898     fn check_impl_item(&mut self, cx: &Context, impl_item: &ast::ImplItem) {
1899         // If the method is an impl for a trait, don't doc.
1900         if method_context(cx, impl_item.id, impl_item.span) == MethodContext::TraitImpl {
1901             return;
1902         }
1903
1904         let desc = match impl_item.node {
1905             ast::ConstImplItem(..) => "an associated constant",
1906             ast::MethodImplItem(..) => "a method",
1907             ast::TypeImplItem(_) => "an associated type",
1908             ast::MacImplItem(_) => "an impl item macro",
1909         };
1910         self.check_missing_docs_attrs(cx, Some(impl_item.id),
1911                                       &impl_item.attrs,
1912                                       impl_item.span, desc);
1913     }
1914
1915     fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
1916         if let ast::NamedField(_, vis) = sf.node.kind {
1917             if vis == ast::Public || self.in_variant {
1918                 let cur_struct_def = *self.struct_def_stack.last()
1919                     .expect("empty struct_def_stack");
1920                 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
1921                                               &sf.node.attrs, sf.span,
1922                                               "a struct field")
1923             }
1924         }
1925     }
1926
1927     fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
1928         self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
1929         assert!(!self.in_variant);
1930         self.in_variant = true;
1931     }
1932
1933     fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) {
1934         assert!(self.in_variant);
1935         self.in_variant = false;
1936     }
1937 }
1938
1939 declare_lint! {
1940     pub MISSING_COPY_IMPLEMENTATIONS,
1941     Allow,
1942     "detects potentially-forgotten implementations of `Copy`"
1943 }
1944
1945 #[derive(Copy, Clone)]
1946 pub struct MissingCopyImplementations;
1947
1948 impl LintPass for MissingCopyImplementations {
1949     fn get_lints(&self) -> LintArray {
1950         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
1951     }
1952
1953     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
1954         if !cx.exported_items.contains(&item.id) {
1955             return;
1956         }
1957         let (def, ty) = match item.node {
1958             ast::ItemStruct(_, ref ast_generics) => {
1959                 if ast_generics.is_parameterized() {
1960                     return;
1961                 }
1962                 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1963                 (def, cx.tcx.mk_struct(def,
1964                                        cx.tcx.mk_substs(Substs::empty())))
1965             }
1966             ast::ItemEnum(_, ref ast_generics) => {
1967                 if ast_generics.is_parameterized() {
1968                     return;
1969                 }
1970                 let def = cx.tcx.lookup_adt_def(DefId::local(item.id));
1971                 (def, cx.tcx.mk_enum(def,
1972                                      cx.tcx.mk_substs(Substs::empty())))
1973             }
1974             _ => return,
1975         };
1976         if def.has_dtor() { return; }
1977         let parameter_environment = cx.tcx.empty_parameter_environment();
1978         // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
1979         // method
1980         if !ty.moves_by_default(&parameter_environment, item.span) {
1981             return;
1982         }
1983         if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
1984             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
1985                          item.span,
1986                          "type could implement `Copy`; consider adding `impl \
1987                           Copy`")
1988         }
1989     }
1990 }
1991
1992 declare_lint! {
1993     MISSING_DEBUG_IMPLEMENTATIONS,
1994     Allow,
1995     "detects missing implementations of fmt::Debug"
1996 }
1997
1998 pub struct MissingDebugImplementations {
1999     impling_types: Option<NodeSet>,
2000 }
2001
2002 impl MissingDebugImplementations {
2003     pub fn new() -> MissingDebugImplementations {
2004         MissingDebugImplementations {
2005             impling_types: None,
2006         }
2007     }
2008 }
2009
2010 impl LintPass for MissingDebugImplementations {
2011     fn get_lints(&self) -> LintArray {
2012         lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
2013     }
2014
2015     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
2016         if !cx.exported_items.contains(&item.id) {
2017             return;
2018         }
2019
2020         match item.node {
2021             ast::ItemStruct(..) | ast::ItemEnum(..) => {},
2022             _ => return,
2023         }
2024
2025         let debug = match cx.tcx.lang_items.debug_trait() {
2026             Some(debug) => debug,
2027             None => return,
2028         };
2029
2030         if self.impling_types.is_none() {
2031             let debug_def = cx.tcx.lookup_trait_def(debug);
2032             let mut impls = NodeSet();
2033             debug_def.for_each_impl(cx.tcx, |d| {
2034                 if d.is_local() {
2035                     if let Some(ty_def) = cx.tcx.node_id_to_type(d.node).ty_to_def_id() {
2036                         impls.insert(ty_def.node);
2037                     }
2038                 }
2039             });
2040
2041             self.impling_types = Some(impls);
2042             debug!("{:?}", self.impling_types);
2043         }
2044
2045         if !self.impling_types.as_ref().unwrap().contains(&item.id) {
2046             cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
2047                          item.span,
2048                          "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
2049                           or a manual implementation")
2050         }
2051     }
2052 }
2053
2054 declare_lint! {
2055     DEPRECATED,
2056     Warn,
2057     "detects use of #[deprecated] items"
2058 }
2059
2060 /// Checks for use of items with `#[deprecated]` attributes
2061 #[derive(Copy, Clone)]
2062 pub struct Stability;
2063
2064 impl Stability {
2065     fn lint(&self, cx: &Context, _id: DefId,
2066             span: Span, stability: &Option<&attr::Stability>) {
2067         // Deprecated attributes apply in-crate and cross-crate.
2068         let (lint, label) = match *stability {
2069             Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
2070                 (DEPRECATED, "deprecated"),
2071             _ => return
2072         };
2073
2074         output(cx, span, stability, lint, label);
2075
2076         fn output(cx: &Context, span: Span, stability: &Option<&attr::Stability>,
2077                   lint: &'static Lint, label: &'static str) {
2078             let msg = match *stability {
2079                 Some(&attr::Stability { reason: Some(ref s), .. }) => {
2080                     format!("use of {} item: {}", label, *s)
2081                 }
2082                 _ => format!("use of {} item", label)
2083             };
2084
2085             cx.span_lint(lint, span, &msg[..]);
2086         }
2087     }
2088 }
2089
2090 impl LintPass for Stability {
2091     fn get_lints(&self) -> LintArray {
2092         lint_array!(DEPRECATED)
2093     }
2094
2095     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
2096         stability::check_item(cx.tcx, item, false,
2097                               &mut |id, sp, stab| self.lint(cx, id, sp, stab));
2098     }
2099
2100     fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
2101         stability::check_expr(cx.tcx, e,
2102                               &mut |id, sp, stab| self.lint(cx, id, sp, stab));
2103     }
2104
2105     fn check_path(&mut self, cx: &Context, path: &ast::Path, id: ast::NodeId) {
2106         stability::check_path(cx.tcx, path, id,
2107                               &mut |id, sp, stab| self.lint(cx, id, sp, stab));
2108     }
2109
2110     fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
2111         stability::check_pat(cx.tcx, pat,
2112                              &mut |id, sp, stab| self.lint(cx, id, sp, stab))
2113     }
2114 }
2115
2116 declare_lint! {
2117     pub UNCONDITIONAL_RECURSION,
2118     Warn,
2119     "functions that cannot return without calling themselves"
2120 }
2121
2122 #[derive(Copy, Clone)]
2123 pub struct UnconditionalRecursion;
2124
2125
2126 impl LintPass for UnconditionalRecursion {
2127     fn get_lints(&self) -> LintArray {
2128         lint_array![UNCONDITIONAL_RECURSION]
2129     }
2130
2131     fn check_fn(&mut self, cx: &Context, fn_kind: FnKind, _: &ast::FnDecl,
2132                 blk: &ast::Block, sp: Span, id: ast::NodeId) {
2133         type F = for<'tcx> fn(&ty::ctxt<'tcx>,
2134                               ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
2135
2136         let method = match fn_kind {
2137             FnKind::ItemFn(..) => None,
2138             FnKind::Method(..) => {
2139                 cx.tcx.impl_or_trait_item(DefId::local(id)).as_opt_method()
2140             }
2141             // closures can't recur, so they don't matter.
2142             FnKind::Closure => return
2143         };
2144
2145         // Walk through this function (say `f`) looking to see if
2146         // every possible path references itself, i.e. the function is
2147         // called recursively unconditionally. This is done by trying
2148         // to find a path from the entry node to the exit node that
2149         // *doesn't* call `f` by traversing from the entry while
2150         // pretending that calls of `f` are sinks (i.e. ignoring any
2151         // exit edges from them).
2152         //
2153         // NB. this has an edge case with non-returning statements,
2154         // like `loop {}` or `panic!()`: control flow never reaches
2155         // the exit node through these, so one can have a function
2156         // that never actually calls itselfs but is still picked up by
2157         // this lint:
2158         //
2159         //     fn f(cond: bool) {
2160         //         if !cond { panic!() } // could come from `assert!(cond)`
2161         //         f(false)
2162         //     }
2163         //
2164         // In general, functions of that form may be able to call
2165         // itself a finite number of times and then diverge. The lint
2166         // considers this to be an error for two reasons, (a) it is
2167         // easier to implement, and (b) it seems rare to actually want
2168         // to have behaviour like the above, rather than
2169         // e.g. accidentally recurring after an assert.
2170
2171         let cfg = cfg::CFG::new(cx.tcx, blk);
2172
2173         let mut work_queue = vec![cfg.entry];
2174         let mut reached_exit_without_self_call = false;
2175         let mut self_call_spans = vec![];
2176         let mut visited = HashSet::new();
2177
2178         while let Some(idx) = work_queue.pop() {
2179             if idx == cfg.exit {
2180                 // found a path!
2181                 reached_exit_without_self_call = true;
2182                 break;
2183             }
2184
2185             let cfg_id = idx.node_id();
2186             if visited.contains(&cfg_id) {
2187                 // already done
2188                 continue;
2189             }
2190             visited.insert(cfg_id);
2191
2192             let node_id = cfg.graph.node_data(idx).id();
2193
2194             // is this a recursive call?
2195             let self_recursive = if node_id != ast::DUMMY_NODE_ID {
2196                 match method {
2197                     Some(ref method) => {
2198                         expr_refers_to_this_method(cx.tcx, method, node_id)
2199                     }
2200                     None => expr_refers_to_this_fn(cx.tcx, id, node_id)
2201                 }
2202             } else {
2203                 false
2204             };
2205             if self_recursive {
2206                 self_call_spans.push(cx.tcx.map.span(node_id));
2207                 // this is a self call, so we shouldn't explore past
2208                 // this node in the CFG.
2209                 continue;
2210             }
2211             // add the successors of this node to explore the graph further.
2212             for (_, edge) in cfg.graph.outgoing_edges(idx) {
2213                 let target_idx = edge.target();
2214                 let target_cfg_id = target_idx.node_id();
2215                 if !visited.contains(&target_cfg_id) {
2216                     work_queue.push(target_idx)
2217                 }
2218             }
2219         }
2220
2221         // Check the number of self calls because a function that
2222         // doesn't return (e.g. calls a `-> !` function or `loop { /*
2223         // no break */ }`) shouldn't be linted unless it actually
2224         // recurs.
2225         if !reached_exit_without_self_call && !self_call_spans.is_empty() {
2226             cx.span_lint(UNCONDITIONAL_RECURSION, sp,
2227                          "function cannot return without recurring");
2228
2229             // FIXME #19668: these could be span_lint_note's instead of this manual guard.
2230             if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
2231                 let sess = cx.sess();
2232                 // offer some help to the programmer.
2233                 for call in &self_call_spans {
2234                     sess.span_note(*call, "recursive call site")
2235                 }
2236                 sess.fileline_help(sp, "a `loop` may express intention \
2237                                         better if this is on purpose")
2238             }
2239         }
2240
2241         // all done
2242         return;
2243
2244         // Functions for identifying if the given Expr NodeId `id`
2245         // represents a call to the function `fn_id`/method `method`.
2246
2247         fn expr_refers_to_this_fn(tcx: &ty::ctxt,
2248                                   fn_id: ast::NodeId,
2249                                   id: ast::NodeId) -> bool {
2250             match tcx.map.get(id) {
2251                 ast_map::NodeExpr(&ast::Expr { node: ast::ExprCall(ref callee, _), .. }) => {
2252                     tcx.def_map.borrow().get(&callee.id)
2253                         .map_or(false, |def| def.def_id() == DefId::local(fn_id))
2254                 }
2255                 _ => false
2256             }
2257         }
2258
2259         // Check if the expression `id` performs a call to `method`.
2260         fn expr_refers_to_this_method(tcx: &ty::ctxt,
2261                                       method: &ty::Method,
2262                                       id: ast::NodeId) -> bool {
2263             let tables = tcx.tables.borrow();
2264
2265             // Check for method calls and overloaded operators.
2266             if let Some(m) = tables.method_map.get(&ty::MethodCall::expr(id)) {
2267                 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2268                     return true;
2269                 }
2270             }
2271
2272             // Check for overloaded autoderef method calls.
2273             if let Some(&ty::AdjustDerefRef(ref adj)) = tables.adjustments.get(&id) {
2274                 for i in 0..adj.autoderefs {
2275                     let method_call = ty::MethodCall::autoderef(id, i as u32);
2276                     if let Some(m) = tables.method_map.get(&method_call) {
2277                         if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
2278                             return true;
2279                         }
2280                     }
2281                 }
2282             }
2283
2284             // Check for calls to methods via explicit paths (e.g. `T::method()`).
2285             match tcx.map.get(id) {
2286                 ast_map::NodeExpr(&ast::Expr { node: ast::ExprCall(ref callee, _), .. }) => {
2287                     match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
2288                         Some(def::DefMethod(def_id)) => {
2289                             let no_substs = &ty::ItemSubsts::empty();
2290                             let ts = tables.item_substs.get(&callee.id).unwrap_or(no_substs);
2291                             method_call_refers_to_method(tcx, method, def_id, &ts.substs, id)
2292                         }
2293                         _ => false
2294                     }
2295                 }
2296                 _ => false
2297             }
2298         }
2299
2300         // Check if the method call to the method with the ID `callee_id`
2301         // and instantiated with `callee_substs` refers to method `method`.
2302         fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
2303                                               method: &ty::Method,
2304                                               callee_id: DefId,
2305                                               callee_substs: &Substs<'tcx>,
2306                                               expr_id: ast::NodeId) -> bool {
2307             let callee_item = tcx.impl_or_trait_item(callee_id);
2308
2309             match callee_item.container() {
2310                 // This is an inherent method, so the `def_id` refers
2311                 // directly to the method definition.
2312                 ty::ImplContainer(_) => {
2313                     callee_id == method.def_id
2314                 }
2315
2316                 // A trait method, from any number of possible sources.
2317                 // Attempt to select a concrete impl before checking.
2318                 ty::TraitContainer(trait_def_id) => {
2319                     let trait_substs = callee_substs.clone().method_to_trait();
2320                     let trait_substs = tcx.mk_substs(trait_substs);
2321                     let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
2322                     let trait_ref = ty::Binder(trait_ref);
2323                     let span = tcx.map.span(expr_id);
2324                     let obligation =
2325                         traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
2326                                                 trait_ref.to_poly_trait_predicate());
2327
2328                     let param_env = ty::ParameterEnvironment::for_item(tcx, method.def_id.node);
2329                     let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
2330                     let mut selcx = traits::SelectionContext::new(&infcx);
2331                     match selcx.select(&obligation) {
2332                         // The method comes from a `T: Trait` bound.
2333                         // If `T` is `Self`, then this call is inside
2334                         // a default method definition.
2335                         Ok(Some(traits::VtableParam(_))) => {
2336                             let self_ty = callee_substs.self_ty();
2337                             let on_self = self_ty.map_or(false, |t| t.is_self());
2338                             // We can only be recurring in a default
2339                             // method if we're being called literally
2340                             // on the `Self` type.
2341                             on_self && callee_id == method.def_id
2342                         }
2343
2344                         // The `impl` is known, so we check that with a
2345                         // special case:
2346                         Ok(Some(traits::VtableImpl(vtable_impl))) => {
2347                             let container = ty::ImplContainer(vtable_impl.impl_def_id);
2348                             // It matches if it comes from the same impl,
2349                             // and has the same method name.
2350                             container == method.container
2351                                 && callee_item.name() == method.name
2352                         }
2353
2354                         // There's no way to know if this call is
2355                         // recursive, so we assume it's not.
2356                         _ => return false
2357                     }
2358                 }
2359             }
2360         }
2361     }
2362 }
2363
2364 declare_lint! {
2365     PLUGIN_AS_LIBRARY,
2366     Warn,
2367     "compiler plugin used as ordinary library in non-plugin crate"
2368 }
2369
2370 #[derive(Copy, Clone)]
2371 pub struct PluginAsLibrary;
2372
2373 impl LintPass for PluginAsLibrary {
2374     fn get_lints(&self) -> LintArray {
2375         lint_array![PLUGIN_AS_LIBRARY]
2376     }
2377
2378     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2379         if cx.sess().plugin_registrar_fn.get().is_some() {
2380             // We're compiling a plugin; it's fine to link other plugins.
2381             return;
2382         }
2383
2384         match it.node {
2385             ast::ItemExternCrate(..) => (),
2386             _ => return,
2387         };
2388
2389         let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
2390             Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
2391             None => {
2392                 // Probably means we aren't linking the crate for some reason.
2393                 //
2394                 // Not sure if / when this could happen.
2395                 return;
2396             }
2397         };
2398
2399         if decoder::get_plugin_registrar_fn(md.data()).is_some() {
2400             cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
2401                          "compiler plugin used as an ordinary library");
2402         }
2403     }
2404 }
2405
2406 declare_lint! {
2407     PRIVATE_NO_MANGLE_FNS,
2408     Warn,
2409     "functions marked #[no_mangle] should be exported"
2410 }
2411
2412 declare_lint! {
2413     PRIVATE_NO_MANGLE_STATICS,
2414     Warn,
2415     "statics marked #[no_mangle] should be exported"
2416 }
2417
2418 declare_lint! {
2419     NO_MANGLE_CONST_ITEMS,
2420     Deny,
2421     "const items will not have their symbols exported"
2422 }
2423
2424 #[derive(Copy, Clone)]
2425 pub struct InvalidNoMangleItems;
2426
2427 impl LintPass for InvalidNoMangleItems {
2428     fn get_lints(&self) -> LintArray {
2429         lint_array!(PRIVATE_NO_MANGLE_FNS,
2430                     PRIVATE_NO_MANGLE_STATICS,
2431                     NO_MANGLE_CONST_ITEMS)
2432     }
2433
2434     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
2435         match it.node {
2436             ast::ItemFn(..) => {
2437                 if attr::contains_name(&it.attrs, "no_mangle") &&
2438                        !cx.exported_items.contains(&it.id) {
2439                     let msg = format!("function {} is marked #[no_mangle], but not exported",
2440                                       it.ident);
2441                     cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
2442                 }
2443             },
2444             ast::ItemStatic(..) => {
2445                 if attr::contains_name(&it.attrs, "no_mangle") &&
2446                        !cx.exported_items.contains(&it.id) {
2447                     let msg = format!("static {} is marked #[no_mangle], but not exported",
2448                                       it.ident);
2449                     cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
2450                 }
2451             },
2452             ast::ItemConst(..) => {
2453                 if attr::contains_name(&it.attrs, "no_mangle") {
2454                     // Const items do not refer to a particular location in memory, and therefore
2455                     // don't have anything to attach a symbol to
2456                     let msg = "const items should never be #[no_mangle], consider instead using \
2457                                `pub static`";
2458                     cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
2459                 }
2460             }
2461             _ => {},
2462         }
2463     }
2464 }
2465
2466 #[derive(Clone, Copy)]
2467 pub struct MutableTransmutes;
2468
2469 declare_lint! {
2470     MUTABLE_TRANSMUTES,
2471     Deny,
2472     "mutating transmuted &mut T from &T may cause undefined behavior"
2473 }
2474
2475 impl LintPass for MutableTransmutes {
2476     fn get_lints(&self) -> LintArray {
2477         lint_array!(MUTABLE_TRANSMUTES)
2478     }
2479
2480     fn check_expr(&mut self, cx: &Context, expr: &ast::Expr) {
2481         use syntax::abi::RustIntrinsic;
2482         let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
2483                    consider instead using an UnsafeCell";
2484         match get_transmute_from_to(cx, expr) {
2485             Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
2486                 if to_mt.mutbl == ast::Mutability::MutMutable
2487                     && from_mt.mutbl == ast::Mutability::MutImmutable {
2488                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
2489                 }
2490             }
2491             _ => ()
2492         }
2493
2494         fn get_transmute_from_to<'a, 'tcx>(cx: &Context<'a, 'tcx>, expr: &ast::Expr)
2495             -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
2496             match expr.node {
2497                 ast::ExprPath(..) => (),
2498                 _ => return None
2499             }
2500             if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
2501                 if !def_id_is_transmute(cx, did) {
2502                     return None;
2503                 }
2504                 let typ = cx.tcx.node_id_to_type(expr.id);
2505                 match typ.sty {
2506                     ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
2507                         if let ty::FnConverging(to) = bare_fn.sig.0.output {
2508                             let from = bare_fn.sig.0.inputs[0];
2509                             return Some((&from.sty, &to.sty));
2510                         }
2511                     },
2512                     _ => ()
2513                 }
2514             }
2515             None
2516         }
2517
2518         fn def_id_is_transmute(cx: &Context, def_id: DefId) -> bool {
2519             match cx.tcx.lookup_item_type(def_id).ty.sty {
2520                 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
2521                 _ => return false
2522             }
2523             cx.tcx.with_path(def_id, |path| match path.last() {
2524                 Some(ref last) => last.name().as_str() == "transmute",
2525                 _ => false
2526             })
2527         }
2528     }
2529 }
2530
2531 /// Forbids using the `#[feature(...)]` attribute
2532 #[derive(Copy, Clone)]
2533 pub struct UnstableFeatures;
2534
2535 declare_lint! {
2536     UNSTABLE_FEATURES,
2537     Allow,
2538     "enabling unstable features (deprecated. do not use)"
2539 }
2540
2541 impl LintPass for UnstableFeatures {
2542     fn get_lints(&self) -> LintArray {
2543         lint_array!(UNSTABLE_FEATURES)
2544     }
2545     fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
2546         if attr::contains_name(&[attr.node.value.clone()], "feature") {
2547             if let Some(items) = attr.node.value.meta_item_list() {
2548                 for item in items {
2549                     ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
2550                 }
2551             }
2552         }
2553     }
2554 }
2555
2556 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
2557 /// attribute (see issue #24585).
2558 #[derive(Copy, Clone)]
2559 pub struct DropWithReprExtern;
2560
2561 declare_lint! {
2562     DROP_WITH_REPR_EXTERN,
2563     Warn,
2564     "use of #[repr(C)] on a type that implements Drop"
2565 }
2566
2567 impl LintPass for DropWithReprExtern {
2568     fn get_lints(&self) -> LintArray {
2569         lint_array!(DROP_WITH_REPR_EXTERN)
2570     }
2571     fn check_crate(&mut self, ctx: &Context, _: &ast::Crate) {
2572         for dtor_did in ctx.tcx.destructors.borrow().iter() {
2573             let (drop_impl_did, dtor_self_type) =
2574                 if dtor_did.is_local() {
2575                     let impl_did = ctx.tcx.map.get_parent_did(dtor_did.node);
2576                     let ty = ctx.tcx.lookup_item_type(impl_did).ty;
2577                     (impl_did, ty)
2578                 } else {
2579                     continue;
2580                 };
2581
2582             match dtor_self_type.sty {
2583                 ty::TyEnum(self_type_def, _) |
2584                 ty::TyStruct(self_type_def, _) => {
2585                     let self_type_did = self_type_def.did;
2586                     let hints = ctx.tcx.lookup_repr_hints(self_type_did);
2587                     if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
2588                         self_type_def.dtor_kind().has_drop_flag() {
2589                         let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
2590                                                                      codemap::DUMMY_SP);
2591                         let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
2592                                                                      codemap::DUMMY_SP);
2593                         ctx.span_lint(DROP_WITH_REPR_EXTERN,
2594                                       drop_impl_span,
2595                                       "implementing Drop adds hidden state to types, \
2596                                        possibly conflicting with `#[repr(C)]`");
2597                         // FIXME #19668: could be span_lint_note instead of manual guard.
2598                         if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
2599                             ctx.sess().span_note(self_defn_span,
2600                                                "the `#[repr(C)]` attribute is attached here");
2601                         }
2602                     }
2603                 }
2604                 _ => {}
2605             }
2606         }
2607     }
2608 }