lint.rs 38.9 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;
P
Patrick Walton 已提交
15
use util::ppaux::{ty_to_str};
16

17 18 19 20 21 22 23 24 25 26
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;
27
use extra::smallintmap::SmallIntMap;
28 29
use syntax::attr;
use syntax::codemap::span;
J
John Clements 已提交
30
use syntax::codemap;
31
use syntax::{ast, visit, ast_util};
32

33 34 35 36 37 38 39
/**
 * 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.
 *
40 41 42 43 44
 * 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
45
 * level at that location is.
46
 *
47 48 49 50 51 52
 * 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.
53
 *
54 55 56 57 58 59 60 61 62 63 64 65 66 67
 * At each node of the ast which can modify lint attributes, all known lint
 * passes are also applied.  Each lint pass is a visit::vt<()> structure. These
 * 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.
 *
 * 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.
68
 */
69

70
#[deriving(Clone, Eq)]
71
pub enum lint {
P
Patrick Walton 已提交
72
    ctypes,
73
    unused_imports,
74
    unnecessary_qualification,
75 76
    while_true,
    path_statement,
77
    implicit_copies,
78
    unrecognized_lint,
79
    deprecated_pattern,
80
    non_camel_case_types,
81
    non_uppercase_statics,
82
    type_limits,
83
    default_methods,
84
    unused_unsafe,
85

86 87 88 89
    managed_heap_memory,
    owned_heap_memory,
    heap_memory,

90 91
    unused_variable,
    dead_assignment,
92
    unused_mut,
93
    unnecessary_allocation,
94

95
    missing_doc,
96
    unreachable_code,
97 98

    warnings,
99 100
}

101
pub fn level_to_str(lv: level) -> &'static str {
102
    match lv {
103 104 105 106
      allow => "allow",
      warn => "warn",
      deny => "deny",
      forbid => "forbid"
107 108 109
    }
}

110
#[deriving(Clone, Eq, Ord)]
111
pub enum level {
112
    allow, warn, deny, forbid
113 114
}

115
#[deriving(Clone, Eq)]
116
pub struct LintSpec {
117
    lint: lint,
118
    desc: &'static str,
119
    default: level
120
}
121

122 123 124 125
impl Ord for LintSpec {
    fn lt(&self, other: &LintSpec) -> bool { self.default < other.default }
}

126
pub type LintDict = HashMap<&'static str, LintSpec>;
127 128 129 130 131 132

enum AttributedNode<'self> {
    Item(@ast::item),
    Method(&'self ast::method),
    Crate(@ast::crate),
}
133

134 135 136 137 138 139 140
#[deriving(Eq)]
enum LintSource {
    Node(span),
    Default,
    CommandLine
}

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

    ("unused_imports",
     LintSpec {
        lint: unused_imports,
        desc: "imports that are never used",
        default: warn
     }),

156 157 158 159 160 161 162
    ("unnecessary_qualification",
     LintSpec {
        lint: unnecessary_qualification,
        desc: "detects unnecessarily qualified names",
        default: allow
     }),

S
Sangeun Kim 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 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
     }),

    ("implicit_copies",
     LintSpec {
        lint: implicit_copies,
        desc: "implicit copies of non implicitly copyable data",
        default: warn
     }),

    ("deprecated_pattern",
     LintSpec {
        lint: deprecated_pattern,
        desc: "warn about deprecated uses of pattern bindings",
        default: allow
     }),

    ("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
    ("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
     }),

    ("default_methods",
     LintSpec {
        lint: default_methods,
        desc: "allow default methods",
244
        default: allow
S
Sangeun Kim 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
     }),

    ("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
    }),
274 275 276 277 278 279 280

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

282
    ("missing_doc",
283
     LintSpec {
284 285
        lint: missing_doc,
        desc: "detects missing documentation for public members",
286 287
        default: allow
    }),
288 289 290 291 292 293 294

    ("unreachable_code",
     LintSpec {
        lint: unreachable_code,
        desc: "detects unreachable code",
        default: warn
    }),
295 296 297 298 299 300 301

    ("warnings",
     LintSpec {
        lint: warnings,
        desc: "mass-change the level for lints which produce warnings",
        default: warn
    }),
S
Sangeun Kim 已提交
302 303
];

304 305 306 307
/*
  Pass names should not contain a '-', as the compiler normalizes
  '-' to '_' in command-line flags
 */
