lint.rs 53.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11

12
use driver::session;
P
Patrick Walton 已提交
13
use middle::ty;
14
use middle::pat_util;
15
use metadata::csearch;
P
Patrick Walton 已提交
16
use util::ppaux::{ty_to_str};
17

18 19 20 21 22 23 24 25 26 27
use std::cmp;
use std::hashmap::HashMap;
use std::i16;
use std::i32;
use std::i64;
use std::i8;
use std::u16;
use std::u32;
use std::u64;
use std::u8;
28
use extra::smallintmap::SmallIntMap;
29
use syntax::ast_map;
30
use syntax::attr;
31
use syntax::attr::{AttrMetaMethods, AttributeMethods};
32
use syntax::codemap::Span;
J
John Clements 已提交
33
use syntax::codemap;
34
use syntax::parse::token;
35 36
use syntax::{ast, ast_util, visit};
use syntax::visit::Visitor;
37

38 39 40 41 42 43 44
/**
 * A 'lint' check is a kind of miscellaneous constraint that a user _might_
 * want to enforce, but might reasonably want to permit as well, on a
 * module-by-module basis. They contrast with static constraints enforced by
 * other phases of the compiler, which are generally required to hold in order
 * to compile the program at all.
 *
45 46 47 48 49
 * The lint checking is all consolidated into one pass which runs just before
 * translation to LLVM bytecode. Throughout compilation, lint warnings can be
 * added via the `add_lint` method on the Session structure. This requires a
 * span and an id of the node that the lint is being added to. The lint isn't
 * actually emitted at that time because it is unknown what the actual lint
50
 * level at that location is.
51
 *
52 53 54 55 56 57
 * To actually emit lint warnings/errors, a separate pass is used just before
 * translation. A context keeps track of the current state of all lint levels.
 * Upon entering a node of the ast which can modify the lint settings, the
 * previous lint state is pushed onto a stack and the ast is then recursed upon.
 * As the ast is traversed, this keeps track of the current lint level for all
 * lint attributes.
58
 *
59
 * At each node of the ast which can modify lint attributes, all known lint
60
 * passes are also applied.  Each lint pass is a visit::Visitor implementator.
61 62 63 64 65 66
 * The visitors are constructed via the lint_*() functions below. There are
 * also some lint checks which operate directly on ast nodes (such as
 * @ast::item), and those are organized as check_item_*(). Each visitor added
 * to the lint context is modified to stop once it reaches a node which could
 * alter the lint levels. This means that everything is looked at once and
 * only once by every lint pass.
67 68 69 70 71 72
 *
 * With this all in place, to add a new lint warning, all you need to do is to
 * either invoke `add_lint` on the session at the appropriate time, or write a
 * lint pass in this module which is just an ast visitor. The context used when
 * traversing the ast has a `span_lint` method which only needs the span of the
 * item that's being warned about.
73
 */
74

75
#[deriving(Clone, Eq)]
76
pub enum lint {
P
Patrick Walton 已提交
77
    ctypes,
78
    cstack,
79
    unused_imports,
80
    unnecessary_qualification,
81 82
    while_true,
    path_statement,
83
    unrecognized_lint,
84
    non_camel_case_types,
85
    non_uppercase_statics,
86
    type_limits,
87
    unused_unsafe,
88

89 90 91 92
    managed_heap_memory,
    owned_heap_memory,
    heap_memory,

93 94
    unused_variable,
    dead_assignment,
95
    unused_mut,
96
    unnecessary_allocation,
97

98
    missing_doc,
99
    unreachable_code,
100

101 102 103 104
    deprecated,
    experimental,
    unstable,

105
    warnings,
106 107
}

108
pub fn level_to_str(lv: level) -> &'static str {
109
    match lv {
110 111 112 113
      allow => "allow",
      warn => "warn",
      deny => "deny",
      forbid => "forbid"
114 115 116
    }
}

117
#[deriving(Clone, Eq, Ord)]
118
pub enum level {
119
    allow, warn, deny, forbid
120 121
}

122
#[deriving(Clone, Eq)]
123
pub struct LintSpec {
124
    lint: lint,
125
    desc: &'static str,
126
    default: level
127
}
128

129 130 131 132
impl Ord for LintSpec {
    fn lt(&self, other: &LintSpec) -> bool { self.default < other.default }
}

133
pub type LintDict = HashMap<&'static str, LintSpec>;
134 135 136 137

enum AttributedNode<'self> {
    Item(@ast::item),
    Method(&'self ast::method),
A
Alex Crichton 已提交
138
    Crate(&'self ast::Crate),
139
}
140

141 142
#[deriving(Eq)]
enum LintSource {
143
    Node(Span),
144 145 146 147
    Default,
    CommandLine
}

S
Sangeun Kim 已提交
148 149 150 151
static lint_table: &'static [(&'static str, LintSpec)] = &[
    ("ctypes",
     LintSpec {
        lint: ctypes,
152
        desc: "proper use of std::libc types in foreign modules",
S
Sangeun Kim 已提交
153 154 155
        default: warn
     }),

156 157 158 159 160 161 162
    ("cstack",
     LintSpec {
        lint: cstack,
        desc: "only invoke foreign functions from fixedstacksegment fns",
        default: deny
     }),

S
Sangeun Kim 已提交
163 164 165 166 167 168 169
    ("unused_imports",
     LintSpec {
        lint: unused_imports,
        desc: "imports that are never used",
        default: warn
     }),

170 171 172 173 174 175 176
    ("unnecessary_qualification",
     LintSpec {
        lint: unnecessary_qualification,
        desc: "detects unnecessarily qualified names",
        default: allow
     }),

S
Sangeun Kim 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    ("while_true",
     LintSpec {
        lint: while_true,
        desc: "suggest using loop { } instead of while(true) { }",
        default: warn
     }),

    ("path_statement",
     LintSpec {
        lint: path_statement,
        desc: "path statements with no effect",
        default: warn
     }),

    ("unrecognized_lint",
     LintSpec {
        lint: unrecognized_lint,
        desc: "unrecognized lint attribute",
        default: warn
     }),

    ("non_camel_case_types",
     LintSpec {
        lint: non_camel_case_types,
        desc: "types, variants and traits should have camel case names",
        default: allow
     }),

205 206 207 208
    ("non_uppercase_statics",
     LintSpec {
         lint: non_uppercase_statics,
         desc: "static constants should have uppercase identifiers",
209
         default: allow
210 211
     }),

S
Sangeun Kim 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    ("managed_heap_memory",
     LintSpec {
        lint: managed_heap_memory,
        desc: "use of managed (@ type) heap memory",
        default: allow
     }),

    ("owned_heap_memory",
     LintSpec {
        lint: owned_heap_memory,
        desc: "use of owned (~ type) heap memory",
        default: allow
     }),

    ("heap_memory",
     LintSpec {
        lint: heap_memory,
        desc: "use of any (~ type or @ type) heap memory",
        default: allow
     }),

    ("type_limits",
     LintSpec {
        lint: type_limits,
        desc: "comparisons made useless by limits of the types involved",
        default: warn
     }),

    ("unused_unsafe",
     LintSpec {
        lint: unused_unsafe,
        desc: "unnecessary use of an `unsafe` block",
        default: warn
    }),

    ("unused_variable",
     LintSpec {
        lint: unused_variable,
        desc: "detect variables which are not used in any way",
        default: warn
    }),

    ("dead_assignment",
     LintSpec {
        lint: dead_assignment,
        desc: "detect assignments that will never be read",
        default: warn
    }),

    ("unused_mut",
     LintSpec {
        lint: unused_mut,
        desc: "detect mut variables which don't need to be mutable",
        default: warn
    }),
267 268 269 270 271 272 273

    ("unnecessary_allocation",
     LintSpec {
        lint: unnecessary_allocation,
        desc: "detects unnecessary allocations that can be eliminated",
        default: warn
    }),
274

275
    ("missing_doc",
276
     LintSpec {
277 278
        lint: missing_doc,
        desc: "detects missing documentation for public members",
279 280
        default: allow
    }),
281 282 283 284 285 286 287

    ("unreachable_code",
     LintSpec {
        lint: unreachable_code,
        desc: "detects unreachable code",
        default: warn
    }),
288

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    ("deprecated",
     LintSpec {
        lint: deprecated,
        desc: "detects use of #[deprecated] items",
        default: warn
    }),

    ("experimental",
     LintSpec {
        lint: experimental,
        desc: "detects use of #[experimental] items",
        default: warn
    }),

    ("unstable",
     LintSpec {
        lint: unstable,
        desc: "detects use of #[unstable] items (incl. items with no stability attribute)",
        default: allow
    }),

310 311 312 313 314 315
    ("warnings",
     LintSpec {
        lint: warnings,
        desc: "mass-change the level for lints which produce warnings",
        default: warn
    }),
S
Sangeun Kim 已提交
316 317
];

