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