308
pub fn get_lint_dict() -> LintDict {
309
    let mut map = HashMap::new();
310
    for lint_table.iter().advance |&(k, v)| {
311
        map.insert(k, v);
312
    }
313
    return map;
314 315
}

316
struct Context {
317 318 319
    // All known lint modes (string versions)
    dict: @LintDict,
    // Current levels of each lint warning
320
    curr: SmallIntMap<(level, LintSource)>,
321 322
    // context we're checking in (used to access fields like sess)
    tcx: ty::ctxt,
323 324 325
    // 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,
326 327 328 329
    // 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,
330 331 332
    // 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.
333
    lint_stack: ~[(lint, level, LintSource)],
334 335 336 337 338
    // 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.
339 340 341 342 343 344 345 346 347
    //
    // 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 used the original visitor's method, although the recursing
    // visitor supplied to the method is the item stopping visitor.
    visitors: ~[(visit::vt<@mut Context>, visit::vt<@mut Context>)],
348
}
349

350
impl Context {
351
    fn get_level(&self, lint: lint) -> level {
352
        match self.curr.find(&(lint as uint)) {
353
          Some(&(lvl, _)) => lvl,
354 355
          None => allow
        }
356 357
    }

358 359 360 361 362 363 364 365
    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) {
366
        if level == allow {
D
Daniel Micay 已提交
367
            self.curr.remove(&(lint as uint));
368
        } else {
369 370 371 372
            self.curr.insert(lint as uint, (level, src));
        }
    }

373
    fn lint_to_str(&self, lint: lint) -> &'static str {
374
        for self.dict.iter().advance |(k, v)| {
375
            if v.lint == lint {
376
                return *k;
377
            }
378
        }
379
        fail!("unregistered lint %?", lint);
380 381
    }

382
    fn span_lint(&self, lint: lint, span: span, msg: &str) {
383
        let (level, src) = match self.curr.find(&(lint as uint)) {
384 385
            None => { return }
            Some(&(warn, src)) => (self.get_level(warnings), src),
386 387
            Some(&pair) => pair,
        };
388
        if level == allow { return }
389 390 391 392 393 394 395

        let mut note = None;
        let msg = match src {
            Default | CommandLine => {
                fmt!("%s [-%c %s%s]", msg, match level {
                        warn => 'W', deny => 'D', forbid => 'F',
                        allow => fail!()
396
                    }, self.lint_to_str(lint).replace("_", "-"),
397 398 399 400 401 402 403 404 405 406 407 408 409
                    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);  }
            allow => fail!(),
        }

410
        for note.iter().advance |&span| {
411 412
            self.tcx.sess.span_note(span, "lint level defined here");
        }
413 414
    }

415
    /**
416
     * Merge the lints specified by any lint attributes into the
417
     * current lint context, call the provided function, then reset the
418
     * lints in effect to their previous state.
419
     */
420 421 422 423 424 425
    fn with_lint_attrs(@mut self, attrs: &[ast::attribute], f: &fn()) {
        // 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;
426
        for each_lint(self.tcx.sess, attrs) |meta, level, lintname| {
427
            let lint = match self.dict.find_equiv(&lintname) {
B
Brian Anderson 已提交
428
              None => {
429
                self.span_lint(
430
                    unrecognized_lint,
431
                    meta.span,
P
Paul Stansifer 已提交
432
                    fmt!("unknown `%s` attribute: `%s`",
433
                         level_to_str(level), lintname));
434
                loop
435
              }
436 437
              Some(lint) => { lint.lint }
            };
438

439 440 441 442 443
            let now = self.get_level(lint);
            if now == forbid && level != forbid {
                self.tcx.sess.span_err(meta.span,
                    fmt!("%s(%s) overruled by outer forbid(%s)",
                         level_to_str(level),
444
                         lintname, lintname));
445
                loop;
446
            }
447

448
            if now != level {
449 450
                let src = self.get_source(lint);
                self.lint_stack.push((lint, now, src));
451
                pushed += 1;
452
                self.set_level(lint, level, Node(meta.span));
453
            }
454
        }
455

456 457
        // detect doc(hidden)
        let mut doc_hidden = false;
458 459
        let r = attr::find_attrs_by_name(attrs, "doc");
        for r.iter().advance |attr| {
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
            match attr::get_meta_item_list(attr.node.value) {
                Some(s) => {
                    if attr::find_meta_items_by_name(s, "hidden").len() > 0 {
                        doc_hidden = true;
                    }
                }
                None => {}
            }
        }
        if doc_hidden && !self.doc_hidden {
            self.doc_hidden = true;
        } else {
            doc_hidden = false;
        }

475
        f();
476

477
        // rollback
478 479 480
        if doc_hidden && self.doc_hidden {
            self.doc_hidden = false;
        }
481
        for pushed.times {
482 483
            let (lint, lvl, src) = self.lint_stack.pop();
            self.set_level(lint, lvl, src);
484
        }
485 486
    }