318 319 320 321
/*
  Pass names should not contain a '-', as the compiler normalizes
  '-' to '_' in command-line flags
 */
322
pub fn get_lint_dict() -> LintDict {
323
    let mut map = HashMap::new();
D
Daniel Micay 已提交
324
    for &(k, v) in lint_table.iter() {
325
        map.insert(k, v);
326
    }
327
    return map;
328 329
}

330 331 332
trait OuterLint {
    fn process_item(@mut self, i:@ast::item, e:@mut Context);
    fn process_fn(@mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
333
                  b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context);
334 335 336 337 338 339 340 341 342 343 344 345 346 347

    // Returned inner variant will not proceed past subitems.
    // Supports decomposition of simple lints into subitem-traversing
    // outer lint visitor and subitem-stopping inner lint visitor.
    fn inner_variant(@mut self) -> @mut InnerLint;
}

trait InnerLint {
    fn descend_item(@mut self, i:&ast::item, e:@mut Context);
    fn descend_crate(@mut self, crate: &ast::Crate, env: @mut Context);
    fn descend_fn(@mut self,
                  function_kind: &visit::fn_kind,
                  function_declaration: &ast::fn_decl,
                  function_body: &ast::Block,
348
                  sp: Span,
349 350 351 352 353 354
                  id: ast::NodeId,
                  env: @mut Context);
}

impl<V:Visitor<@mut Context>> InnerLint for V {
    fn descend_item(@mut self, i:&ast::item, e:@mut Context) {
355 356
        visit::walk_item(self, i, e);
    }
357 358 359 360
    fn descend_crate(@mut self, crate: &ast::Crate, env: @mut Context) {
        visit::walk_crate(self, crate, env);
    }
    fn descend_fn(@mut self, fk: &visit::fn_kind, fd: &ast::fn_decl, fb: &ast::Block,
361
                  sp: Span, id: ast::NodeId, env: @mut Context) {
362 363 364 365
        visit::walk_fn(self, fk, fd, fb, sp, id, env);
    }
}

366 367 368 369 370 371 372 373
enum AnyVisitor {
    // This is a pair so every visitor can visit every node. When a lint pass
    // is registered, another visitor is created which stops at all items
    // which can alter the attributes of the ast. This "item stopping visitor"
    // is the second element of the pair, while the original visitor is the
    // first element. This means that when visiting a node, the original
    // recursive call can use the original visitor's method, although the
    // recursing visitor supplied to the method is the item stopping visitor.
374
    OldVisitor(@mut OuterLint, @mut InnerLint),
375
    NewVisitor(@mut visit::Visitor<()>),
376 377
}

378
struct Context {
379 380 381
    // All known lint modes (string versions)
    dict: @LintDict,
    // Current levels of each lint warning
382
    curr: SmallIntMap<(level, LintSource)>,
383 384
    // context we're checking in (used to access fields like sess)
    tcx: ty::ctxt,
385 386 387
    // Just a simple flag if we're currently recursing into a trait
    // implementation. This is only used by the lint_missing_doc() pass
    in_trait_impl: bool,
388 389 390 391
    // Another flag for doc lint emissions. Does some parent of the current node
    // have the doc(hidden) attribute? Treating this as allow(missing_doc) would
    // play badly with forbid(missing_doc) when it shouldn't.
    doc_hidden: bool,
392 393 394
    // When recursing into an attributed node of the ast which modifies lint
    // levels, this stack keeps track of the previous lint levels of whatever
    // was modified.
395
    lint_stack: ~[(lint, level, LintSource)],
396 397 398 399 400
    // Each of these visitors represents a lint pass. A number of the lint
    // attributes are registered by adding a visitor to iterate over the ast.
    // Others operate directly on @ast::item structures (or similar). Finally,
    // others still are added to the Session object via `add_lint`, and these
    // are all passed with the lint_session visitor.
401
    visitors: ~[AnyVisitor],
402
}
403

404
impl Context {
405
    fn get_level(&self, lint: lint) -> level {
406
        match self.curr.find(&(lint as uint)) {
407
          Some(&(lvl, _)) => lvl,
408 409
          None => allow
        }
410 411
    }

412 413 414 415 416 417 418 419
    fn get_source(&self, lint: lint) -> LintSource {
        match self.curr.find(&(lint as uint)) {
          Some(&(_, src)) => src,
          None => Default
        }
    }

    fn set_level(&mut self, lint: lint, level: level, src: LintSource) {
420
        if level == allow {
D
Daniel Micay 已提交
421
            self.curr.remove(&(lint as uint));
422
        } else {
423 424 425 426
            self.curr.insert(lint as uint, (level, src));
        }
    }

427
    fn lint_to_str(&self, lint: lint) -> &'static str {
D
Daniel Micay 已提交
428
        for (k, v) in self.dict.iter() {
429
            if v.lint == lint {
430
                return *k;
431
            }
432
        }
A
Alex Crichton 已提交
433
        fail2!("unregistered lint {:?}", lint);
434 435
    }

436
    fn span_lint(&self, lint: lint, span: Span, msg: &str) {
437
        let (level, src) = match self.curr.find(&(lint as uint)) {
438 439
            None => { return }
            Some(&(warn, src)) => (self.get_level(warnings), src),
440 441
            Some(&pair) => pair,
        };
442
        if level == allow { return }
443 444 445 446

        let mut note = None;
        let msg = match src {
            Default | CommandLine => {
A
Alex Crichton 已提交
447
                format!("{} [-{} {}{}]", msg, match level {
448
                        warn => 'W', deny => 'D', forbid => 'F',
A
Alex Crichton 已提交
449
                        allow => fail2!()
450
                    }, self.lint_to_str(lint).replace("_", "-"),
451 452 453 454 455 456 457 458 459 460
                    if src == Default { " (default)" } else { "" })
            },
            Node(src) => {
                note = Some(src);
                msg.to_str()
            }
        };
        match level {
            warn =>          { self.tcx.sess.span_warn(span, msg); }
            deny | forbid => { self.tcx.sess.span_err(span, msg);  }
A
Alex Crichton 已提交
461
            allow => fail2!(),
462 463
        }

D
Daniel Micay 已提交
464
        for &span in note.iter() {
465 466
            self.tcx.sess.span_note(span, "lint level defined here");
        }
467 468
    }

