]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lint.rs
librustc: Remove `@str` from the language
[rust.git] / src / librustc / middle / lint.rs
1 // Copyright 2012-2014 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 //! A 'lint' check is a kind of miscellaneous constraint that a user _might_
12 //! want to enforce, but might reasonably want to permit as well, on a
13 //! module-by-module basis. They contrast with static constraints enforced by
14 //! other phases of the compiler, which are generally required to hold in order
15 //! to compile the program at all.
16 //!
17 //! The lint checking is all consolidated into one pass which runs just before
18 //! translation to LLVM bytecode. Throughout compilation, lint warnings can be
19 //! added via the `add_lint` method on the Session structure. This requires a
20 //! span and an id of the node that the lint is being added to. The lint isn't
21 //! actually emitted at that time because it is unknown what the actual lint
22 //! level at that location is.
23 //!
24 //! To actually emit lint warnings/errors, a separate pass is used just before
25 //! translation. A context keeps track of the current state of all lint levels.
26 //! Upon entering a node of the ast which can modify the lint settings, the
27 //! previous lint state is pushed onto a stack and the ast is then recursed
28 //! upon.  As the ast is traversed, this keeps track of the current lint level
29 //! for all lint attributes.
30 //!
31 //! To add a new lint warning, all you need to do is to either invoke `add_lint`
32 //! on the session at the appropriate time, or write a few linting functions and
33 //! modify the Context visitor appropriately. If you're adding lints from the
34 //! Context itself, span_lint should be used instead of add_lint.
35
36 use driver::session;
37 use metadata::csearch;
38 use middle::dead::DEAD_CODE_LINT_STR;
39 use middle::pat_util;
40 use middle::privacy;
41 use middle::trans::adt; // for `adt::is_ffi_safe`
42 use middle::ty;
43 use middle::typeck::astconv::{ast_ty_to_ty, AstConv};
44 use middle::typeck::infer;
45 use middle::typeck;
46 use std::to_str::ToStr;
47 use util::ppaux::{ty_to_str};
48
49 use std::cmp;
50 use std::hashmap::HashMap;
51 use std::i16;
52 use std::i32;
53 use std::i64;
54 use std::i8;
55 use std::u16;
56 use std::u32;
57 use std::u64;
58 use std::u8;
59 use extra::smallintmap::SmallIntMap;
60 use syntax::ast_map;
61 use syntax::ast_util::IdVisitingOperation;
62 use syntax::attr::{AttrMetaMethods, AttributeMethods};
63 use syntax::attr;
64 use syntax::codemap::Span;
65 use syntax::parse::token::InternedString;
66 use syntax::parse::token;
67 use syntax::visit::Visitor;
68 use syntax::{ast, ast_util, visit};
69
70 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
71 pub enum Lint {
72     CTypes,
73     UnusedImports,
74     UnnecessaryQualification,
75     WhileTrue,
76     PathStatement,
77     UnrecognizedLint,
78     NonCamelCaseTypes,
79     NonUppercaseStatics,
80     NonUppercasePatternStatics,
81     UnnecessaryParens,
82     TypeLimits,
83     TypeOverflow,
84     UnusedUnsafe,
85     UnsafeBlock,
86     AttributeUsage,
87     UnknownFeatures,
88     UnknownCrateType,
89     DefaultTypeParamUsage,
90
91     ManagedHeapMemory,
92     OwnedHeapMemory,
93     HeapMemory,
94
95     UnusedVariable,
96     DeadAssignment,
97     UnusedMut,
98     UnnecessaryAllocation,
99     DeadCode,
100     UnnecessaryTypecast,
101
102     MissingDoc,
103     UnreachableCode,
104
105     Deprecated,
106     Experimental,
107     Unstable,
108
109     UnusedMustUse,
110     UnusedResult,
111
112     Warnings,
113 }
114
115 pub fn level_to_str(lv: level) -> &'static str {
116     match lv {
117       allow => "allow",
118       warn => "warn",
119       deny => "deny",
120       forbid => "forbid"
121     }
122 }
123
124 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
125 pub enum level {
126     allow, warn, deny, forbid
127 }
128
129 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
130 pub struct LintSpec {
131     default: level,
132     lint: Lint,
133     desc: &'static str,
134 }
135
136 pub type LintDict = HashMap<&'static str, LintSpec>;
137
138 #[deriving(Eq)]
139 enum LintSource {
140     Node(Span),
141     Default,
142     CommandLine
143 }
144
145 static lint_table: &'static [(&'static str, LintSpec)] = &[
146     ("ctypes",
147      LintSpec {
148         lint: CTypes,
149         desc: "proper use of std::libc types in foreign modules",
150         default: warn
151      }),
152
153     ("unused_imports",
154      LintSpec {
155         lint: UnusedImports,
156         desc: "imports that are never used",
157         default: warn
158      }),
159
160     ("unnecessary_qualification",
161      LintSpec {
162         lint: UnnecessaryQualification,
163         desc: "detects unnecessarily qualified names",
164         default: allow
165      }),
166
167     ("while_true",
168      LintSpec {
169         lint: WhileTrue,
170         desc: "suggest using `loop { }` instead of `while true { }`",
171         default: warn
172      }),
173
174     ("path_statement",
175      LintSpec {
176         lint: PathStatement,
177         desc: "path statements with no effect",
178         default: warn
179      }),
180
181     ("unrecognized_lint",
182      LintSpec {
183         lint: UnrecognizedLint,
184         desc: "unrecognized lint attribute",
185         default: warn
186      }),
187
188     ("non_camel_case_types",
189      LintSpec {
190         lint: NonCamelCaseTypes,
191         desc: "types, variants and traits should have camel case names",
192         default: allow
193      }),
194
195     ("non_uppercase_statics",
196      LintSpec {
197          lint: NonUppercaseStatics,
198          desc: "static constants should have uppercase identifiers",
199          default: allow
200      }),
201
202     ("non_uppercase_pattern_statics",
203      LintSpec {
204          lint: NonUppercasePatternStatics,
205          desc: "static constants in match patterns should be all caps",
206          default: warn
207      }),
208
209     ("unnecessary_parens",
210      LintSpec {
211         lint: UnnecessaryParens,
212         desc: "`if`, `match`, `while` and `return` do not need parentheses",
213         default: warn
214      }),
215
216     ("managed_heap_memory",
217      LintSpec {
218         lint: ManagedHeapMemory,
219         desc: "use of managed (@ type) heap memory",
220         default: allow
221      }),
222
223     ("owned_heap_memory",
224      LintSpec {
225         lint: OwnedHeapMemory,
226         desc: "use of owned (~ type) heap memory",
227         default: allow
228      }),
229
230     ("heap_memory",
231      LintSpec {
232         lint: HeapMemory,
233         desc: "use of any (~ type or @ type) heap memory",
234         default: allow
235      }),
236
237     ("type_limits",
238      LintSpec {
239         lint: TypeLimits,
240         desc: "comparisons made useless by limits of the types involved",
241         default: warn
242      }),
243
244     ("type_overflow",
245      LintSpec {
246         lint: TypeOverflow,
247         desc: "literal out of range for its type",
248         default: warn
249      }),
250
251
252     ("unused_unsafe",
253      LintSpec {
254         lint: UnusedUnsafe,
255         desc: "unnecessary use of an `unsafe` block",
256         default: warn
257     }),
258
259     ("unsafe_block",
260      LintSpec {
261         lint: UnsafeBlock,
262         desc: "usage of an `unsafe` block",
263         default: allow
264     }),
265
266     ("attribute_usage",
267      LintSpec {
268         lint: AttributeUsage,
269         desc: "detects bad use of attributes",
270         default: warn
271     }),
272
273     ("unused_variable",
274      LintSpec {
275         lint: UnusedVariable,
276         desc: "detect variables which are not used in any way",
277         default: warn
278     }),
279
280     ("dead_assignment",
281      LintSpec {
282         lint: DeadAssignment,
283         desc: "detect assignments that will never be read",
284         default: warn
285     }),
286
287     ("unnecessary_typecast",
288      LintSpec {
289         lint: UnnecessaryTypecast,
290         desc: "detects unnecessary type casts, that can be removed",
291         default: allow,
292     }),
293
294     ("unused_mut",
295      LintSpec {
296         lint: UnusedMut,
297         desc: "detect mut variables which don't need to be mutable",
298         default: warn
299     }),
300
301     ("unnecessary_allocation",
302      LintSpec {
303         lint: UnnecessaryAllocation,
304         desc: "detects unnecessary allocations that can be eliminated",
305         default: warn
306     }),
307
308     (DEAD_CODE_LINT_STR,
309      LintSpec {
310         lint: DeadCode,
311         desc: "detect piece of code that will never be used",
312         default: warn
313     }),
314
315     ("missing_doc",
316      LintSpec {
317         lint: MissingDoc,
318         desc: "detects missing documentation for public members",
319         default: allow
320     }),
321
322     ("unreachable_code",
323      LintSpec {
324         lint: UnreachableCode,
325         desc: "detects unreachable code",
326         default: warn
327     }),
328
329     ("deprecated",
330      LintSpec {
331         lint: Deprecated,
332         desc: "detects use of #[deprecated] items",
333         default: warn
334     }),
335
336     ("experimental",
337      LintSpec {
338         lint: Experimental,
339         desc: "detects use of #[experimental] items",
340         default: warn
341     }),
342
343     ("unstable",
344      LintSpec {
345         lint: Unstable,
346         desc: "detects use of #[unstable] items (incl. items with no stability attribute)",
347         default: allow
348     }),
349
350     ("warnings",
351      LintSpec {
352         lint: Warnings,
353         desc: "mass-change the level for lints which produce warnings",
354         default: warn
355     }),
356
357     ("unknown_features",
358      LintSpec {
359         lint: UnknownFeatures,
360         desc: "unknown features found in crate-level #[feature] directives",
361         default: deny,
362     }),
363
364     ("unknown_crate_type",
365     LintSpec {
366         lint: UnknownCrateType,
367         desc: "unknown crate type found in #[crate_type] directive",
368         default: deny,
369     }),
370
371     ("unused_must_use",
372     LintSpec {
373         lint: UnusedMustUse,
374         desc: "unused result of a type flagged as #[must_use]",
375         default: warn,
376     }),
377
378     ("unused_result",
379     LintSpec {
380         lint: UnusedResult,
381         desc: "unused result of an expression in a statement",
382         default: allow,
383     }),
384
385      ("default_type_param_usage",
386      LintSpec {
387          lint: DefaultTypeParamUsage,
388          desc: "prevents explicitly setting a type parameter with a default",
389          default: deny,
390      }),
391 ];
392
393 /*
394   Pass names should not contain a '-', as the compiler normalizes
395   '-' to '_' in command-line flags
396  */
397 pub fn get_lint_dict() -> LintDict {
398     let mut map = HashMap::new();
399     for &(k, v) in lint_table.iter() {
400         map.insert(k, v);
401     }
402     return map;
403 }
404
405 struct Context<'a> {
406     // All known lint modes (string versions)
407     dict: @LintDict,
408     // Current levels of each lint warning
409     cur: SmallIntMap<(level, LintSource)>,
410     // context we're checking in (used to access fields like sess)
411     tcx: ty::ctxt,
412     // maps from an expression id that corresponds to a method call to the
413     // details of the method to be invoked
414     method_map: typeck::method_map,
415     // Items exported by the crate; used by the missing_doc lint.
416     exported_items: &'a privacy::ExportedItems,
417     // The id of the current `ast::StructDef` being walked.
418     cur_struct_def_id: ast::NodeId,
419     // Whether some ancestor of the current node was marked
420     // #[doc(hidden)].
421     is_doc_hidden: bool,
422
423     // When recursing into an attributed node of the ast which modifies lint
424     // levels, this stack keeps track of the previous lint levels of whatever
425     // was modified.
426     lint_stack: ~[(Lint, level, LintSource)],
427
428     // id of the last visited negated expression
429     negated_expr_id: ast::NodeId
430 }
431
432 impl<'a> Context<'a> {
433     fn get_level(&self, lint: Lint) -> level {
434         match self.cur.find(&(lint as uint)) {
435           Some(&(lvl, _)) => lvl,
436           None => allow
437         }
438     }
439
440     fn get_source(&self, lint: Lint) -> LintSource {
441         match self.cur.find(&(lint as uint)) {
442           Some(&(_, src)) => src,
443           None => Default
444         }
445     }
446
447     fn set_level(&mut self, lint: Lint, level: level, src: LintSource) {
448         if level == allow {
449             self.cur.remove(&(lint as uint));
450         } else {
451             self.cur.insert(lint as uint, (level, src));
452         }
453     }
454
455     fn lint_to_str(&self, lint: Lint) -> &'static str {
456         for (k, v) in self.dict.iter() {
457             if v.lint == lint {
458                 return *k;
459             }
460         }
461         fail!("unregistered lint {:?}", lint);
462     }
463
464     fn span_lint(&self, lint: Lint, span: Span, msg: &str) {
465         let (level, src) = match self.cur.find(&(lint as uint)) {
466             None => { return }
467             Some(&(warn, src)) => (self.get_level(Warnings), src),
468             Some(&pair) => pair,
469         };
470         if level == allow { return }
471
472         let mut note = None;
473         let msg = match src {
474             Default => {
475                 format!("{}, \\#[{}({})] on by default", msg,
476                     level_to_str(level), self.lint_to_str(lint))
477             },
478             CommandLine => {
479                 format!("{} [-{} {}]", msg,
480                     match level {
481                         warn => 'W', deny => 'D', forbid => 'F',
482                         allow => fail!()
483                     }, self.lint_to_str(lint).replace("_", "-"))
484             },
485             Node(src) => {
486                 note = Some(src);
487                 msg.to_str()
488             }
489         };
490         match level {
491             warn =>          { self.tcx.sess.span_warn(span, msg); }
492             deny | forbid => { self.tcx.sess.span_err(span, msg);  }
493             allow => fail!(),
494         }
495
496         for &span in note.iter() {
497             self.tcx.sess.span_note(span, "lint level defined here");
498         }
499     }
500
501     /**
502      * Merge the lints specified by any lint attributes into the
503      * current lint context, call the provided function, then reset the
504      * lints in effect to their previous state.
505      */
506     fn with_lint_attrs(&mut self,
507                        attrs: &[ast::Attribute],
508                        f: |&mut Context|) {
509         // Parse all of the lint attributes, and then add them all to the
510         // current dictionary of lint information. Along the way, keep a history
511         // of what we changed so we can roll everything back after invoking the
512         // specified closure
513         let mut pushed = 0u;
514         each_lint(self.tcx.sess, attrs, |meta, level, lintname| {
515             match self.dict.find_equiv(&lintname) {
516                 None => {
517                     self.span_lint(
518                         UnrecognizedLint,
519                         meta.span,
520                         format!("unknown `{}` attribute: `{}`",
521                         level_to_str(level), lintname));
522                 }
523                 Some(lint) => {
524                     let lint = lint.lint;
525                     let now = self.get_level(lint);
526                     if now == forbid && level != forbid {
527                         self.tcx.sess.span_err(meta.span,
528                         format!("{}({}) overruled by outer forbid({})",
529                         level_to_str(level),
530                         lintname, lintname));
531                     } else if now != level {
532                         let src = self.get_source(lint);
533                         self.lint_stack.push((lint, now, src));
534                         pushed += 1;
535                         self.set_level(lint, level, Node(meta.span));
536                     }
537                 }
538             }
539             true
540         });
541
542         let old_is_doc_hidden = self.is_doc_hidden;
543         self.is_doc_hidden =
544             self.is_doc_hidden ||
545             attrs.iter()
546                  .any(|attr| {
547                      attr.name().equiv(&("doc")) &&
548                      match attr.meta_item_list() {
549                          None => false,
550                          Some(l) => attr::contains_name(l, "hidden")
551                      }
552                  });
553
554         f(self);
555
556         // rollback
557         self.is_doc_hidden = old_is_doc_hidden;
558         for _ in range(0, pushed) {
559             let (lint, lvl, src) = self.lint_stack.pop().unwrap();
560             self.set_level(lint, lvl, src);
561         }
562     }
563
564     fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
565         let mut v = ast_util::IdVisitor {
566             operation: self,
567             pass_through_items: false,
568             visited_outermost: false,
569         };
570         f(&mut v);
571     }
572 }
573
574 // Check that every lint from the list of attributes satisfies `f`.
575 // Return true if that's the case. Otherwise return false.
576 pub fn each_lint(sess: session::Session,
577                  attrs: &[ast::Attribute],
578                  f: |@ast::MetaItem, level, InternedString| -> bool)
579                  -> bool {
580     let xs = [allow, warn, deny, forbid];
581     for &level in xs.iter() {
582         let level_name = level_to_str(level);
583         for attr in attrs.iter().filter(|m| m.name().equiv(&level_name)) {
584             let meta = attr.node.value;
585             let metas = match meta.node {
586                 ast::MetaList(_, ref metas) => metas,
587                 _ => {
588                     sess.span_err(meta.span, "malformed lint attribute");
589                     continue;
590                 }
591             };
592             for meta in metas.iter() {
593                 match meta.node {
594                     ast::MetaWord(ref lintname) => {
595                         if !f(*meta, level, (*lintname).clone()) {
596                             return false;
597                         }
598                     }
599                     _ => {
600                         sess.span_err(meta.span, "malformed lint attribute");
601                     }
602                 }
603             }
604         }
605     }
606     true
607 }
608
609 // Check from a list of attributes if it contains the appropriate
610 // `#[level(lintname)]` attribute (e.g. `#[allow(dead_code)]).
611 pub fn contains_lint(attrs: &[ast::Attribute],
612                      level: level,
613                      lintname: &'static str)
614                      -> bool {
615     let level_name = level_to_str(level);
616     for attr in attrs.iter().filter(|m| m.name().equiv(&level_name)) {
617         if attr.meta_item_list().is_none() {
618             continue
619         }
620         let list = attr.meta_item_list().unwrap();
621         for meta_item in list.iter() {
622             if meta_item.name().equiv(&lintname) {
623                 return true;
624             }
625         }
626     }
627     false
628 }
629
630 fn check_while_true_expr(cx: &Context, e: &ast::Expr) {
631     match e.node {
632         ast::ExprWhile(cond, _) => {
633             match cond.node {
634                 ast::ExprLit(lit) => {
635                     match lit.node {
636                         ast::LitBool(true) => {
637                             cx.span_lint(WhileTrue,
638                                          e.span,
639                                          "denote infinite loops with loop \
640                                           { ... }");
641                         }
642                         _ => {}
643                     }
644                 }
645                 _ => ()
646             }
647         }
648         _ => ()
649     }
650 }
651 impl<'a> AstConv for Context<'a>{
652     fn tcx(&self) -> ty::ctxt { self.tcx }
653
654     fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
655         ty::lookup_item_type(self.tcx, id)
656     }
657
658     fn get_trait_def(&self, id: ast::DefId) -> @ty::TraitDef {
659         ty::lookup_trait_def(self.tcx, id)
660     }
661
662     fn ty_infer(&self, _span: Span) -> ty::t {
663         let infcx: @infer::InferCtxt = infer::new_infer_ctxt(self.tcx);
664         infcx.next_ty_var()
665     }
666 }
667
668
669 fn check_unused_casts(cx: &Context, e: &ast::Expr) {
670     return match e.node {
671         ast::ExprCast(expr, ty) => {
672             let infcx: @infer::InferCtxt = infer::new_infer_ctxt(cx.tcx);
673             let t_t = ast_ty_to_ty(cx, &infcx, ty);
674             if  ty::get(ty::expr_ty(cx.tcx, expr)).sty == ty::get(t_t).sty {
675                 cx.span_lint(UnnecessaryTypecast, ty.span,
676                              "unnecessary type cast");
677             }
678         }
679         _ => ()
680     };
681 }
682
683 fn check_type_limits(cx: &Context, e: &ast::Expr) {
684     return match e.node {
685         ast::ExprBinary(_, binop, l, r) => {
686             if is_comparison(binop) && !check_limits(cx.tcx, binop, l, r) {
687                 cx.span_lint(TypeLimits, e.span,
688                              "comparison is useless due to type limits");
689             }
690         },
691         ast::ExprLit(lit) => {
692             match ty::get(ty::expr_ty(cx.tcx, e)).sty {
693                 ty::ty_int(t) => {
694                     let int_type = if t == ast::TyI {
695                         cx.tcx.sess.targ_cfg.int_type
696                     } else { t };
697                     let (min, max) = int_ty_range(int_type);
698                     let mut lit_val: i64 = match lit.node {
699                         ast::LitInt(v, _) => v,
700                         ast::LitUint(v, _) => v as i64,
701                         ast::LitIntUnsuffixed(v) => v,
702                         _ => fail!()
703                     };
704                     if cx.negated_expr_id == e.id {
705                         lit_val *= -1;
706                     }
707                     if  lit_val < min || lit_val > max {
708                         cx.span_lint(TypeOverflow, e.span,
709                                      "literal out of range for its type");
710                     }
711                 },
712                 ty::ty_uint(t) => {
713                     let uint_type = if t == ast::TyU {
714                         cx.tcx.sess.targ_cfg.uint_type
715                     } else { t };
716                     let (min, max) = uint_ty_range(uint_type);
717                     let lit_val: u64 = match lit.node {
718                         ast::LitInt(v, _) => v as u64,
719                         ast::LitUint(v, _) => v,
720                         ast::LitIntUnsuffixed(v) => v as u64,
721                         _ => fail!()
722                     };
723                     if  lit_val < min || lit_val > max {
724                         cx.span_lint(TypeOverflow, e.span,
725                                      "literal out of range for its type");
726                     }
727                 },
728
729                 _ => ()
730             };
731         },
732         _ => ()
733     };
734
735     fn is_valid<T:cmp::Ord>(binop: ast::BinOp, v: T,
736                             min: T, max: T) -> bool {
737         match binop {
738             ast::BiLt => v <= max,
739             ast::BiLe => v < max,
740             ast::BiGt => v >= min,
741             ast::BiGe => v > min,
742             ast::BiEq | ast::BiNe => v >= min && v <= max,
743             _ => fail!()
744         }
745     }
746
747     fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
748         match binop {
749             ast::BiLt => ast::BiGt,
750             ast::BiLe => ast::BiGe,
751             ast::BiGt => ast::BiLt,
752             ast::BiGe => ast::BiLe,
753             _ => binop
754         }
755     }
756
757     // for int & uint, be conservative with the warnings, so that the
758     // warnings are consistent between 32- and 64-bit platforms
759     fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
760         match int_ty {
761             ast::TyI =>    (i64::MIN,        i64::MAX),
762             ast::TyI8 =>   (i8::MIN  as i64, i8::MAX  as i64),
763             ast::TyI16 =>  (i16::MIN as i64, i16::MAX as i64),
764             ast::TyI32 =>  (i32::MIN as i64, i32::MAX as i64),
765             ast::TyI64 =>  (i64::MIN,        i64::MAX)
766         }
767     }
768
769     fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
770         match uint_ty {
771             ast::TyU =>   (u64::MIN,         u64::MAX),
772             ast::TyU8 =>  (u8::MIN   as u64, u8::MAX   as u64),
773             ast::TyU16 => (u16::MIN  as u64, u16::MAX  as u64),
774             ast::TyU32 => (u32::MIN  as u64, u32::MAX  as u64),
775             ast::TyU64 => (u64::MIN,         u64::MAX)
776         }
777     }
778
779     fn check_limits(tcx: ty::ctxt, binop: ast::BinOp,
780                     l: &ast::Expr, r: &ast::Expr) -> bool {
781         let (lit, expr, swap) = match (&l.node, &r.node) {
782             (&ast::ExprLit(_), _) => (l, r, true),
783             (_, &ast::ExprLit(_)) => (r, l, false),
784             _ => return true
785         };
786         // Normalize the binop so that the literal is always on the RHS in
787         // the comparison
788         let norm_binop = if swap { rev_binop(binop) } else { binop };
789         match ty::get(ty::expr_ty(tcx, expr)).sty {
790             ty::ty_int(int_ty) => {
791                 let (min, max) = int_ty_range(int_ty);
792                 let lit_val: i64 = match lit.node {
793                     ast::ExprLit(li) => match li.node {
794                         ast::LitInt(v, _) => v,
795                         ast::LitUint(v, _) => v as i64,
796                         ast::LitIntUnsuffixed(v) => v,
797                         _ => return true
798                     },
799                     _ => fail!()
800                 };
801                 is_valid(norm_binop, lit_val, min, max)
802             }
803             ty::ty_uint(uint_ty) => {
804                 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
805                 let lit_val: u64 = match lit.node {
806                     ast::ExprLit(li) => match li.node {
807                         ast::LitInt(v, _) => v as u64,
808                         ast::LitUint(v, _) => v,
809                         ast::LitIntUnsuffixed(v) => v as u64,
810                         _ => return true
811                     },
812                     _ => fail!()
813                 };
814                 is_valid(norm_binop, lit_val, min, max)
815             }
816             _ => true
817         }
818     }
819
820     fn is_comparison(binop: ast::BinOp) -> bool {
821         match binop {
822             ast::BiEq | ast::BiLt | ast::BiLe |
823             ast::BiNe | ast::BiGe | ast::BiGt => true,
824             _ => false
825         }
826     }
827 }
828
829 fn check_item_ctypes(cx: &Context, it: &ast::Item) {
830     fn check_ty(cx: &Context, ty: &ast::Ty) {
831         match ty.node {
832             ast::TyPath(_, _, id) => {
833                 let def_map = cx.tcx.def_map.borrow();
834                 match def_map.get().get_copy(&id) {
835                     ast::DefPrimTy(ast::TyInt(ast::TyI)) => {
836                         cx.span_lint(CTypes, ty.span,
837                                 "found rust type `int` in foreign module, while \
838                                 libc::c_int or libc::c_long should be used");
839                     }
840                     ast::DefPrimTy(ast::TyUint(ast::TyU)) => {
841                         cx.span_lint(CTypes, ty.span,
842                                 "found rust type `uint` in foreign module, while \
843                                 libc::c_uint or libc::c_ulong should be used");
844                     }
845                     ast::DefTy(def_id) => {
846                         if !adt::is_ffi_safe(cx.tcx, def_id) {
847                             cx.span_lint(CTypes, ty.span,
848                                          "found enum type without foreign-function-safe \
849                                           representation annotation in foreign module");
850                             // hmm... this message could be more helpful
851                         }
852                     }
853                     _ => ()
854                 }
855             }
856             ast::TyPtr(ref mt) => { check_ty(cx, mt.ty) }
857             _ => {}
858         }
859     }
860
861     fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
862         for input in decl.inputs.iter() {
863             check_ty(cx, input.ty);
864         }
865         check_ty(cx, decl.output)
866     }
867
868     match it.node {
869       ast::ItemForeignMod(ref nmod) if !nmod.abis.is_intrinsic() => {
870         for ni in nmod.items.iter() {
871             match ni.node {
872                 ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, decl),
873                 ast::ForeignItemStatic(t, _) => check_ty(cx, t)
874             }
875         }
876       }
877       _ => {/* nothing to do */ }
878     }
879 }
880
881 fn check_heap_type(cx: &Context, span: Span, ty: ty::t) {
882     let xs = [ManagedHeapMemory, OwnedHeapMemory, HeapMemory];
883     for &lint in xs.iter() {
884         if cx.get_level(lint) == allow { continue }
885
886         let mut n_box = 0;
887         let mut n_uniq = 0;
888         ty::fold_ty(cx.tcx, ty, |t| {
889             match ty::get(t).sty {
890                 ty::ty_box(_) |
891                 ty::ty_vec(_, ty::vstore_box) |
892                 ty::ty_trait(_, _, ty::BoxTraitStore, _, _) => {
893                     n_box += 1;
894                 }
895                 ty::ty_uniq(_) | ty::ty_str(ty::vstore_uniq) |
896                 ty::ty_vec(_, ty::vstore_uniq) |
897                 ty::ty_trait(_, _, ty::UniqTraitStore, _, _) => {
898                     n_uniq += 1;
899                 }
900                 ty::ty_closure(ref c) if c.sigil == ast::OwnedSigil => {
901                     n_uniq += 1;
902                 }
903
904                 _ => ()
905             };
906             t
907         });
908
909         if n_uniq > 0 && lint != ManagedHeapMemory {
910             let s = ty_to_str(cx.tcx, ty);
911             let m = format!("type uses owned (~ type) pointers: {}", s);
912             cx.span_lint(lint, span, m);
913         }
914
915         if n_box > 0 && lint != OwnedHeapMemory {
916             let s = ty_to_str(cx.tcx, ty);
917             let m = format!("type uses managed (@ type) pointers: {}", s);
918             cx.span_lint(lint, span, m);
919         }
920     }
921 }
922
923 fn check_heap_item(cx: &Context, it: &ast::Item) {
924     match it.node {
925         ast::ItemFn(..) |
926         ast::ItemTy(..) |
927         ast::ItemEnum(..) |
928         ast::ItemStruct(..) => check_heap_type(cx, it.span,
929                                                ty::node_id_to_type(cx.tcx,
930                                                                    it.id)),
931         _ => ()
932     }
933
934     // If it's a struct, we also have to check the fields' types
935     match it.node {
936         ast::ItemStruct(struct_def, _) => {
937             for struct_field in struct_def.fields.iter() {
938                 check_heap_type(cx, struct_field.span,
939                                 ty::node_id_to_type(cx.tcx,
940                                                     struct_field.node.id));
941             }
942         }
943         _ => ()
944     }
945 }
946
947 static crate_attrs: &'static [&'static str] = &[
948     "crate_type", "feature", "no_uv", "no_main", "no_std", "crate_id",
949     "desc", "comment", "license", "copyright", // not used in rustc now
950 ];
951
952
953 static obsolete_attrs: &'static [(&'static str, &'static str)] = &[
954     ("abi", "Use `extern \"abi\" fn` instead"),
955     ("auto_encode", "Use `#[deriving(Encodable)]` instead"),
956     ("auto_decode", "Use `#[deriving(Decodable)]` instead"),
957     ("fast_ffi", "Remove it"),
958     ("fixed_stack_segment", "Remove it"),
959     ("rust_stack", "Remove it"),
960 ];
961
962 static other_attrs: &'static [&'static str] = &[
963     // item-level
964     "address_insignificant", // can be crate-level too
965     "thread_local", // for statics
966     "allow", "deny", "forbid", "warn", // lint options
967     "deprecated", "experimental", "unstable", "stable", "locked", "frozen", //item stability
968     "crate_map", "cfg", "doc", "export_name", "link_section",
969     "no_mangle", "static_assert", "unsafe_no_drop_flag", "packed",
970     "simd", "repr", "deriving", "unsafe_destructor", "link", "phase",
971     "macro_export", "must_use",
972
973     //mod-level
974     "path", "link_name", "link_args", "nolink", "macro_escape", "no_implicit_prelude",
975
976     // fn-level
977     "test", "bench", "should_fail", "ignore", "inline", "lang", "main", "start",
978     "no_split_stack", "cold", "macro_registrar",
979
980     // internal attribute: bypass privacy inside items
981     "!resolve_unexported",
982 ];
983
984 fn check_crate_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
985
986     for attr in attrs.iter() {
987         let name = attr.node.value.name();
988         let mut iter = crate_attrs.iter().chain(other_attrs.iter());
989         if !iter.any(|other_attr| { name.equiv(other_attr) }) {
990             cx.span_lint(AttributeUsage, attr.span, "unknown crate attribute");
991         }
992         if name.equiv(& &"link") {
993             cx.tcx.sess.span_err(attr.span,
994                                  "obsolete crate `link` attribute");
995             cx.tcx.sess.note("the link attribute has been superceded by the crate_id \
996                              attribute, which has the format `#[crate_id = \"name#version\"]`");
997         }
998     }
999 }
1000
1001 fn check_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
1002     // check if element has crate-level, obsolete, or any unknown attributes.
1003
1004     for attr in attrs.iter() {
1005         let name = attr.node.value.name();
1006         for crate_attr in crate_attrs.iter() {
1007             if name.equiv(crate_attr) {
1008                 let msg = match attr.node.style {
1009                     ast::AttrOuter => "crate-level attribute should be an inner attribute: \
1010                                        add semicolon at end",
1011                     ast::AttrInner => "crate-level attribute should be in the root module",
1012                 };
1013                 cx.span_lint(AttributeUsage, attr.span, msg);
1014                 return;
1015             }
1016         }
1017
1018         for &(obs_attr, obs_alter) in obsolete_attrs.iter() {
1019             if name.equiv(&obs_attr) {
1020                 cx.span_lint(AttributeUsage, attr.span,
1021                              format!("obsolete attribute: {:s}", obs_alter));
1022                 return;
1023             }
1024         }
1025
1026         if !other_attrs.iter().any(|other_attr| { name.equiv(other_attr) }) {
1027             cx.span_lint(AttributeUsage, attr.span, "unknown attribute");
1028         }
1029     }
1030 }
1031
1032 fn check_heap_expr(cx: &Context, e: &ast::Expr) {
1033     let ty = ty::expr_ty(cx.tcx, e);
1034     check_heap_type(cx, e.span, ty);
1035 }
1036
1037 fn check_path_statement(cx: &Context, s: &ast::Stmt) {
1038     match s.node {
1039         ast::StmtSemi(expr, _) => {
1040             match expr.node {
1041                 ast::ExprPath(_) => {
1042                     cx.span_lint(PathStatement,
1043                                  s.span,
1044                                  "path statement with no effect");
1045                 }
1046                 _ => {}
1047             }
1048         }
1049         _ => ()
1050     }
1051 }
1052
1053 fn check_unused_result(cx: &Context, s: &ast::Stmt) {
1054     let expr = match s.node {
1055         ast::StmtSemi(expr, _) => expr,
1056         _ => return
1057     };
1058     let t = ty::expr_ty(cx.tcx, expr);
1059     match ty::get(t).sty {
1060         ty::ty_nil | ty::ty_bot | ty::ty_bool => return,
1061         _ => {}
1062     }
1063     match expr.node {
1064         ast::ExprRet(..) => return,
1065         _ => {}
1066     }
1067
1068     let t = ty::expr_ty(cx.tcx, expr);
1069     let mut warned = false;
1070     match ty::get(t).sty {
1071         ty::ty_struct(did, _) |
1072         ty::ty_enum(did, _) => {
1073             if ast_util::is_local(did) {
1074                 match cx.tcx.items.get(did.node) {
1075                     ast_map::NodeItem(it, _) => {
1076                         if attr::contains_name(it.attrs, "must_use") {
1077                             cx.span_lint(UnusedMustUse, s.span,
1078                                          "unused result which must be used");
1079                             warned = true;
1080                         }
1081                     }
1082                     _ => {}
1083                 }
1084             } else {
1085                 csearch::get_item_attrs(cx.tcx.sess.cstore, did, |attrs| {
1086                     if attr::contains_name(attrs, "must_use") {
1087                         cx.span_lint(UnusedMustUse, s.span,
1088                                      "unused result which must be used");
1089                         warned = true;
1090                     }
1091                 });
1092             }
1093         }
1094         _ => {}
1095     }
1096     if !warned {
1097         cx.span_lint(UnusedResult, s.span, "unused result");
1098     }
1099 }
1100
1101 fn check_item_non_camel_case_types(cx: &Context, it: &ast::Item) {
1102     fn is_camel_case(cx: ty::ctxt, ident: ast::Ident) -> bool {
1103         let ident = cx.sess.str_of(ident);
1104         assert!(!ident.is_empty());
1105         let ident = ident.trim_chars(&'_');
1106
1107         // start with a non-lowercase letter rather than non-uppercase
1108         // ones (some scripts don't have a concept of upper/lowercase)
1109         !ident.char_at(0).is_lowercase() &&
1110             !ident.contains_char('_')
1111     }
1112
1113     fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1114         if !is_camel_case(cx.tcx, ident) {
1115             cx.span_lint(
1116                 NonCamelCaseTypes, span,
1117                 format!("{} `{}` should have a camel case identifier",
1118                     sort, cx.tcx.sess.str_of(ident)));
1119         }
1120     }
1121
1122     match it.node {
1123         ast::ItemTy(..) | ast::ItemStruct(..) => {
1124             check_case(cx, "type", it.ident, it.span)
1125         }
1126         ast::ItemTrait(..) => {
1127             check_case(cx, "trait", it.ident, it.span)
1128         }
1129         ast::ItemEnum(ref enum_definition, _) => {
1130             check_case(cx, "type", it.ident, it.span);
1131             for variant in enum_definition.variants.iter() {
1132                 check_case(cx, "variant", variant.node.name, variant.span);
1133             }
1134         }
1135         _ => ()
1136     }
1137 }
1138
1139 fn check_item_non_uppercase_statics(cx: &Context, it: &ast::Item) {
1140     match it.node {
1141         // only check static constants
1142         ast::ItemStatic(_, ast::MutImmutable, _) => {
1143             let s = cx.tcx.sess.str_of(it.ident);
1144             // check for lowercase letters rather than non-uppercase
1145             // ones (some scripts don't have a concept of
1146             // upper/lowercase)
1147             if s.chars().any(|c| c.is_lowercase()) {
1148                 cx.span_lint(NonUppercaseStatics, it.span,
1149                              "static constant should have an uppercase identifier");
1150             }
1151         }
1152         _ => {}
1153     }
1154 }
1155
1156 fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) {
1157     // Lint for constants that look like binding identifiers (#7526)
1158     let def_map = cx.tcx.def_map.borrow();
1159     match (&p.node, def_map.get().find(&p.id)) {
1160         (&ast::PatIdent(_, ref path, _), Some(&ast::DefStatic(_, false))) => {
1161             // last identifier alone is right choice for this lint.
1162             let ident = path.segments.last().unwrap().identifier;
1163             let s = cx.tcx.sess.str_of(ident);
1164             if s.chars().any(|c| c.is_lowercase()) {
1165                 cx.span_lint(NonUppercasePatternStatics, path.span,
1166                              "static constant in pattern should be all caps");
1167             }
1168         }
1169         _ => {}
1170     }
1171 }
1172
1173 fn check_unnecessary_parens(cx: &Context, e: &ast::Expr) {
1174     let (value, msg) = match e.node {
1175         ast::ExprIf(cond, _, _) => (cond, "`if` condition"),
1176         ast::ExprWhile(cond, _) => (cond, "`while` condition"),
1177         ast::ExprMatch(head, _) => (head, "`match` head expression"),
1178         ast::ExprRet(Some(value)) => (value, "`return` value"),
1179         _ => return
1180     };
1181
1182     match value.node {
1183         ast::ExprParen(_) => {
1184             cx.span_lint(UnnecessaryParens, value.span,
1185                          format!("unnecessary parentheses around {}", msg))
1186         }
1187         _ => {}
1188     }
1189 }
1190
1191 fn check_unused_unsafe(cx: &Context, e: &ast::Expr) {
1192     match e.node {
1193         // Don't warn about generated blocks, that'll just pollute the output.
1194         ast::ExprBlock(ref blk) => {
1195             let used_unsafe = cx.tcx.used_unsafe.borrow();
1196             if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1197                 !used_unsafe.get().contains(&blk.id) {
1198                 cx.span_lint(UnusedUnsafe, blk.span,
1199                              "unnecessary `unsafe` block");
1200             }
1201         }
1202         _ => ()
1203     }
1204 }
1205
1206 fn check_unsafe_block(cx: &Context, e: &ast::Expr) {
1207     match e.node {
1208         // Don't warn about generated blocks, that'll just pollute the output.
1209         ast::ExprBlock(ref blk) if blk.rules == ast::UnsafeBlock(ast::UserProvided) => {
1210             cx.span_lint(UnsafeBlock, blk.span, "usage of an `unsafe` block");
1211         }
1212         _ => ()
1213     }
1214 }
1215
1216 fn check_unused_mut_pat(cx: &Context, p: &ast::Pat) {
1217     match p.node {
1218         ast::PatIdent(ast::BindByValue(ast::MutMutable),
1219                       ref path, _) if pat_util::pat_is_binding(cx.tcx.def_map, p)=> {
1220             // `let mut _a = 1;` doesn't need a warning.
1221             let initial_underscore = match path.segments {
1222                 [ast::PathSegment { identifier: id, .. }] => {
1223                     cx.tcx.sess.str_of(id).starts_with("_")
1224                 }
1225                 _ => {
1226                     cx.tcx.sess.span_bug(p.span,
1227                                          "mutable binding that doesn't \
1228                                          consist of exactly one segment");
1229                 }
1230             };
1231
1232             let used_mut_nodes = cx.tcx.used_mut_nodes.borrow();
1233             if !initial_underscore && !used_mut_nodes.get().contains(&p.id) {
1234                 cx.span_lint(UnusedMut, p.span,
1235                              "variable does not need to be mutable");
1236             }
1237         }
1238         _ => ()
1239     }
1240 }
1241
1242 enum Allocation {
1243     VectorAllocation,
1244     BoxAllocation
1245 }
1246
1247 fn check_unnecessary_allocation(cx: &Context, e: &ast::Expr) {
1248     // Warn if string and vector literals with sigils, or boxing expressions,
1249     // are immediately borrowed.
1250     let allocation = match e.node {
1251         ast::ExprVstore(e2, ast::ExprVstoreUniq) |
1252         ast::ExprVstore(e2, ast::ExprVstoreBox) => {
1253             match e2.node {
1254                 ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
1255                     VectorAllocation
1256                 }
1257                 ast::ExprVec(..) => VectorAllocation,
1258                 _ => return
1259             }
1260         }
1261         ast::ExprUnary(_, ast::UnUniq, _) |
1262         ast::ExprUnary(_, ast::UnBox, _) => BoxAllocation,
1263
1264         _ => return
1265     };
1266
1267     let report = |msg| {
1268         cx.span_lint(UnnecessaryAllocation, e.span, msg);
1269     };
1270
1271     let adjustment = {
1272         let adjustments = cx.tcx.adjustments.borrow();
1273         adjustments.get().find_copy(&e.id)
1274     };
1275     match adjustment {
1276         Some(adjustment) => {
1277             match *adjustment {
1278                 ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => {
1279                     match (allocation, autoref) {
1280                         (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
1281                             report("unnecessary allocation, the sigil can be \
1282                                     removed");
1283                         }
1284                         (BoxAllocation,
1285                          Some(ty::AutoPtr(_, ast::MutImmutable))) => {
1286                             report("unnecessary allocation, use & instead");
1287                         }
1288                         (BoxAllocation,
1289                          Some(ty::AutoPtr(_, ast::MutMutable))) => {
1290                             report("unnecessary allocation, use &mut \
1291                                     instead");
1292                         }
1293                         _ => ()
1294                     }
1295                 }
1296                 _ => {}
1297             }
1298         }
1299
1300         _ => ()
1301     }
1302 }
1303
1304 fn check_missing_doc_attrs(cx: &Context,
1305                            id: Option<ast::NodeId>,
1306                            attrs: &[ast::Attribute],
1307                            sp: Span,
1308                            desc: &'static str) {
1309     // If we're building a test harness, then warning about
1310     // documentation is probably not really relevant right now.
1311     if cx.tcx.sess.opts.test { return }
1312
1313     // `#[doc(hidden)]` disables missing_doc check.
1314     if cx.is_doc_hidden { return }
1315
1316     // Only check publicly-visible items, using the result from the privacy pass. It's an option so
1317     // the crate root can also use this function (it doesn't have a NodeId).
1318     match id {
1319         Some(ref id) if !cx.exported_items.contains(id) => return,
1320         _ => ()
1321     }
1322
1323     let has_doc = attrs.iter().any(|a| {
1324         match a.node.value.node {
1325             ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
1326             _ => false
1327         }
1328     });
1329     if !has_doc {
1330         cx.span_lint(MissingDoc, sp,
1331                      format!("missing documentation for {}", desc));
1332     }
1333 }
1334
1335 fn check_missing_doc_item(cx: &Context, it: &ast::Item) {
1336     let desc = match it.node {
1337         ast::ItemFn(..) => "a function",
1338         ast::ItemMod(..) => "a module",
1339         ast::ItemEnum(..) => "an enum",
1340         ast::ItemStruct(..) => "a struct",
1341         ast::ItemTrait(..) => "a trait",
1342         _ => return
1343     };
1344     check_missing_doc_attrs(cx, Some(it.id), it.attrs, it.span, desc);
1345 }
1346
1347 fn check_missing_doc_method(cx: &Context, m: &ast::Method) {
1348     let did = ast::DefId {
1349         crate: ast::LOCAL_CRATE,
1350         node: m.id
1351     };
1352
1353     let method_opt;
1354     {
1355         let methods = cx.tcx.methods.borrow();
1356         method_opt = methods.get().find(&did).map(|method| *method);
1357     }
1358
1359     match method_opt {
1360         None => cx.tcx.sess.span_bug(m.span, "missing method descriptor?!"),
1361         Some(md) => {
1362             match md.container {
1363                 // Always check default methods defined on traits.
1364                 ty::TraitContainer(..) => {}
1365                 // For methods defined on impls, it depends on whether
1366                 // it is an implementation for a trait or is a plain
1367                 // impl.
1368                 ty::ImplContainer(cid) => {
1369                     match ty::impl_trait_ref(cx.tcx, cid) {
1370                         Some(..) => return, // impl for trait: don't doc
1371                         None => {} // plain impl: doc according to privacy
1372                     }
1373                 }
1374             }
1375         }
1376     }
1377     check_missing_doc_attrs(cx, Some(m.id), m.attrs, m.span, "a method");
1378 }
1379
1380 fn check_missing_doc_ty_method(cx: &Context, tm: &ast::TypeMethod) {
1381     check_missing_doc_attrs(cx, Some(tm.id), tm.attrs, tm.span, "a type method");
1382 }
1383
1384 fn check_missing_doc_struct_field(cx: &Context, sf: &ast::StructField) {
1385     match sf.node.kind {
1386         ast::NamedField(_, vis) if vis != ast::Private =>
1387             check_missing_doc_attrs(cx, Some(cx.cur_struct_def_id), sf.node.attrs,
1388                                     sf.span, "a struct field"),
1389         _ => {}
1390     }
1391 }
1392
1393 fn check_missing_doc_variant(cx: &Context, v: &ast::Variant) {
1394     check_missing_doc_attrs(cx, Some(v.node.id), v.node.attrs, v.span, "a variant");
1395 }
1396
1397 /// Checks for use of items with #[deprecated], #[experimental] and
1398 /// #[unstable] (or none of them) attributes.
1399 fn check_stability(cx: &Context, e: &ast::Expr) {
1400     let id = match e.node {
1401         ast::ExprPath(..) | ast::ExprStruct(..) => {
1402             let def_map = cx.tcx.def_map.borrow();
1403             match def_map.get().find(&e.id) {
1404                 Some(&def) => ast_util::def_id_of_def(def),
1405                 None => return
1406             }
1407         }
1408         ast::ExprMethodCall(..) => {
1409             let method_map = cx.method_map.borrow();
1410             match method_map.get().find(&e.id) {
1411                 Some(&typeck::method_map_entry { origin, .. }) => {
1412                     match origin {
1413                         typeck::method_static(def_id) => {
1414                             // If this implements a trait method, get def_id
1415                             // of the method inside trait definition.
1416                             // Otherwise, use the current def_id (which refers
1417                             // to the method inside impl).
1418                             ty::trait_method_of_method(
1419                                 cx.tcx, def_id).unwrap_or(def_id)
1420                         }
1421                         typeck::method_param(typeck::method_param {
1422                             trait_id: trait_id,
1423                             method_num: index,
1424                             ..
1425                         })
1426                         | typeck::method_object(typeck::method_object {
1427                             trait_id: trait_id,
1428                             method_num: index,
1429                             ..
1430                         }) => ty::trait_method(cx.tcx, trait_id, index).def_id
1431                     }
1432                 }
1433                 None => return
1434             }
1435         }
1436         _ => return
1437     };
1438
1439     let stability = if ast_util::is_local(id) {
1440         // this crate
1441         match cx.tcx.items.find(id.node) {
1442             Some(ast_node) => {
1443                 let s = ast_node.with_attrs(|attrs| {
1444                     attrs.map(|a| {
1445                         attr::find_stability(a.iter().map(|a| a.meta()))
1446                     })
1447                 });
1448                 match s {
1449                     Some(s) => s,
1450
1451                     // no possibility of having attributes
1452                     // (e.g. it's a local variable), so just
1453                     // ignore it.
1454                     None => return
1455                 }
1456             }
1457             _ => cx.tcx.sess.span_bug(e.span,
1458                                       format!("handle_def: {:?} not found", id))
1459         }
1460     } else {
1461         // cross-crate
1462
1463         let mut s = None;
1464         // run through all the attributes and take the first
1465         // stability one.
1466         csearch::get_item_attrs(cx.tcx.cstore, id, |meta_items| {
1467             if s.is_none() {
1468                 s = attr::find_stability(meta_items.move_iter())
1469             }
1470         });
1471         s
1472     };
1473
1474     let (lint, label) = match stability {
1475         // no stability attributes == Unstable
1476         None => (Unstable, "unmarked"),
1477         Some(attr::Stability { level: attr::Unstable, .. }) =>
1478                 (Unstable, "unstable"),
1479         Some(attr::Stability { level: attr::Experimental, .. }) =>
1480                 (Experimental, "experimental"),
1481         Some(attr::Stability { level: attr::Deprecated, .. }) =>
1482                 (Deprecated, "deprecated"),
1483         _ => return
1484     };
1485
1486     let msg = match stability {
1487         Some(attr::Stability { text: Some(ref s), .. }) => {
1488             format!("use of {} item: {}", label, *s)
1489         }
1490         _ => format!("use of {} item", label)
1491     };
1492
1493     cx.span_lint(lint, e.span, msg);
1494 }
1495
1496 impl<'a> Visitor<()> for Context<'a> {
1497     fn visit_item(&mut self, it: &ast::Item, _: ()) {
1498         self.with_lint_attrs(it.attrs, |cx| {
1499             check_item_ctypes(cx, it);
1500             check_item_non_camel_case_types(cx, it);
1501             check_item_non_uppercase_statics(cx, it);
1502             check_heap_item(cx, it);
1503             check_missing_doc_item(cx, it);
1504             check_attrs_usage(cx, it.attrs);
1505
1506             cx.visit_ids(|v| v.visit_item(it, ()));
1507
1508             visit::walk_item(cx, it, ());
1509         })
1510     }
1511
1512     fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
1513         self.with_lint_attrs(it.attrs, |cx| {
1514             check_attrs_usage(cx, it.attrs);
1515             visit::walk_foreign_item(cx, it, ());
1516         })
1517     }
1518
1519     fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
1520         self.with_lint_attrs(i.attrs, |cx| {
1521             check_attrs_usage(cx, i.attrs);
1522             visit::walk_view_item(cx, i, ());
1523         })
1524     }
1525
1526     fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
1527         check_pat_non_uppercase_statics(self, p);
1528         check_unused_mut_pat(self, p);
1529
1530         visit::walk_pat(self, p, ());
1531     }
1532
1533     fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
1534         match e.node {
1535             ast::ExprUnary(_, ast::UnNeg, expr) => {
1536                 // propagate negation, if the negation itself isn't negated
1537                 if self.negated_expr_id != e.id {
1538                     self.negated_expr_id = expr.id;
1539                 }
1540             },
1541             ast::ExprParen(expr) => if self.negated_expr_id == e.id {
1542                 self.negated_expr_id = expr.id
1543             },
1544             _ => ()
1545         };
1546
1547         check_while_true_expr(self, e);
1548         check_stability(self, e);
1549         check_unnecessary_parens(self, e);
1550         check_unused_unsafe(self, e);
1551         check_unsafe_block(self, e);
1552         check_unnecessary_allocation(self, e);
1553         check_heap_expr(self, e);
1554
1555         check_type_limits(self, e);
1556         check_unused_casts(self, e);
1557
1558         visit::walk_expr(self, e, ());
1559     }
1560
1561     fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
1562         check_path_statement(self, s);
1563         check_unused_result(self, s);
1564
1565         visit::walk_stmt(self, s, ());
1566     }
1567
1568     fn visit_fn(&mut self, fk: &visit::FnKind, decl: &ast::FnDecl,
1569                 body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
1570         let recurse = |this: &mut Context| {
1571             visit::walk_fn(this, fk, decl, body, span, id, ());
1572         };
1573
1574         match *fk {
1575             visit::FkMethod(_, _, m) => {
1576                 self.with_lint_attrs(m.attrs, |cx| {
1577                     check_missing_doc_method(cx, m);
1578                     check_attrs_usage(cx, m.attrs);
1579
1580                     cx.visit_ids(|v| {
1581                         v.visit_fn(fk, decl, body, span, id, ());
1582                     });
1583                     recurse(cx);
1584                 })
1585             }
1586             _ => recurse(self),
1587         }
1588     }
1589
1590
1591     fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
1592         self.with_lint_attrs(t.attrs, |cx| {
1593             check_missing_doc_ty_method(cx, t);
1594             check_attrs_usage(cx, t.attrs);
1595
1596             visit::walk_ty_method(cx, t, ());
1597         })
1598     }
1599
1600     fn visit_struct_def(&mut self,
1601                         s: &ast::StructDef,
1602                         i: ast::Ident,
1603                         g: &ast::Generics,
1604                         id: ast::NodeId,
1605                         _: ()) {
1606         let old_id = self.cur_struct_def_id;
1607         self.cur_struct_def_id = id;
1608         visit::walk_struct_def(self, s, i, g, id, ());
1609         self.cur_struct_def_id = old_id;
1610     }
1611
1612     fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
1613         self.with_lint_attrs(s.node.attrs, |cx| {
1614             check_missing_doc_struct_field(cx, s);
1615             check_attrs_usage(cx, s.node.attrs);
1616
1617             visit::walk_struct_field(cx, s, ());
1618         })
1619     }
1620
1621     fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
1622         self.with_lint_attrs(v.node.attrs, |cx| {
1623             check_missing_doc_variant(cx, v);
1624             check_attrs_usage(cx, v.node.attrs);
1625
1626             visit::walk_variant(cx, v, g, ());
1627         })
1628     }
1629
1630     // FIXME(#10894) should continue recursing
1631     fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {}
1632 }
1633
1634 impl<'a> IdVisitingOperation for Context<'a> {
1635     fn visit_id(&self, id: ast::NodeId) {
1636         let mut lints = self.tcx.sess.lints.borrow_mut();
1637         match lints.get().pop(&id) {
1638             None => {}
1639             Some(l) => {
1640                 for (lint, span, msg) in l.move_iter() {
1641                     self.span_lint(lint, span, msg)
1642                 }
1643             }
1644         }
1645     }
1646 }
1647
1648 pub fn check_crate(tcx: ty::ctxt,
1649                    method_map: typeck::method_map,
1650                    exported_items: &privacy::ExportedItems,
1651                    crate: &ast::Crate) {
1652     let mut cx = Context {
1653         dict: @get_lint_dict(),
1654         cur: SmallIntMap::new(),
1655         tcx: tcx,
1656         method_map: method_map,
1657         exported_items: exported_items,
1658         cur_struct_def_id: -1,
1659         is_doc_hidden: false,
1660         lint_stack: ~[],
1661         negated_expr_id: -1
1662     };
1663
1664     // Install default lint levels, followed by the command line levels, and
1665     // then actually visit the whole crate.
1666     for (_, spec) in cx.dict.iter() {
1667         cx.set_level(spec.lint, spec.default, Default);
1668     }
1669     for &(lint, level) in tcx.sess.opts.lint_opts.iter() {
1670         cx.set_level(lint, level, CommandLine);
1671     }
1672     cx.with_lint_attrs(crate.attrs, |cx| {
1673         cx.visit_id(ast::CRATE_NODE_ID);
1674         cx.visit_ids(|v| {
1675             v.visited_outermost = true;
1676             visit::walk_crate(v, crate, ());
1677         });
1678
1679         check_crate_attrs_usage(cx, crate.attrs);
1680         // since the root module isn't visited as an item (because it isn't an item), warn for it
1681         // here.
1682         check_missing_doc_attrs(cx, None, crate.attrs, crate.span, "crate");
1683
1684         visit::walk_crate(cx, crate, ());
1685     });
1686
1687     // If we missed any lints added to the session, then there's a bug somewhere
1688     // in the iteration code.
1689     let lints = tcx.sess.lints.borrow();
1690     for (id, v) in lints.get().iter() {
1691         for &(lint, span, ref msg) in v.iter() {
1692             tcx.sess.span_bug(span, format!("unprocessed lint {:?} at {}: {}",
1693                                             lint,
1694                                             ast_map::node_id_to_str(tcx.items,
1695                                                 *id,
1696                                                 token::get_ident_interner()),
1697                                             *msg))
1698         }
1699     }
1700
1701     tcx.sess.abort_if_errors();
1702 }