487
    fn add_lint(&mut self, v: visit::vt<@mut Context>) {
488
        self.visitors.push((v, item_stopping_visitor(v)));
489 490
    }

491
    fn process(@mut self, n: AttributedNode) {
492 493
        // see comment of the `visitors` field in the struct for why there's a
        // pair instead of just one visitor.
494
        match n {
495
            Item(it) => {
496
                for self.visitors.iter().advance |&(orig, stopping)| {
497
                    (orig.visit_item)(it, (self, stopping));
498 499 500
                }
            }
            Crate(c) => {
501
                for self.visitors.iter().advance |&(_, stopping)| {
502
                    visit::visit_crate(c, (self, stopping));
503 504
                }
            }
505 506 507
            // Can't use visit::visit_method_helper because the
            // item_stopping_visitor has overridden visit_fn(&fk_method(... ))
            // to be a no-op, so manually invoke visit_fn.
508
            Method(m) => {
509
                let fk = visit::fk_method(m.ident, &m.generics, m);
510
                for self.visitors.iter().advance |&(orig, stopping)| {
511
                    (orig.visit_fn)(&fk, &m.decl, &m.body, m.span, m.id,
512
                                    (self, stopping));
513 514
                }
            }
515 516 517 518
        }
    }
}

519 520
pub fn each_lint(sess: session::Session,
                 attrs: &[ast::attribute],
521 522 523
                 f: &fn(@ast::meta_item, level, @str) -> bool) -> bool {
    let xs = [allow, warn, deny, forbid];
    for xs.iter().advance |&level| {
524 525
        let level_name = level_to_str(level);
        let attrs = attr::find_attrs_by_name(attrs, level_name);
526
        for attrs.iter().advance |attr| {
527 528 529 530
            let meta = attr.node.value;
            let metas = match meta.node {
                ast::meta_list(_, ref metas) => metas,
                _ => {
531
                    sess.span_err(meta.span, "malformed lint attribute");
532 533 534
                    loop;
                }
            };
535
            for metas.iter().advance |meta| {
536 537 538 539 540 541 542
                match meta.node {
                    ast::meta_word(lintname) => {
                        if !f(*meta, level, lintname) {
                            return false;
                        }
                    }
                    _ => {
543
                        sess.span_err(meta.span, "malformed lint attribute");
544 545 546 547 548
                    }
                }
            }
        }
    }
549
    true
550 551
}

552 553 554 555
// Take a visitor, and modify it so that it will not proceed past subitems.
// This is used to make the simple visitors used for the lint passes
// not traverse into subitems, since that is handled by the outer
// lint visitor.
556
fn item_stopping_visitor<E>(outer: visit::vt<E>) -> visit::vt<E> {
557
    visit::mk_vt(@visit::Visitor {
558 559
        visit_item: |_i, (_e, _v)| { },
        visit_fn: |fk, fd, b, s, id, (e, v)| {
560 561
            match *fk {
                visit::fk_method(*) => {}
562
                _ => (outer.visit_fn)(fk, fd, b, s, id, (e, v))
563 564
            }
        },
565
    .. **outer})
566 567
}

568 569
fn lint_while_true() -> visit::vt<@mut Context> {
    visit::mk_vt(@visit::Visitor {
570
        visit_expr: |e, (cx, vt): (@mut Context, visit::vt<@mut Context>)| {
571 572 573 574 575 576 577 578 579
            match e.node {
                ast::expr_while(cond, _) => {
                    match cond.node {
                        ast::expr_lit(@codemap::spanned {
                            node: ast::lit_bool(true), _}) =>
                        {
                            cx.span_lint(while_true, e.span,
                                         "denote infinite loops with \
                                          loop { ... }");
580
                        }
581
                        _ => ()
582 583
                    }
                }
584 585
                _ => ()
            }
586
            visit::visit_expr(e, (cx, vt));
587
        },
588
        .. *visit::default_visitor()
589
    })
V
Viktor Dahl 已提交
590 591
}