469
    /**
470
     * Merge the lints specified by any lint attributes into the
471
     * current lint context, call the provided function, then reset the
472
     * lints in effect to their previous state.
473
     */
474
    fn with_lint_attrs(@mut self, attrs: &[ast::Attribute], f: &fn()) {
475 476 477 478 479
        // Parse all of the lint attributes, and then add them all to the
        // current dictionary of lint information. Along the way, keep a history
        // of what we changed so we can roll everything back after invoking the
        // specified closure
        let mut pushed = 0u;
480 481 482 483 484 485
        do each_lint(self.tcx.sess, attrs) |meta, level, lintname| {
            match self.dict.find_equiv(&lintname) {
                None => {
                    self.span_lint(
                        unrecognized_lint,
                        meta.span,
A
Alex Crichton 已提交
486
                        format!("unknown `{}` attribute: `{}`",
487 488 489 490 491 492 493
                        level_to_str(level), lintname));
                }
                Some(lint) => {
                    let lint = lint.lint;
                    let now = self.get_level(lint);
                    if now == forbid && level != forbid {
                        self.tcx.sess.span_err(meta.span,
A
Alex Crichton 已提交
494
                        format!("{}({}) overruled by outer forbid({})",
495 496 497 498 499 500 501 502 503
                        level_to_str(level),
                        lintname, lintname));
                    } else if now != level {
                        let src = self.get_source(lint);
                        self.lint_stack.push((lint, now, src));
                        pushed += 1;
                        self.set_level(lint, level, Node(meta.span));
                    }
                }
504
            }
505 506
            true
        };
507

508
        // detect doc(hidden)
509 510 511 512 513
        let mut doc_hidden = do attrs.iter().any |attr| {
            "doc" == attr.name() &&
                match attr.meta_item_list() {
                    Some(l) => attr::contains_name(l, "hidden"),
                    None    => false // not of the form #[doc(...)]
514
                }
515 516
        };

517 518 519 520 521 522
        if doc_hidden && !self.doc_hidden {
            self.doc_hidden = true;
        } else {
            doc_hidden = false;
        }

523
        f();
524

525
        // rollback
526 527 528
        if doc_hidden && self.doc_hidden {
            self.doc_hidden = false;
        }
529
        do pushed.times {
530 531
            let (lint, lvl, src) = self.lint_stack.pop();
            self.set_level(lint, lvl, src);
532
        }
533 534
    }

535
    fn add_old_lint(&mut self, v: @mut OuterLint) {
536
        self.visitors.push(OldVisitor(v, v.inner_variant()));
537 538
    }

539
    fn add_lint(&mut self, v: @mut visit::Visitor<()>) {
540
        self.visitors.push(NewVisitor(v));
541 542
    }

543
    fn process(@mut self, n: AttributedNode) {
544 545
        // see comment of the `visitors` field in the struct for why there's a
        // pair instead of just one visitor.
546
        match n {
547
            Item(it) => {
D
Daniel Micay 已提交
548
                for visitor in self.visitors.iter() {
549 550
                    match *visitor {
                        OldVisitor(orig, stopping) => {
551 552
                            orig.process_item(it, self);
                            stopping.descend_item(it, self);
553 554
                        }
                        NewVisitor(new_visitor) => {
555
                            let new_visitor = new_visitor;
556 557 558
                            new_visitor.visit_item(it, ());
                        }
                    }
559 560 561
                }
            }
            Crate(c) => {
D
Daniel Micay 已提交
562
                for visitor in self.visitors.iter() {
563 564
                    match *visitor {
                        OldVisitor(_, stopping) => {
565
                            stopping.descend_crate(c, self)
566 567
                        }
                        NewVisitor(new_visitor) => {
568 569
                            let mut new_visitor = new_visitor;
                            visit::walk_crate(&mut new_visitor, c, ())
570 571
                        }
                    }
572 573
                }
            }
574
            // Can't use visit::walk_method_helper because the
575 576
            // item_stopping_visitor has overridden visit_fn(&fk_method(... ))
            // to be a no-op, so manually invoke visit_fn.
577
            Method(m) => {
D
Daniel Micay 已提交
578
                for visitor in self.visitors.iter() {
579 580
                    match *visitor {
                        OldVisitor(orig, stopping) => {
581 582 583
                            let fk = visit::fk_method(m.ident, &m.generics, m);
                            orig.process_fn(&fk, &m.decl, &m.body, m.span, m.id, self);
                            stopping.descend_fn(&fk, &m.decl, &m.body, m.span, m.id, self);
584 585 586 587 588
                        }
                        NewVisitor(new_visitor) => {
                            let fk = visit::fk_method(m.ident,
                                                      &m.generics,
                                                      m);
589
                            let new_visitor = new_visitor;
590 591 592 593 594 595 596 597
                            new_visitor.visit_fn(&fk,
                                                 &m.decl,
                                                 &m.body,
                                                 m.span,
                                                 m.id,
                                                 ())
                        }
                    }
598 599
                }
            }
600 601 602 603
        }
    }
}

604
pub fn each_lint(sess: session::Session,
605 606
                 attrs: &[ast::Attribute],
                 f: &fn(@ast::MetaItem, level, @str) -> bool) -> bool {
607
    let xs = [allow, warn, deny, forbid];
D
Daniel Micay 已提交
608
    for &level in xs.iter() {
609
        let level_name = level_to_str(level);
D
Daniel Micay 已提交
610
        for attr in attrs.iter().filter(|m| level_name == m.name()) {
611 612
            let meta = attr.node.value;
            let metas = match meta.node {
613
                ast::MetaList(_, ref metas) => metas,
614
                _ => {
615
                    sess.span_err(meta.span, "malformed lint attribute");
616 617 618
                    loop;
                }
            };
D
Daniel Micay 已提交
619
            for meta in metas.iter() {
620
                match meta.node {
621
                    ast::MetaWord(lintname) => {
622 623 624 625 626
                        if !f(*meta, level, lintname) {
                            return false;
                        }
                    }
                    _ => {
627
                        sess.span_err(meta.span, "malformed lint attribute");
628 629 630 631 632
                    }
                }
            }
        }
    }
633
    true
634 635
}

636 637 638 639 640 641 642 643
trait SubitemStoppableVisitor : Visitor<@mut Context> {
    fn is_running_on_items(&mut self) -> bool;

    fn visit_item_action(&mut self, _i:@ast::item, _e:@mut Context) {
        // fill in with particular action without recursion if desired
    }

    fn visit_fn_action(&mut self, _fk:&visit::fn_kind, _fd:&ast::fn_decl,
644
                       _b:&ast::Block, _s:Span, _n:ast::NodeId, _e:@mut Context) {
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
        // fill in with particular action without recursion if desired
    }

    // The two OVERRIDE methods:
    //
    //   OVERRIDE_visit_item
    //   OVERRIDE_visit_fn
    //
    // *must* be included as initial reimplementations of the standard
    // default behavior of visit_item and visit_fn for every impl of
    // Visitor, in order to recreate the effect of having two variant
    // Outer/Inner behaviors of lint visitors.  (See earlier versions
    // of this module to see what the original encoding was of this
    // emulated behavior.)

    fn OVERRIDE_visit_item(&mut self, i:@ast::item, e:@mut Context) {
        if self.is_running_on_items() {
            self.visit_item_action(i, e);
            visit::walk_item(self, i, e);
        }
    }