592
fn lint_type_limits() -> visit::vt<@mut Context> {
593
    fn is_valid<T:cmp::Ord>(binop: ast::binop, v: T,
594 595 596 597 598 599 600
            min: T, max: T) -> bool {
        match binop {
            ast::lt => v <= max,
            ast::le => v < max,
            ast::gt => v >= min,
            ast::ge => v > min,
            ast::eq | ast::ne => v >= min && v <= max,
601
            _ => fail!()
602 603 604
        }
    }

605
    fn rev_binop(binop: ast::binop) -> ast::binop {
606 607 608 609 610 611 612 613 614
        match binop {
            ast::lt => ast::gt,
            ast::le => ast::ge,
            ast::gt => ast::lt,
            ast::ge => ast::le,
            _ => binop
        }
    }

615 616
    // for int & uint, be conservative with the warnings, so that the
    // warnings are consistent between 32- and 64-bit platforms
617
    fn int_ty_range(int_ty: ast::int_ty) -> (i64, i64) {
618
        match int_ty {
619
            ast::ty_i =>    (i64::min_value,        i64::max_value),
620 621 622 623 624 625 626 627
            ast::ty_char => (u32::min_value as i64, u32::max_value as i64),
            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)
        }
    }

628
    fn uint_ty_range(uint_ty: ast::uint_ty) -> (u64, u64) {
629
        match uint_ty {
630
            ast::ty_u =>   (u64::min_value,         u64::max_value),
631 632 633 634 635 636 637
            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)
        }
    }

638 639 640 641 642
    fn check_limits(cx: &Context,
                    binop: ast::binop,
                    l: @ast::expr,
                    r: @ast::expr)
                    -> bool {
643 644 645
        let (lit, expr, swap) = match (&l.node, &r.node) {
            (&ast::expr_lit(_), _) => (l, r, true),
            (_, &ast::expr_lit(_)) => (r, l, false),
646 647 648 649
            _ => return true
        };
        // Normalize the binop so that the literal is always on the RHS in
        // the comparison
650
        let norm_binop = if swap {
651 652 653 654
            rev_binop(binop)
        } else {
            binop
        };
655
        match ty::get(ty::expr_ty(cx.tcx, expr)).sty {
656 657 658 659 660 661 662 663 664
            ty::ty_int(int_ty) => {
                let (min, max) = int_ty_range(int_ty);
                let lit_val: i64 = match lit.node {
                    ast::expr_lit(@li) => match li.node {
                        ast::lit_int(v, _) => v,
                        ast::lit_uint(v, _) => v as i64,
                        ast::lit_int_unsuffixed(v) => v,
                        _ => return true
                    },
665
                    _ => fail!()
666 667 668 669 670 671 672 673 674 675 676 677
                };
                is_valid(norm_binop, lit_val, min, max)
            }
            ty::ty_uint(uint_ty) => {
                let (min, max): (u64, u64) = uint_ty_range(uint_ty);
                let lit_val: u64 = match lit.node {
                    ast::expr_lit(@li) => match li.node {
                        ast::lit_int(v, _) => v as u64,
                        ast::lit_uint(v, _) => v,
                        ast::lit_int_unsuffixed(v) => v as u64,
                        _ => return true
                    },
678
                    _ => fail!()
679 680 681 682 683 684 685
                };
                is_valid(norm_binop, lit_val, min, max)
            }
            _ => true
        }
    }

686
    fn is_comparison(binop: ast::binop) -> bool {
687 688 689 690 691 692 693
        match binop {
            ast::eq | ast::lt | ast::le |
            ast::ne | ast::ge | ast::gt => true,
            _ => false
        }
    }

694
    visit::mk_vt(@visit::Visitor {
695
        visit_expr: |e, (cx, vt): (@mut Context, visit::vt<@mut Context>)| {
696
            match e.node {
697
                ast::expr_binary(_, ref binop, l, r) => {
698 699 700 701 702
                    if is_comparison(*binop)
                        && !check_limits(cx, *binop, l, r) {
                        cx.span_lint(type_limits, e.span,
                                     "comparison is useless due to type limits");
                    }
703
                }
704
                _ => ()
705
            }
706
            visit::visit_expr(e, (cx, vt));
707
        },
708

709
        .. *visit::default_visitor()
710
    })