    fn OVERRIDE_visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
668
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
669 670 671 672
        if self.is_running_on_items() {
            self.visit_fn_action(fk, fd, b, s, n, e);
            visit::walk_fn(self, fk, fd, b, s, n, e);
        } else {
673
            match *fk {
674 675 676 677 678
                visit::fk_method(*) => {}
                _ => {
                    self.visit_fn_action(fk, fd, b, s, n, e);
                    visit::walk_fn(self, fk, fd, b, s, n, e);
                }
679
            }
680 681 682 683 684 685 686 687 688
        }
    }
}

struct WhileTrueLintVisitor { stopping_on_items: bool }


impl SubitemStoppableVisitor for WhileTrueLintVisitor {
    fn is_running_on_items(&mut self) -> bool { !self.stopping_on_items }
689 690
}

691 692 693 694 695 696
impl Visitor<@mut Context> for WhileTrueLintVisitor {
    fn visit_item(&mut self, i:@ast::item, e:@mut Context) {
        self.OVERRIDE_visit_item(i, e);
    }

    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
697
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
698 699 700
        self.OVERRIDE_visit_fn(fk, fd, b, s, n, e);
    }

701
    fn visit_expr(&mut self, e:@ast::Expr, cx:@mut Context) {
702

703
            match e.node {
704
                ast::ExprWhile(cond, _) => {
705
                    match cond.node {
706
                        ast::ExprLit(@codemap::Spanned {
707 708 709 710 711
                            node: ast::lit_bool(true), _}) =>
                        {
                            cx.span_lint(while_true, e.span,
                                         "denote infinite loops with \
                                          loop { ... }");
712
                        }
713
                        _ => ()
714 715
                    }
                }
716 717
                _ => ()
            }
718 719 720 721 722
            visit::walk_expr(self, e, cx);
    }
}

macro_rules! outer_lint_boilerplate_impl(
723
    ($Visitor:ident) =>
724 725 726 727 728 729
    (
        impl OuterLint for $Visitor {
            fn process_item(@mut self, i:@ast::item, e:@mut Context) {
                self.visit_item_action(i, e);
            }
            fn process_fn(@mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
730
                          b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
731 732 733 734 735 736 737 738 739 740 741 742
                self.visit_fn_action(fk, fd, b, s, n, e);
            }
            fn inner_variant(@mut self) -> @mut InnerLint {
                @mut $Visitor { stopping_on_items: true } as @mut InnerLint
            }
        }
    ))

outer_lint_boilerplate_impl!(WhileTrueLintVisitor)

fn lint_while_true() -> @mut OuterLint {
    @mut WhileTrueLintVisitor{ stopping_on_items: false } as @mut OuterLint
V
Viktor Dahl 已提交
743 744
}

745 746 747 748 749 750 751
struct TypeLimitsLintVisitor { stopping_on_items: bool }

impl SubitemStoppableVisitor for TypeLimitsLintVisitor {
    fn is_running_on_items(&mut self) -> bool { !self.stopping_on_items }
}

impl TypeLimitsLintVisitor {
752
    fn is_valid<T:cmp::Ord>(&mut self, binop: ast::BinOp, v: T,
753 754
            min: T, max: T) -> bool {
        match binop {
755 756 757 758 759
            ast::BiLt => v <= max,
            ast::BiLe => v < max,
            ast::BiGt => v >= min,
            ast::BiGe => v > min,
            ast::BiEq | ast::BiNe => v >= min && v <= max,
A
Alex Crichton 已提交
760
            _ => fail2!()
761 762 763
        }
    }

764
    fn rev_binop(&mut self, binop: ast::BinOp) -> ast::BinOp {
765
        match binop {
766 767 768 769
            ast::BiLt => ast::BiGt,
            ast::BiLe => ast::BiGe,
            ast::BiGt => ast::BiLt,
            ast::BiGe => ast::BiLe,
770 771 772 773
            _ => binop
        }
    }

774 775
    // for int & uint, be conservative with the warnings, so that the
    // warnings are consistent between 32- and 64-bit platforms
776
    fn int_ty_range(&mut self, int_ty: ast::int_ty) -> (i64, i64) {
777
        match int_ty {
778
            ast::ty_i =>    (i64::min_value,        i64::max_value),
779 780 781 782 783 784 785
            ast::ty_i8 =>   (i8::min_value  as i64, i8::max_value  as i64),
            ast::ty_i16 =>  (i16::min_value as i64, i16::max_value as i64),
            ast::ty_i32 =>  (i32::min_value as i64, i32::max_value as i64),
            ast::ty_i64 =>  (i64::min_value,        i64::max_value)
        }
    }

786
    fn uint_ty_range(&mut self, uint_ty: ast::uint_ty) -> (u64, u64) {
787
        match uint_ty {
788
            ast::ty_u =>   (u64::min_value,         u64::max_value),
789 790 791 792 793 794 795
            ast::ty_u8 =>  (u8::min_value   as u64, u8::max_value   as u64),
            ast::ty_u16 => (u16::min_value  as u64, u16::max_value  as u64),
            ast::ty_u32 => (u32::min_value  as u64, u32::max_value  as u64),
            ast::ty_u64 => (u64::min_value,         u64::max_value)
        }
    }

796 797
    fn check_limits(&mut self,
                    cx: &Context,
798 799 800
                    binop: ast::BinOp,
                    l: @ast::Expr,
                    r: @ast::Expr)
801
                    -> bool {
802
        let (lit, expr, swap) = match (&l.node, &r.node) {
803 804
            (&ast::ExprLit(_), _) => (l, r, true),
            (_, &ast::ExprLit(_)) => (r, l, false),
805 806 807 808
            _ => return true
        };
        // Normalize the binop so that the literal is always on the RHS in
        // the comparison
809
        let norm_binop = if swap {
810
            self.rev_binop(binop)
811 812 813
        } else {
            binop
        };
814
        match ty::get(ty::expr_ty(cx.tcx, expr)).sty {
815
            ty::ty_int(int_ty) => {
816
                let (min, max) = self.int_ty_range(int_ty);
817
                let lit_val: i64 = match lit.node {
818
                    ast::ExprLit(@li) => match li.node {
819 820 821 822 823
                        ast::lit_int(v, _) => v,
                        ast::lit_uint(v, _) => v as i64,
                        ast::lit_int_unsuffixed(v) => v,
                        _ => return true
                    },
A
Alex Crichton 已提交
824
                    _ => fail2!()
825
                };
826
                self.is_valid(norm_binop, lit_val, min, max)
827 828
            }
            ty::ty_uint(uint_ty) => {
829
                let (min, max): (u64, u64) = self.uint_ty_range(uint_ty);
830
                let lit_val: u64 = match lit.node {
831
                    ast::ExprLit(@li) => match li.node {
832 833 834 835 836
                        ast::lit_int(v, _) => v as u64,
                        ast::lit_uint(v, _) => v,
                        ast::lit_int_unsuffixed(v) => v as u64,
                        _ => return true
                    },
A
Alex Crichton 已提交
837
                    _ => fail2!()
838
                };
839
                self.is_valid(norm_binop, lit_val, min, max)
840 841 842 843 844
            }
            _ => true
        }
    }

845
    fn is_comparison(&mut self, binop: ast::BinOp) -> bool {
846
        match binop {
847 848
            ast::BiEq | ast::BiLt | ast::BiLe |
            ast::BiNe | ast::BiGe | ast::BiGt => true,
849 850 851
            _ => false
        }
    }
852 853 854 855 856 857 858 859
}

impl Visitor<@mut Context> for TypeLimitsLintVisitor {
    fn visit_item(&mut self, i:@ast::item, e:@mut Context) {
        self.OVERRIDE_visit_item(i, e);
    }

    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
860
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
861 862 863
        self.OVERRIDE_visit_fn(fk, fd, b, s, n, e);
    }

864
    fn visit_expr(&mut self, e:@ast::Expr, cx:@mut Context) {
865

866
            match e.node {
867
                ast::ExprBinary(_, ref binop, l, r) => {
868 869
                    if self.is_comparison(*binop)
                        && !self.check_limits(cx, *binop, l, r) {
870 871 872
                        cx.span_lint(type_limits, e.span,
                                     "comparison is useless due to type limits");
                    }
873
                }
874
                _ => ()
875
            }
876 877 878
            visit::walk_expr(self, e, cx);
    }
}
879

880 881 882 883
outer_lint_boilerplate_impl!(TypeLimitsLintVisitor)

fn lint_type_limits() -> @mut OuterLint {
    @mut TypeLimitsLintVisitor{ stopping_on_items: false } as @mut OuterLint
884 885
}

886 887
fn check_item_ctypes(cx: &Context, it: &ast::item) {
    fn check_ty(cx: &Context, ty: &ast::Ty) {
888 889 890
        match ty.node {
            ast::ty_path(_, _, id) => {
                match cx.tcx.def_map.get_copy(&id) {
891
                    ast::DefPrimTy(ast::ty_int(ast::ty_i)) => {
892 893 894 895
                        cx.span_lint(ctypes, ty.span,
                                "found rust type `int` in foreign module, while \
                                libc::c_int or libc::c_long should be used");
                    }
896
                    ast::DefPrimTy(ast::ty_uint(ast::ty_u)) => {
897 898 899 900 901 902 903
                        cx.span_lint(ctypes, ty.span,
                                "found rust type `uint` in foreign module, while \
                                libc::c_uint or libc::c_ulong should be used");
                    }
                    _ => ()
                }
            }
904
            ast::ty_ptr(ref mt) => { check_ty(cx, mt.ty) }
905 906 907
            _ => ()
        }
    }
908

909
    fn check_foreign_fn(cx: &Context, decl: &ast::fn_decl) {
D
Daniel Micay 已提交
910
        for input in decl.inputs.iter() {
911
            check_ty(cx, &input.ty);
912
        }
J
James Miller 已提交
913
        check_ty(cx, &decl.output)
914 915
    }

916
    match it.node {
917
      ast::item_foreign_mod(ref nmod) if !nmod.abis.is_intrinsic() => {
D
Daniel Micay 已提交
918
        for ni in nmod.items.iter() {
919
            match ni.node {
920
                ast::foreign_item_fn(ref decl, _) => {
921 922
                    check_foreign_fn(cx, decl);
                }
J
James Miller 已提交
923
                ast::foreign_item_static(ref t, _) => { check_ty(cx, t); }
924 925
            }
        }
926
      }
B
Brian Anderson 已提交
927
      _ => {/* nothing to do */ }
928 929
    }
}
930

931
fn check_type_for_lint(cx: &Context, lint: lint, span: Span, ty: ty::t) {
932
    if cx.get_level(lint) == allow { return }
933

934 935 936 937 938 939 940 941 942 943
    let mut n_box = 0;
    let mut n_uniq = 0;
    ty::fold_ty(cx.tcx, ty, |t| {
        match ty::get(t).sty {
          ty::ty_box(_) => n_box += 1,
          ty::ty_uniq(_) => n_uniq += 1,
          _ => ()
        };
        t
    });
944

945 946 947 948 949
    if n_uniq > 0 && lint != managed_heap_memory {
        let s = ty_to_str(cx.tcx, ty);
        let m = ~"type uses owned (~ type) pointers: " + s;
        cx.span_lint(lint, span, m);
    }
950

951 952 953 954
    if n_box > 0 && lint != owned_heap_memory {
        let s = ty_to_str(cx.tcx, ty);
        let m = ~"type uses managed (@ type) pointers: " + s;
        cx.span_lint(lint, span, m);
955
    }
956
}
957

958
fn check_type(cx: &Context, span: Span, ty: ty::t) {
959
    let xs = [managed_heap_memory, owned_heap_memory, heap_memory];
D
Daniel Micay 已提交
960
    for lint in xs.iter() {
961
        check_type_for_lint(cx, *lint, span, ty);
962
    }
963
}
964

965
fn check_item_heap(cx: &Context, it: &ast::item) {
966 967 968 969 970 971 972 973 974
    match it.node {
      ast::item_fn(*) |
      ast::item_ty(*) |
      ast::item_enum(*) |
      ast::item_struct(*) => check_type(cx, it.span,
                                        ty::node_id_to_type(cx.tcx,
                                                            it.id)),
      _ => ()
    }
975

976 977 978
    // If it's a struct, we also have to check the fields' types
    match it.node {
        ast::item_struct(struct_def, _) => {
D
Daniel Micay 已提交
979
            for struct_field in struct_def.fields.iter() {
980 981 982
                check_type(cx, struct_field.span,
                           ty::node_id_to_type(cx.tcx,
                                               struct_field.node.id));
983 984 985 986
            }
        }
        _ => ()
    }
987
}
988

989 990 991 992 993 994 995 996 997 998 999 1000
struct HeapLintVisitor { stopping_on_items: bool }

impl SubitemStoppableVisitor for HeapLintVisitor {
    fn is_running_on_items(&mut self) -> bool { !self.stopping_on_items }
}

impl Visitor<@mut Context> for HeapLintVisitor {
    fn visit_item(&mut self, i:@ast::item, e:@mut Context) {
        self.OVERRIDE_visit_item(i, e);
    }

    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
1001
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
1002 1003 1004
        self.OVERRIDE_visit_fn(fk, fd, b, s, n, e);
    }

1005
    fn visit_expr(&mut self, e:@ast::Expr, cx:@mut Context) {
1006 1007
            let ty = ty::expr_ty(cx.tcx, e);
            check_type(cx, e.span, ty);
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
            visit::walk_expr(self, e, cx);
    }
}

outer_lint_boilerplate_impl!(HeapLintVisitor)

fn lint_heap() -> @mut OuterLint {
    @mut HeapLintVisitor { stopping_on_items: false } as @mut OuterLint
}

struct PathStatementLintVisitor {
    stopping_on_items: bool
}

impl SubitemStoppableVisitor for PathStatementLintVisitor {
    fn is_running_on_items(&mut self) -> bool { !self.stopping_on_items }
1024 1025
}

1026 1027 1028 1029 1030 1031
impl Visitor<@mut Context> for PathStatementLintVisitor {
    fn visit_item(&mut self, i:@ast::item, e:@mut Context) {
        self.OVERRIDE_visit_item(i, e);
    }

    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
1032
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
1033 1034 1035
        self.OVERRIDE_visit_fn(fk, fd, b, s, n, e);
    }

1036
    fn visit_stmt(&mut self, s:@ast::Stmt, cx:@mut Context) {
1037
            match s.node {
1038 1039
                ast::StmtSemi(
                    @ast::Expr { node: ast::ExprPath(_), _ },
1040 1041 1042 1043
                    _
                ) => {
                    cx.span_lint(path_statement, s.span,
                                 "path statement with no effect");
1044
                }
1045 1046
                _ => ()
            }
1047 1048 1049 1050 1051 1052 1053 1054 1055
            visit::walk_stmt(self, s, cx);

    }
}