711 712
}

713
fn check_item_default_methods(cx: &Context, item: &ast::item) {
714 715
    match item.node {
        ast::item_trait(_, _, ref methods) => {
716
            for methods.iter().advance |method| {
717 718 719
                match *method {
                    ast::required(*) => {}
                    ast::provided(*) => {
720 721
                        cx.span_lint(default_methods, item.span,
                                     "default methods are experimental");
722 723 724 725 726 727 728 729
                    }
                }
            }
        }
        _ => {}
    }
}

730 731
fn check_item_ctypes(cx: &Context, it: &ast::item) {
    fn check_ty(cx: &Context, ty: &ast::Ty) {
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
        match ty.node {
            ast::ty_path(_, _, id) => {
                match cx.tcx.def_map.get_copy(&id) {
                    ast::def_prim_ty(ast::ty_int(ast::ty_i)) => {
                        cx.span_lint(ctypes, ty.span,
                                "found rust type `int` in foreign module, while \
                                libc::c_int or libc::c_long should be used");
                    }
                    ast::def_prim_ty(ast::ty_uint(ast::ty_u)) => {
                        cx.span_lint(ctypes, ty.span,
                                "found rust type `uint` in foreign module, while \
                                libc::c_uint or libc::c_ulong should be used");
                    }
                    _ => ()
                }
            }
748
            ast::ty_ptr(ref mt) => { check_ty(cx, mt.ty) }
749 750 751
            _ => ()
        }
    }
752

753
    fn check_foreign_fn(cx: &Context, decl: &ast::fn_decl) {
754
        for decl.inputs.iter().advance |in| {
J
James Miller 已提交
755
            check_ty(cx, &in.ty);
756
        }
J
James Miller 已提交
757
        check_ty(cx, &decl.output)
758 759
    }

760
    match it.node {
761
      ast::item_foreign_mod(ref nmod) if !nmod.abis.is_intrinsic() => {
762
        for nmod.items.iter().advance |ni| {
763
            match ni.node {
764 765 766
                ast::foreign_item_fn(ref decl, _, _) => {
                    check_foreign_fn(cx, decl);
                }
J
James Miller 已提交
767
                ast::foreign_item_static(ref t, _) => { check_ty(cx, t); }
768 769
            }
        }
770
      }
B
Brian Anderson 已提交
771
      _ => {/* nothing to do */ }
772 773
    }
}
774

775
fn check_type_for_lint(cx: &Context, lint: lint, span: span, ty: ty::t) {
776
    if cx.get_level(lint) == allow { return }
777

778 779 780 781 782 783 784 785 786 787
    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
    });
788

789 790 791 792 793
    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);
    }
794

795 796 797 798
    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);
799
    }
800
}
801

802
fn check_type(cx: &Context, span: span, ty: ty::t) {
803 804
    let xs = [managed_heap_memory, owned_heap_memory, heap_memory];
    for xs.iter().advance |lint| {
805
        check_type_for_lint(cx, *lint, span, ty);
806
    }
807
}
808

809
fn check_item_heap(cx: &Context, it: &ast::item) {
810 811 812 813 814 815 816 817 818
    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)),
      _ => ()
    }
819

820 821 822
    // If it's a struct, we also have to check the fields' types
    match it.node {
        ast::item_struct(struct_def, _) => {
823
            for struct_def.fields.iter().advance |struct_field| {
824 825 826
                check_type(cx, struct_field.span,
                           ty::node_id_to_type(cx.tcx,
                                               struct_field.node.id));
827 828 829 830
            }
        }
        _ => ()
    }
831
}
832

833 834
fn lint_heap() -> visit::vt<@mut Context> {
    visit::mk_vt(@visit::Visitor {
835
        visit_expr: |e, (cx, vt): (@mut Context, visit::vt<@mut Context>)| {
836 837
            let ty = ty::expr_ty(cx.tcx, e);
            check_type(cx, e.span, ty);
838
            visit::visit_expr(e, (cx, vt));
839
        },
840
        .. *visit::default_visitor()
841
    })
842 843
}

844 845
fn lint_path_statement() -> visit::vt<@mut Context> {
    visit::mk_vt(@visit::Visitor {
846
        visit_stmt: |s, (cx, vt): (@mut Context, visit::vt<@mut Context>)| {
847 848 849 850 851 852 853
            match s.node {
                ast::stmt_semi(
                    @ast::expr { node: ast::expr_path(_), _ },
                    _
                ) => {
                    cx.span_lint(path_statement, s.span,
                                 "path statement with no effect");
854
                }
855 856
                _ => ()
            }
857
            visit::visit_stmt(s, (cx, vt));
858
        },
859
        .. *visit::default_visitor()
860
    })
861 862
}

863
fn check_item_non_camel_case_types(cx: &Context, it: &ast::item) {
P
Paul Stansifer 已提交
864 865
    fn is_camel_case(cx: ty::ctxt, ident: ast::ident) -> bool {
        let ident = cx.sess.str_of(ident);
P
Patrick Walton 已提交
866
        assert!(!ident.is_empty());
867
        let ident = ident.trim_chars(&'_');
868 869 870 871

        // 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() &&
872 873 874
            !ident.contains_char('_')
    }

875
    fn check_case(cx: &Context, ident: ast::ident, span: span) {
876 877 878 879
        if !is_camel_case(cx.tcx, ident) {
            cx.span_lint(non_camel_case_types, span,
                         "type, variant, or trait should have \
                          a camel case identifier");
880 881 882
        }
    }

883
    match it.node {
E
Erick Tryzelaar 已提交
884 885
        ast::item_ty(*) | ast::item_struct(*) |
        ast::item_trait(*) => {
886
            check_case(cx, it.ident, it.span)
887
        }
E
Erick Tryzelaar 已提交
888
        ast::item_enum(ref enum_definition, _) => {
889
            check_case(cx, it.ident, it.span);
890
            for enum_definition.variants.iter().advance |variant| {
891
                check_case(cx, variant.node.name, variant.span);
E
Erick Tryzelaar 已提交
892 893 894
            }
        }
        _ => ()
895 896 897
    }
}

898 899 900 901 902 903 904 905
fn check_item_non_uppercase_statics(cx: &Context, it: &ast::item) {
    match it.node {
        // only check static constants
        ast::item_static(_, ast::m_imm, _) => {
            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)
906
            if s.iter().any(|c| c.is_lowercase()) {
907 908 909 910 911 912 913 914
                cx.span_lint(non_uppercase_statics, it.span,
                             "static constant should have an uppercase identifier");
            }
        }
        _ => {}
    }
}

915 916
fn lint_unused_unsafe() -> visit::vt<@mut Context> {
    visit::mk_vt(@visit::Visitor {
917
        visit_expr: |e, (cx, vt): (@mut Context, visit::vt<@mut Context>)| {
918
            match e.node {
919 920
                ast::expr_block(ref blk) if blk.rules == ast::unsafe_blk => {
                    if !cx.tcx.used_unsafe.contains(&blk.id) {
921 922 923
                        cx.span_lint(unused_unsafe, blk.span,
                                     "unnecessary `unsafe` block");
                    }
924
                }
925
                _ => ()
926
            }
927
            visit::visit_expr(e, (cx, vt));
928 929
        },
        .. *visit::default_visitor()
930
    })
931 932
}

933 934
fn lint_unused_mut() -> visit::vt<@mut Context> {
    fn check_pat(cx: &Context, p: @ast::pat) {
935 936
        let mut used = false;
        let mut bindings = 0;
937 938
        do pat_util::pat_bindings(cx.tcx.def_map, p) |_, id, _, _| {
            used = used || cx.tcx.used_mut_nodes.contains(&id);
939 940 941 942
            bindings += 1;
        }
        if !used {
            let msg = if bindings == 1 {
S
Seo Sanghyeon 已提交
943
                "variable does not need to be mutable"
944
            } else {
S
Seo Sanghyeon 已提交
945
                "variables do not need to be mutable"
946
            };
947
            cx.span_lint(unused_mut, p.span, msg);
948
        }
949
    }
950

951
    fn visit_fn_decl(cx: &Context, fd: &ast::fn_decl) {
952
        for fd.inputs.iter().advance |arg| {
953
            if arg.is_mutbl {
954
                check_pat(cx, arg.pat);
955 956
            }
        }
957
    }
958

959
    visit::mk_vt(@visit::Visitor {
960
        visit_local: |l, (cx, vt): (@mut Context, visit::vt<@mut Context>)| {
961
            if l.node.is_mutbl {
962
                check_pat(cx, l.node.pat);
963
            }
964
            visit::visit_local(l, (cx, vt));
965
        },
966
        visit_fn: |a, fd, b, c, d, (cx, vt)| {
967
            visit_fn_decl(cx, fd);
968
            visit::visit_fn(a, fd, b, c, d, (cx, vt));
969
        },
970
        visit_ty_method: |tm, (cx, vt)| {
971
            visit_fn_decl(cx, &tm.decl);
972
            visit::visit_ty_method(tm, (cx, vt));
973
        },
974
        visit_trait_method: |tm, (cx, vt)| {
975
            match *tm {
976 977
                ast::required(ref tm) => visit_fn_decl(cx, &tm.decl),
                ast::provided(m) => visit_fn_decl(cx, &m.decl)
978
            }
979
            visit::visit_trait_method(tm, (cx, vt));
980
        },
981
        .. *visit::default_visitor()
982
    })
983 984
}