outer_lint_boilerplate_impl!(PathStatementLintVisitor)

fn lint_path_statement() -> @mut OuterLint {
    @mut PathStatementLintVisitor{ stopping_on_items: false } as @mut OuterLint
1056 1057
}

1058
fn check_item_non_camel_case_types(cx: &Context, it: &ast::item) {
1059
    fn is_camel_case(cx: ty::ctxt, ident: ast::Ident) -> bool {
P
Paul Stansifer 已提交
1060
        let ident = cx.sess.str_of(ident);
P
Patrick Walton 已提交
1061
        assert!(!ident.is_empty());
1062
        let ident = ident.trim_chars(&'_');
1063 1064 1065 1066

        // start with a non-lowercase letter rather than non-uppercase
        // ones (some scripts don't have a concept of upper/lowercase)
        !ident.char_at(0).is_lowercase() &&
1067 1068 1069
            !ident.contains_char('_')
    }

1070
    fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1071
        if !is_camel_case(cx.tcx, ident) {
1072 1073
            cx.span_lint(
                non_camel_case_types, span,
A
Alex Crichton 已提交
1074
                format!("{} `{}` should have a camel case identifier",
1075
                    sort, cx.tcx.sess.str_of(ident)));
1076 1077 1078
        }
    }

1079
    match it.node {
1080 1081 1082
        ast::item_ty(*) | ast::item_struct(*) => {
            check_case(cx, "type", it.ident, it.span)
        }
E
Erick Tryzelaar 已提交
1083
        ast::item_trait(*) => {
1084
            check_case(cx, "trait", it.ident, it.span)
1085
        }
E
Erick Tryzelaar 已提交
1086
        ast::item_enum(ref enum_definition, _) => {
1087
            check_case(cx, "type", it.ident, it.span);
D
Daniel Micay 已提交
1088
            for variant in enum_definition.variants.iter() {
1089
                check_case(cx, "variant", variant.node.name, variant.span);
E
Erick Tryzelaar 已提交
1090 1091 1092
            }
        }
        _ => ()
1093 1094 1095
    }
}

1096 1097 1098
fn check_item_non_uppercase_statics(cx: &Context, it: &ast::item) {
    match it.node {
        // only check static constants
1099
        ast::item_static(_, ast::MutImmutable, _) => {
1100 1101 1102 1103
            let s = cx.tcx.sess.str_of(it.ident);
            // check for lowercase letters rather than non-uppercase
            // ones (some scripts don't have a concept of
            // upper/lowercase)
1104
            if s.iter().any(|c| c.is_lowercase()) {
1105 1106 1107 1108 1109 1110 1111 1112
                cx.span_lint(non_uppercase_statics, it.span,
                             "static constant should have an uppercase identifier");
            }
        }
        _ => {}
    }
}

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
struct UnusedUnsafeLintVisitor { stopping_on_items: bool }

impl SubitemStoppableVisitor for UnusedUnsafeLintVisitor {
    fn is_running_on_items(&mut self) -> bool { !self.stopping_on_items }
}

impl Visitor<@mut Context> for UnusedUnsafeLintVisitor {
    fn visit_item(&mut self, i:@ast::item, e:@mut Context) {
        self.OVERRIDE_visit_item(i, e);
    }

    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
1125
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
1126 1127 1128
        self.OVERRIDE_visit_fn(fk, fd, b, s, n, e);
    }

1129
    fn visit_expr(&mut self, e:@ast::Expr, cx:@mut Context) {
1130

1131
            match e.node {
1132 1133
                // Don't warn about generated blocks, that'll just pollute the
                // output.
1134 1135 1136
                ast::ExprBlock(ref blk) => {
                    if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
                       !cx.tcx.used_unsafe.contains(&blk.id) {
1137 1138 1139
                        cx.span_lint(unused_unsafe, blk.span,
                                     "unnecessary `unsafe` block");
                    }
1140
                }
1141
                _ => ()
1142
            }
1143 1144 1145 1146 1147 1148 1149 1150
            visit::walk_expr(self, e, cx);
    }
}

outer_lint_boilerplate_impl!(UnusedUnsafeLintVisitor)

fn lint_unused_unsafe() -> @mut OuterLint {
    @mut UnusedUnsafeLintVisitor{ stopping_on_items: false } as @mut OuterLint
1151 1152
}

1153 1154 1155
struct UnusedMutLintVisitor { stopping_on_items: bool }

impl UnusedMutLintVisitor {
1156
    fn check_pat(&mut self, cx: &Context, p: @ast::Pat) {
1157 1158
        let mut used = false;
        let mut bindings = 0;
1159 1160
        do pat_util::pat_bindings(cx.tcx.def_map, p) |_, id, _, _| {
            used = used || cx.tcx.used_mut_nodes.contains(&id);
1161 1162 1163 1164
            bindings += 1;
        }
        if !used {
            let msg = if bindings == 1 {
S
Seo Sanghyeon 已提交
1165
                "variable does not need to be mutable"
1166
            } else {
S
Seo Sanghyeon 已提交
1167
                "variables do not need to be mutable"
1168
            };
1169
            cx.span_lint(unused_mut, p.span, msg);
1170
        }
1171
    }
1172

1173
    fn visit_fn_decl(&mut self, cx: &Context, fd: &ast::fn_decl) {
D
Daniel Micay 已提交
1174
        for arg in fd.inputs.iter() {
1175
            if arg.is_mutbl {
1176
                self.check_pat(cx, arg.pat);
1177 1178
            }
        }
1179
    }
1180 1181 1182 1183 1184 1185
}

impl SubitemStoppableVisitor for UnusedMutLintVisitor {
    fn is_running_on_items(&mut self) -> bool { !self.stopping_on_items }

    fn visit_fn_action(&mut self, _a:&visit::fn_kind, fd:&ast::fn_decl,
1186
                       _b:&ast::Block, _c:Span, _d:ast::NodeId, cx:@mut Context) {
1187 1188 1189
            self.visit_fn_decl(cx, fd);
    }
}
1190

1191 1192 1193 1194 1195 1196
impl Visitor<@mut Context> for UnusedMutLintVisitor {
    fn visit_item(&mut self, i:@ast::item, e:@mut Context) {
        self.OVERRIDE_visit_item(i, e);
    }

    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
1197
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
1198 1199 1200 1201 1202
        self.OVERRIDE_visit_fn(fk, fd, b, s, n, e);
    }


    fn visit_local(&mut self, l:@ast::Local, cx:@mut Context) {
1203
            if l.is_mutbl {
1204
                self.check_pat(cx, l.pat);
1205
            }
1206 1207 1208 1209 1210 1211 1212 1213 1214
            visit::walk_local(self, l, cx);
    }

    fn visit_ty_method(&mut self, tm:&ast::TypeMethod, cx:@mut Context) {
            self.visit_fn_decl(cx, &tm.decl);
            visit::walk_ty_method(self, tm, cx);
    }

    fn visit_trait_method(&mut self, tm:&ast::trait_method, cx:@mut Context) {
1215
            match *tm {
1216 1217
                ast::required(ref tm) => self.visit_fn_decl(cx, &tm.decl),
                ast::provided(m) => self.visit_fn_decl(cx, &m.decl)
1218
            }
1219 1220 1221 1222 1223 1224 1225 1226
            visit::walk_trait_method(self, tm, cx);
    }
}

outer_lint_boilerplate_impl!(UnusedMutLintVisitor)

fn lint_unused_mut() -> @mut OuterLint {
    @mut UnusedMutLintVisitor{ stopping_on_items: false } as @mut OuterLint
1227 1228
}

1229 1230 1231 1232 1233 1234 1235 1236
struct LintReportingIdVisitor {
    cx: @mut Context,
}

impl ast_util::IdVisitingOperation for LintReportingIdVisitor {
    fn visit_id(&self, id: ast::NodeId) {
        match self.cx.tcx.sess.lints.pop(&id) {
            None => {}
1237
            Some(l) => {
1238
                for (lint, span, msg) in l.move_iter() {
1239
                    self.cx.span_lint(lint, span, msg)
1240
                }
1241 1242
            }
        }
1243 1244 1245 1246 1247 1248 1249
    }
}

fn lint_session(cx: @mut Context) -> @mut visit::Visitor<()> {
    ast_util::id_visitor(@LintReportingIdVisitor {
        cx: cx,
    } as @ast_util::IdVisitingOperation, false)
1250 1251
}

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
struct UnnecessaryAllocationLintVisitor { stopping_on_items: bool }

impl SubitemStoppableVisitor for UnnecessaryAllocationLintVisitor {
    fn is_running_on_items(&mut self) -> bool { !self.stopping_on_items }
}

impl Visitor<@mut Context> for UnnecessaryAllocationLintVisitor {
    fn visit_item(&mut self, i:@ast::item, e:@mut Context) {
        self.OVERRIDE_visit_item(i, e);
    }

    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
1264
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
1265 1266 1267
        self.OVERRIDE_visit_fn(fk, fd, b, s, n, e);
    }

1268
    fn visit_expr(&mut self, e:@ast::Expr, cx:@mut Context) {
1269 1270 1271 1272 1273 1274
            self.check(cx, e);
            visit::walk_expr(self, e, cx);
    }
}

impl UnnecessaryAllocationLintVisitor {
1275 1276
    // Warn if string and vector literals with sigils are immediately borrowed.
    // Those can have the sigil removed.
1277
    fn check(&mut self, cx: &Context, e: &ast::Expr) {
1278
        match e.node {
1279 1280
            ast::ExprVstore(e2, ast::ExprVstoreUniq) |
            ast::ExprVstore(e2, ast::ExprVstoreBox) => {
1281
                match e2.node {
1282
                    ast::ExprLit(@codemap::Spanned{
1283
                            node: ast::lit_str(*), _}) |
1284
                    ast::ExprVec(*) => {}
1285 1286 1287 1288 1289 1290 1291
                    _ => return
                }
            }

            _ => return
        }

1292 1293 1294
        match cx.tcx.adjustments.find_copy(&e.id) {
            Some(@ty::AutoDerefRef(ty::AutoDerefRef {
                autoref: Some(ty::AutoBorrowVec(*)), _ })) => {
1295 1296 1297 1298 1299 1300 1301 1302
                cx.span_lint(unnecessary_allocation,
                             e.span, "unnecessary allocation, the sigil can be \
                                      removed");
            }

            _ => ()
        }
    }
1303
}
1304

1305 1306 1307 1308
outer_lint_boilerplate_impl!(UnnecessaryAllocationLintVisitor)

fn lint_unnecessary_allocations() -> @mut OuterLint {
    @mut UnnecessaryAllocationLintVisitor{ stopping_on_items: false } as @mut OuterLint
1309 1310
}

1311 1312 1313 1314 1315
struct MissingDocLintVisitor { stopping_on_items: bool }

impl MissingDocLintVisitor {
    fn check_attrs(&mut self,
                   cx: @mut Context,
1316
                   attrs: &[ast::Attribute],
1317
                   sp: Span,
1318
                   msg: &str) {
1319 1320 1321 1322 1323 1324
        // If we're building a test harness, then warning about documentation is
        // probably not really relevant right now
        if cx.tcx.sess.opts.test { return }
        // If we have doc(hidden), nothing to do
        if cx.doc_hidden { return }
        // If we're documented, nothing to do
1325
        if attrs.iter().any(|a| a.node.is_sugared_doc) { return }
1326 1327 1328

        // otherwise, warn!
        cx.span_lint(missing_doc, sp, msg);
1329
    }
1330 1331 1332 1333 1334 1335
}

impl Visitor<@mut Context> for MissingDocLintVisitor {
    fn visit_item(&mut self, i:@ast::item, e:@mut Context) {
        self.OVERRIDE_visit_item(i, e);
    }
1336

1337
    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
1338
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
1339 1340 1341 1342
        self.OVERRIDE_visit_fn(fk, fd, b, s, n, e);
    }

    fn visit_ty_method(&mut self, m:&ast::TypeMethod, cx:@mut Context) {
1343 1344
            // All ty_method objects are linted about because they're part of a
            // trait (no visibility)
1345
            self.check_attrs(cx, m.attrs, m.span,
1346
                        "missing documentation for a method");
1347 1348 1349 1350 1351 1352 1353 1354
            visit::walk_ty_method(self, m, cx);
    }
}

impl SubitemStoppableVisitor for MissingDocLintVisitor {
    fn is_running_on_items(&mut self) -> bool { !self.stopping_on_items }

    fn visit_fn_action(&mut self, fk:&visit::fn_kind, _d:&ast::fn_decl,
1355
                       _b:&ast::Block, sp:Span, _id:ast::NodeId, cx:@mut Context) {
1356

1357 1358 1359
            // Only warn about explicitly public methods. Soon implicit
            // public-ness will hopefully be going away.
            match *fk {
1360
                visit::fk_method(_, _, m) if m.vis == ast::public => {
1361 1362 1363
                    // If we're in a trait implementation, no need to duplicate
                    // documentation
                    if !cx.in_trait_impl {
1364
                        self.check_attrs(cx, m.attrs, sp,
1365
                                    "missing documentation for a method");
1366 1367
                    }
                }
1368

1369 1370
                _ => {}
            }
1371 1372 1373
    }

    fn visit_item_action(&mut self, it:@ast::item, cx:@mut Context) {
1374

1375 1376 1377 1378 1379
            match it.node {
                // Go ahead and match the fields here instead of using
                // visit_struct_field while we have access to the enclosing
                // struct's visibility
                ast::item_struct(sdef, _) if it.vis == ast::public => {
1380
                    self.check_attrs(cx, it.attrs, it.span,
1381
                                "missing documentation for a struct");
D
Daniel Micay 已提交
1382
                    for field in sdef.fields.iter() {
1383 1384
                        match field.node.kind {
                            ast::named_field(_, vis) if vis != ast::private => {
1385
                                self.check_attrs(cx, field.node.attrs, field.span,
1386
                                            "missing documentation for a field");
1387
                            }
1388
                            ast::unnamed_field | ast::named_field(*) => {}
1389 1390 1391
                        }
                    }
                }
1392 1393

                ast::item_trait(*) if it.vis == ast::public => {
1394
                    self.check_attrs(cx, it.attrs, it.span,
1395 1396 1397 1398
                                "missing documentation for a trait");
                }

                ast::item_fn(*) if it.vis == ast::public => {
1399
                    self.check_attrs(cx, it.attrs, it.span,
1400 1401 1402 1403
                                "missing documentation for a function");
                }

                _ => {}
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
            }
    }
}

outer_lint_boilerplate_impl!(MissingDocLintVisitor)