985 986
fn lint_session() -> visit::vt<@mut Context> {
    ast_util::id_visitor(|id, cx: @mut Context| {
987 988 989
        match cx.tcx.sess.lints.pop(&id) {
            None => {},
            Some(l) => {
990
                for l.consume_iter().advance |(lint, span, msg)| {
991
                    cx.span_lint(lint, span, msg)
992
                }
993 994
            }
        }
995
    })
996 997
}

998
fn lint_unnecessary_allocations() -> visit::vt<@mut Context> {
999 1000
    // Warn if string and vector literals with sigils are immediately borrowed.
    // Those can have the sigil removed.
1001
    fn check(cx: &Context, e: &ast::expr) {
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        match e.node {
            ast::expr_vstore(e2, ast::expr_vstore_uniq) |
            ast::expr_vstore(e2, ast::expr_vstore_box) => {
                match e2.node {
                    ast::expr_lit(@codemap::spanned{
                            node: ast::lit_str(*), _}) |
                    ast::expr_vec(*) => {}
                    _ => return
                }
            }

            _ => return
        }

1016 1017 1018
        match cx.tcx.adjustments.find_copy(&e.id) {
            Some(@ty::AutoDerefRef(ty::AutoDerefRef {
                autoref: Some(ty::AutoBorrowVec(*)), _ })) => {
1019 1020 1021 1022 1023 1024 1025 1026 1027
                cx.span_lint(unnecessary_allocation,
                             e.span, "unnecessary allocation, the sigil can be \
                                      removed");
            }

            _ => ()
        }
    }

1028
    visit::mk_vt(@visit::Visitor {
1029
        visit_expr: |e, (cx, vt): (@mut Context, visit::vt<@mut Context>)| {
1030
            check(cx, e);
1031
            visit::visit_expr(e, (cx, vt));
1032 1033
        },
        .. *visit::default_visitor()
1034 1035 1036
    })
}

1037 1038 1039
fn lint_missing_doc() -> visit::vt<@mut Context> {
    fn check_attrs(cx: @mut Context, attrs: &[ast::attribute],
                   sp: span, msg: &str) {
1040 1041 1042 1043 1044 1045
        // 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
1046
        if attrs.iter().any(|a| a.node.is_sugared_doc) { return }
1047 1048 1049

        // otherwise, warn!
        cx.span_lint(missing_doc, sp, msg);
1050 1051
    }

1052
    visit::mk_vt(@visit::Visitor {
1053
        visit_ty_method: |m, (cx, vt)| {
1054 1055 1056 1057
            // All ty_method objects are linted about because they're part of a
            // trait (no visibility)
            check_attrs(cx, m.attrs, m.span,
                        "missing documentation for a method");
1058
            visit::visit_ty_method(m, (cx, vt));
1059
        },
1060

1061
        visit_fn: |fk, d, b, sp, id, (cx, vt)| {
1062 1063 1064 1065 1066 1067 1068 1069 1070
            // Only warn about explicitly public methods. Soon implicit
            // public-ness will hopefully be going away.
            match *fk {
                visit::fk_method(_, _, m) if m.vis == ast::public => {
                    // If we're in a trait implementation, no need to duplicate
                    // documentation
                    if !cx.in_trait_impl {
                        check_attrs(cx, m.attrs, sp,
                                    "missing documentation for a method");
1071 1072
                    }
                }
1073

1074 1075
                _ => {}
            }
1076
            visit::visit_fn(fk, d, b, sp, id, (cx, vt));
1077 1078
        },

1079
        visit_item: |it, (cx, vt)| {
1080 1081 1082 1083 1084 1085 1086
            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 => {
                    check_attrs(cx, it.attrs, it.span,
                                "missing documentation for a struct");
1087
                    for sdef.fields.iter().advance |field| {
1088 1089 1090 1091
                        match field.node.kind {
                            ast::named_field(_, vis) if vis != ast::private => {
                                check_attrs(cx, field.node.attrs, field.span,
                                            "missing documentation for a field");
1092
                            }
1093
                            ast::unnamed_field | ast::named_field(*) => {}
1094 1095 1096
                        }
                    }
                }
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

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

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

                _ => {}
1109
            };
1110

1111
            visit::visit_item(it, (cx, vt));
1112
        },
1113

1114
        .. *visit::default_visitor()
1115 1116 1117
    })
}