fn lint_missing_doc() -> @mut OuterLint {
    @mut MissingDocLintVisitor { stopping_on_items: false } as @mut OuterLint
}

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
/// Checks for use of items with #[deprecated], #[experimental] and
/// #[unstable] (or none of them) attributes.
struct StabilityLintVisitor { stopping_on_items: bool }

impl StabilityLintVisitor {
    fn handle_def(&mut self, sp: Span, def: &ast::Def, cx: @mut Context) {
        let id = ast_util::def_id_of_def(*def);

        let stability = if ast_util::is_local(id) {
            // this crate
            match cx.tcx.items.find(&id.node) {
                Some(ast_node) => {
                    let s = do ast_node.with_attrs |attrs| {
                        do attrs.map_move |a| {
                            attr::find_stability(a.iter().map(|a| a.meta()))
                        }
                    };
                    match s {
                        Some(s) => s,

                        // no possibility of having attributes
                        // (e.g. it's a local variable), so just
                        // ignore it.
                        None => return
                    }
                }
A
Alex Crichton 已提交
1440
                _ => cx.tcx.sess.bug(format!("handle_def: {:?} not found", id))
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
            }
        } else {
            // cross-crate

            let mut s = None;
            // run through all the attributes and take the first
            // stability one.
            do csearch::get_item_attrs(cx.tcx.cstore, id) |meta_items| {
                if s.is_none() {
                    s = attr::find_stability(meta_items.move_iter())
                }
            }
            s
        };

        let (lint, label) = match stability {
            // no stability attributes == Unstable
            None => (unstable, "unmarked"),
            Some(attr::Stability { level: attr::Unstable, _ }) => (unstable, "unstable"),
            Some(attr::Stability { level: attr::Experimental, _ }) => {
                (experimental, "experimental")
            }
            Some(attr::Stability { level: attr::Deprecated, _ }) => (deprecated, "deprecated"),
            _ => return
        };

        let msg = match stability {
            Some(attr::Stability { text: Some(ref s), _ }) => {
A
Alex Crichton 已提交
1469
                format!("use of {} item: {}", label, *s)
1470
            }
A
Alex Crichton 已提交
1471
            _ => format!("use of {} item", label)
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
        };

        cx.span_lint(lint, sp, msg);
    }
}

impl SubitemStoppableVisitor for StabilityLintVisitor {
    fn is_running_on_items(&mut self) -> bool { !self.stopping_on_items }
}

impl Visitor<@mut Context> for StabilityLintVisitor {
    fn visit_item(&mut self, i:@ast::item, e:@mut Context) {
        self.OVERRIDE_visit_item(i, e);
    }

    fn visit_fn(&mut self, fk:&visit::fn_kind, fd:&ast::fn_decl,
                b:&ast::Block, s:Span, n:ast::NodeId, e:@mut Context) {
        self.OVERRIDE_visit_fn(fk, fd, b, s, n, e);
    }

    fn visit_expr(&mut self, ex: @ast::Expr, cx: @mut Context) {
        match ex.node {
            ast::ExprMethodCall(*) |
            ast::ExprPath(*) |
            ast::ExprStruct(*) => {
                match cx.tcx.def_map.find(&ex.id) {
                    Some(def) => self.handle_def(ex.span, def, cx),
                    None => {}
                }
            }
            _ => {}
        }

        visit::walk_expr(self, ex, cx)
    }
}

outer_lint_boilerplate_impl!(StabilityLintVisitor)

fn lint_stability() -> @mut OuterLint {
    @mut StabilityLintVisitor { stopping_on_items: false } as @mut OuterLint
}

1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
struct LintCheckVisitor;

impl Visitor<@mut Context> for LintCheckVisitor {

    fn visit_item(&mut self, it:@ast::item, cx: @mut Context) {

                do cx.with_lint_attrs(it.attrs) {
                    match it.node {
                        ast::item_impl(_, Some(*), _, _) => {
                            cx.in_trait_impl = true;
                        }
                        _ => {}
                    }
                    check_item_ctypes(cx, it);
                    check_item_non_camel_case_types(cx, it);
                    check_item_non_uppercase_statics(cx, it);
                    check_item_heap(cx, it);

                    cx.process(Item(it));
                    visit::walk_item(self, it, cx);
                    cx.in_trait_impl = false;
                }
    }
1538

1539
    fn visit_fn(&mut self, fk:&visit::fn_kind, decl:&ast::fn_decl,
1540
                body:&ast::Block, span:Span, id:ast::NodeId, cx:@mut Context) {
1541

1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
                match *fk {
                    visit::fk_method(_, _, m) => {
                        do cx.with_lint_attrs(m.attrs) {
                            cx.process(Method(m));
                            visit::walk_fn(self,
                                               fk,
                                               decl,
                                               body,
                                               span,
                                               id,
                                               cx);
                        }
                    }
                    _ => {
                        visit::walk_fn(self,
                                           fk,
                                           decl,
                                           body,
                                           span,
                                           id,
                                           cx);
                    }
                }
    }
1566 1567
}

A
Alex Crichton 已提交
1568
pub fn check_crate(tcx: ty::ctxt, crate: &ast::Crate) {
1569 1570 1571 1572 1573
    let cx = @mut Context {
        dict: @get_lint_dict(),
        curr: SmallIntMap::new(),
        tcx: tcx,
        lint_stack: ~[],
1574
        visitors: ~[],
1575
        in_trait_impl: false,
1576
        doc_hidden: false,
1577 1578 1579
    };

    // Install defaults.
D
Daniel Micay 已提交
1580
    for (_, spec) in cx.dict.iter() {
1581
        cx.set_level(spec.lint, spec.default, Default);
1582 1583 1584
    }

    // Install command-line options, overriding defaults.
D
Daniel Micay 已提交
1585
    for &(lint, level) in tcx.sess.opts.lint_opts.iter() {
1586
        cx.set_level(lint, level, CommandLine);
1587 1588
    }

1589
    // Register each of the lint passes with the context
1590 1591 1592 1593 1594 1595 1596 1597
    cx.add_old_lint(lint_while_true());
    cx.add_old_lint(lint_path_statement());
    cx.add_old_lint(lint_heap());
    cx.add_old_lint(lint_type_limits());
    cx.add_old_lint(lint_unused_unsafe());
    cx.add_old_lint(lint_unused_mut());
    cx.add_old_lint(lint_unnecessary_allocations());
    cx.add_old_lint(lint_missing_doc());
1598
    cx.add_old_lint(lint_stability());
1599
    cx.add_lint(lint_session(cx));
1600

1601
    // Actually perform the lint checks (iterating the ast)
1602
    do cx.with_lint_attrs(crate.attrs) {
1603
        cx.process(Crate(crate));
1604

1605
        let mut visitor = LintCheckVisitor;
1606

1607
        visit::walk_crate(&mut visitor, crate, cx);
1608 1609
    }

1610 1611
    // If we missed any lints added to the session, then there's a bug somewhere
    // in the iteration code.
D
Daniel Micay 已提交
1612 1613
    for (id, v) in tcx.sess.lints.iter() {
        for t in v.iter() {
1614 1615
            match *t {
                (lint, span, ref msg) =>
A
Alex Crichton 已提交
1616 1617
                    tcx.sess.span_bug(span, format!("unprocessed lint {:?} at {}: \
                                                  {}",
1618 1619 1620 1621 1622 1623
                                                 lint,
                                                 ast_map::node_id_to_str(
                                                 tcx.items,
                                                 *id,
                                                 token::get_ident_interner()),
                                                 *msg))
1624 1625 1626
            }
        }
    }
1627

1628
    tcx.sess.abort_if_errors();
1629
}