1118
pub fn check_crate(tcx: ty::ctxt, crate: @ast::crate) {
1119 1120 1121 1122 1123
    let cx = @mut Context {
        dict: @get_lint_dict(),
        curr: SmallIntMap::new(),
        tcx: tcx,
        lint_stack: ~[],
1124
        visitors: ~[],
1125
        in_trait_impl: false,
1126
        doc_hidden: false,
1127 1128 1129 1130
    };

    // Install defaults.
    for cx.dict.each_value |spec| {
1131
        cx.set_level(spec.lint, spec.default, Default);
1132 1133 1134
    }

    // Install command-line options, overriding defaults.
1135
    for tcx.sess.opts.lint_opts.iter().advance |&(lint, level)| {
1136
        cx.set_level(lint, level, CommandLine);
1137 1138
    }

1139
    // Register each of the lint passes with the context
1140 1141 1142 1143 1144 1145 1146 1147
    cx.add_lint(lint_while_true());
    cx.add_lint(lint_path_statement());
    cx.add_lint(lint_heap());
    cx.add_lint(lint_type_limits());
    cx.add_lint(lint_unused_unsafe());
    cx.add_lint(lint_unused_mut());
    cx.add_lint(lint_session());
    cx.add_lint(lint_unnecessary_allocations());
1148
    cx.add_lint(lint_missing_doc());
1149

1150
    // Actually perform the lint checks (iterating the ast)
1151
    do cx.with_lint_attrs(crate.node.attrs) {
1152
        cx.process(Crate(crate));
1153

1154 1155
        visit::visit_crate(crate, (cx, visit::mk_vt(@visit::Visitor {
            visit_item: |it, (cx, vt): (@mut Context, visit::vt<@mut Context>)| {
1156
                do cx.with_lint_attrs(it.attrs) {
1157 1158 1159 1160 1161 1162
                    match it.node {
                        ast::item_impl(_, Some(*), _, _) => {
                            cx.in_trait_impl = true;
                        }
                        _ => {}
                    }
1163 1164
                    check_item_ctypes(cx, it);
                    check_item_non_camel_case_types(cx, it);
1165
                    check_item_non_uppercase_statics(cx, it);
1166 1167 1168 1169
                    check_item_default_methods(cx, it);
                    check_item_heap(cx, it);

                    cx.process(Item(it));
1170
                    visit::visit_item(it, (cx, vt));
1171
                    cx.in_trait_impl = false;
1172 1173
                }
            },
1174
            visit_fn: |fk, decl, body, span, id, (cx, vt)| {
1175 1176 1177
                match *fk {
                    visit::fk_method(_, _, m) => {
                        do cx.with_lint_attrs(m.attrs) {
1178
                            cx.process(Method(m));
1179
                            visit::visit_fn(fk, decl, body, span, id, (cx, vt));
1180 1181 1182
                        }
                    }
                    _ => {
1183
                        visit::visit_fn(fk, decl, body, span, id, (cx, vt));
1184 1185 1186 1187
                    }
                }
            },
            .. *visit::default_visitor()
1188
        })));
1189 1190
    }

1191 1192
    // If we missed any lints added to the session, then there's a bug somewhere
    // in the iteration code.
1193
    for tcx.sess.lints.iter().advance |(_, v)| {
1194
        for v.iter().advance |t| {
1195 1196 1197 1198 1199 1200 1201
            match *t {
                (lint, span, ref msg) =>
                    tcx.sess.span_bug(span, fmt!("unprocessed lint %?: %s",
                                                 lint, *msg))
            }
        }
    }
1202

1203
    tcx.sess.abort_if_errors();
1204
}