lint.rs 37.1 KB
Newer Older
G
Geoff Hill 已提交
1
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// 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 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
//! 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.
//!
//! 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
//! level at that location is.
//!
//! 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.
//!
//! 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 few linting functions and
//! modify the Context visitor appropriately. If you're adding lints from the
//! Context itself, span_lint should be used instead of add_lint.
35

36
use driver::session;
P
Patrick Walton 已提交
37
use middle::ty;
38
use middle::pat_util;
39
use metadata::csearch;
P
Patrick Walton 已提交
40
use util::ppaux::{ty_to_str};
41

42 43 44 45 46 47 48 49 50 51
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;
52
use extra::smallintmap::SmallIntMap;
53
use syntax::ast_map;
54
use syntax::attr;
55
use syntax::attr::{AttrMetaMethods, AttributeMethods};
56
use syntax::codemap::Span;
J
John Clements 已提交
57
use syntax::codemap;
58
use syntax::parse::token;
59 60
use syntax::{ast, ast_util, visit};
use syntax::visit::Visitor;
61

62
#[deriving(Clone, Eq)]
63
pub enum lint {
P
Patrick Walton 已提交
64
    ctypes,
65
    cstack,
66
    unused_imports,
67
    unnecessary_qualification,
68 69
    while_true,
    path_statement,
70
    unrecognized_lint,
71
    non_camel_case_types,
72
    non_uppercase_statics,
73
    non_uppercase_pattern_statics,
74
    type_limits,
75
    unused_unsafe,
76

77 78 79 80
    managed_heap_memory,
    owned_heap_memory,
    heap_memory,

81 82
    unused_variable,
    dead_assignment,
83
    unused_mut,
84
    unnecessary_allocation,
85

86
    missing_doc,
87
    unreachable_code,
88

89 90 91 92
    deprecated,
    experimental,
    unstable,

93
    warnings,
94 95
}

96
pub fn level_to_str(lv: level) -> &'static str {
97
    match lv {
98 99 100 101
      allow => "allow",
      warn => "warn",
      deny => "deny",
      forbid => "forbid"
102 103 104
    }
}

105
#[deriving(Clone, Eq, Ord)]
106
pub enum level {
107
    allow, warn, deny, forbid
108 109
}

110
#[deriving(Clone, Eq)]
111
pub struct LintSpec {
112
    lint: lint,
113
    desc: &'static str,
114
    default: level
115
}
116

117 118 119 120
impl Ord for LintSpec {
    fn lt(&self, other: &LintSpec) -> bool { self.default < other.default }
}

121
pub type LintDict = HashMap<&'static str, LintSpec>;
122

123 124
#[deriving(Eq)]
enum LintSource {
125
    Node(Span),
126 127 128 129
    Default,
    CommandLine
}

S
Sangeun Kim 已提交
130 131 132 133
static lint_table: &'static [(&'static str, LintSpec)] = &[
    ("ctypes",
     LintSpec {
        lint: ctypes,
134
        desc: "proper use of std::libc types in foreign modules",
S
Sangeun Kim 已提交
135 136 137
        default: warn
     }),

138 139 140 141 142 143 144
    ("cstack",
     LintSpec {
        lint: cstack,
        desc: "only invoke foreign functions from fixedstacksegment fns",
        default: deny
     }),

S
Sangeun Kim 已提交
145 146 147 148 149 150 151
    ("unused_imports",
     LintSpec {
        lint: unused_imports,
        desc: "imports that are never used",
        default: warn
     }),

152 153 154 155 156 157 158
    ("unnecessary_qualification",
     LintSpec {
        lint: unnecessary_qualification,
        desc: "detects unnecessarily qualified names",
        default: allow
     }),

S
Sangeun Kim 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    ("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
     }),

187 188 189 190
    ("non_uppercase_statics",
     LintSpec {
         lint: non_uppercase_statics,
         desc: "static constants should have uppercase identifiers",
191
         default: allow
192 193
     }),

194 195 196
    ("non_uppercase_pattern_statics",
     LintSpec {
         lint: non_uppercase_pattern_statics,
197
         desc: "static constants in match patterns should be all caps",
198 199 200
         default: warn
     }),

S
Sangeun Kim 已提交
201 202 203 204 205 206 207 208 209 210 211 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
    ("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
    }),
256 257 258 259 260 261 262

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

264
    ("missing_doc",
265
     LintSpec {
266 267
        lint: missing_doc,
        desc: "detects missing documentation for public members",
268 269
        default: allow
    }),
270 271 272 273 274 275 276

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

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    ("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
    }),

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

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

319
struct Context {
320 321 322
    // All known lint modes (string versions)
    dict: @LintDict,
    // Current levels of each lint warning
323
    cur: SmallIntMap<(level, LintSource)>,
324 325
    // context we're checking in (used to access fields like sess)
    tcx: ty::ctxt,
326

327 328 329
    // 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.
330
    lint_stack: ~[(lint, level, LintSource)],
331
}
332

333
impl Context {
334
    fn get_level(&self, lint: lint) -> level {
335
        match self.cur.find(&(lint as uint)) {
336
          Some(&(lvl, _)) => lvl,
337 338
          None => allow
        }
339 340
    }

341
    fn get_source(&self, lint: lint) -> LintSource {
342
        match self.cur.find(&(lint as uint)) {
343 344 345 346 347 348
          Some(&(_, src)) => src,
          None => Default
        }
    }

    fn set_level(&mut self, lint: lint, level: level, src: LintSource) {
349
        if level == allow {
350
            self.cur.remove(&(lint as uint));
351
        } else {
352
            self.cur.insert(lint as uint, (level, src));
353 354 355
        }
    }

356
    fn lint_to_str(&self, lint: lint) -> &'static str {
D
Daniel Micay 已提交
357
        for (k, v) in self.dict.iter() {
358
            if v.lint == lint {
359
                return *k;
360
            }
361
        }
A
Alex Crichton 已提交
362
        fail2!("unregistered lint {:?}", lint);
363 364
    }

365
    fn span_lint(&self, lint: lint, span: Span, msg: &str) {
366
        let (level, src) = match self.cur.find(&(lint as uint)) {
367 368
            None => { return }
            Some(&(warn, src)) => (self.get_level(warnings), src),
369 370
            Some(&pair) => pair,
        };
371
        if level == allow { return }
372 373 374

        let mut note = None;
        let msg = match src {
G
Geoff Hill 已提交
375 376 377 378 379 380 381
            Default => {
                format!("{}, \\#[{}({})] on by default", msg,
                    level_to_str(level), self.lint_to_str(lint))
            },
            CommandLine => {
                format!("{} [-{} {}]", msg,
                    match level {
382
                        warn => 'W', deny => 'D', forbid => 'F',
A
Alex Crichton 已提交
383
                        allow => fail2!()
G
Geoff Hill 已提交
384
                    }, self.lint_to_str(lint).replace("_", "-"))
385 386 387 388 389 390 391 392 393
            },
            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 已提交
394
            allow => fail2!(),
395 396
        }

D
Daniel Micay 已提交
397
        for &span in note.iter() {
398 399
            self.tcx.sess.span_note(span, "lint level defined here");
        }
400 401
    }

402
    /**
403
     * Merge the lints specified by any lint attributes into the
404
     * current lint context, call the provided function, then reset the
405
     * lints in effect to their previous state.
406
     */
407 408
    fn with_lint_attrs(&mut self, attrs: &[ast::Attribute],
                       f: &fn(&mut Context)) {
409 410 411 412 413
        // 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;
414 415 416 417 418 419
        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 已提交
420
                        format!("unknown `{}` attribute: `{}`",
421 422 423 424 425 426 427
                        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 已提交
428
                        format!("{}({}) overruled by outer forbid({})",
429 430 431 432 433 434 435 436 437
                        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));
                    }
                }
438
            }
439 440
            true
        };
441

442
        f(self);
443

444
        // rollback
445
        do pushed.times {
446 447
            let (lint, lvl, src) = self.lint_stack.pop();
            self.set_level(lint, lvl, src);
448
        }
449 450
    }

451 452 453 454 455 456 457
    fn visit_ids(&self, f: &fn(&mut ast_util::IdVisitor<Context>)) {
        let mut v = ast_util::IdVisitor {
            operation: self,
            pass_through_items: false,
            visited_outermost: false,
        };
        f(&mut v);
458 459 460
    }
}

461
pub fn each_lint(sess: session::Session,
462 463
                 attrs: &[ast::Attribute],
                 f: &fn(@ast::MetaItem, level, @str) -> bool) -> bool {
464
    let xs = [allow, warn, deny, forbid];
D
Daniel Micay 已提交
465
    for &level in xs.iter() {
466
        let level_name = level_to_str(level);
D
Daniel Micay 已提交
467
        for attr in attrs.iter().filter(|m| level_name == m.name()) {
468 469
            let meta = attr.node.value;
            let metas = match meta.node {
470
                ast::MetaList(_, ref metas) => metas,
471
                _ => {
472
                    sess.span_err(meta.span, "malformed lint attribute");
473
                    continue;
474 475
                }
            };
D
Daniel Micay 已提交
476
            for meta in metas.iter() {
477
                match meta.node {
478
                    ast::MetaWord(lintname) => {
479 480 481 482 483
                        if !f(*meta, level, lintname) {
                            return false;
                        }
                    }
                    _ => {
484
                        sess.span_err(meta.span, "malformed lint attribute");
485 486 487 488 489
                    }
                }
            }
        }
    }
490
    true
491 492
}

493 494 495 496 497 498 499 500 501
fn check_while_true_expr(cx: &Context, e: &ast::Expr) {
    match e.node {
        ast::ExprWhile(cond, _) => {
            match cond.node {
                ast::ExprLit(@codemap::Spanned {
                    node: ast::lit_bool(true), _}) =>
                {
                    cx.span_lint(while_true, e.span,
                                 "denote infinite loops with loop { ... }");
502
                }
503 504
                _ => ()
            }
505 506
        }
        _ => ()
507 508 509
    }
}

510 511 512 513 514 515
fn check_type_limits(cx: &Context, e: &ast::Expr) {
    return match e.node {
        ast::ExprBinary(_, binop, l, r) => {
            if is_comparison(binop) && !check_limits(cx.tcx, binop, l, r) {
                cx.span_lint(type_limits, e.span,
                             "comparison is useless due to type limits");
516 517
            }
        }
518 519
        _ => ()
    };
520

521 522
    fn is_valid<T:cmp::Ord>(binop: ast::BinOp, v: T,
                            min: T, max: T) -> bool {
523
        match binop {
524 525 526 527 528
            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 已提交
529
            _ => fail2!()
530 531 532
        }
    }

533
    fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
534
        match binop {
535 536 537 538
            ast::BiLt => ast::BiGt,
            ast::BiLe => ast::BiGe,
            ast::BiGt => ast::BiLt,
            ast::BiGe => ast::BiLe,
539 540 541 542
            _ => binop
        }
    }

543 544
    // for int & uint, be conservative with the warnings, so that the
    // warnings are consistent between 32- and 64-bit platforms
545
    fn int_ty_range(int_ty: ast::int_ty) -> (i64, i64) {
546
        match int_ty {
547
            ast::ty_i =>    (i64::min_value,        i64::max_value),
548 549 550 551 552 553 554
            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)
        }
    }

555
    fn uint_ty_range(uint_ty: ast::uint_ty) -> (u64, u64) {
556
        match uint_ty {
557
            ast::ty_u =>   (u64::min_value,         u64::max_value),
558 559 560 561 562 563 564
            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)
        }
    }

565 566
    fn check_limits(tcx: ty::ctxt, binop: ast::BinOp,
                    l: &ast::Expr, r: &ast::Expr) -> bool {
567
        let (lit, expr, swap) = match (&l.node, &r.node) {
568 569
            (&ast::ExprLit(_), _) => (l, r, true),
            (_, &ast::ExprLit(_)) => (r, l, false),
570 571 572 573
            _ => return true
        };
        // Normalize the binop so that the literal is always on the RHS in
        // the comparison
574 575
        let norm_binop = if swap { rev_binop(binop) } else { binop };
        match ty::get(ty::expr_ty(tcx, expr)).sty {
576
            ty::ty_int(int_ty) => {
577
                let (min, max) = int_ty_range(int_ty);
578
                let lit_val: i64 = match lit.node {
579
                    ast::ExprLit(li) => match li.node {
580 581 582 583 584
                        ast::lit_int(v, _) => v,
                        ast::lit_uint(v, _) => v as i64,
                        ast::lit_int_unsuffixed(v) => v,
                        _ => return true
                    },
A
Alex Crichton 已提交
585
                    _ => fail2!()
586
                };
587
                is_valid(norm_binop, lit_val, min, max)
588 589
            }
            ty::ty_uint(uint_ty) => {
590
                let (min, max): (u64, u64) = uint_ty_range(uint_ty);
591
                let lit_val: u64 = match lit.node {
592
                    ast::ExprLit(li) => match li.node {
593 594 595 596 597
                        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 已提交
598
                    _ => fail2!()
599
                };
600
                is_valid(norm_binop, lit_val, min, max)
601 602 603 604 605
            }
            _ => true
        }
    }

606
    fn is_comparison(binop: ast::BinOp) -> bool {
607
        match binop {
608 609
            ast::BiEq | ast::BiLt | ast::BiLe |
            ast::BiNe | ast::BiGe | ast::BiGt => true,
610 611 612
            _ => false
        }
    }
613 614
}

615 616
fn check_item_ctypes(cx: &Context, it: &ast::item) {
    fn check_ty(cx: &Context, ty: &ast::Ty) {
617 618 619
        match ty.node {
            ast::ty_path(_, _, id) => {
                match cx.tcx.def_map.get_copy(&id) {
620
                    ast::DefPrimTy(ast::ty_int(ast::ty_i)) => {
621 622 623 624
                        cx.span_lint(ctypes, ty.span,
                                "found rust type `int` in foreign module, while \
                                libc::c_int or libc::c_long should be used");
                    }
625
                    ast::DefPrimTy(ast::ty_uint(ast::ty_u)) => {
626 627 628 629 630 631 632
                        cx.span_lint(ctypes, ty.span,
                                "found rust type `uint` in foreign module, while \
                                libc::c_uint or libc::c_ulong should be used");
                    }
                    _ => ()
                }
            }
633
            ast::ty_ptr(ref mt) => { check_ty(cx, mt.ty) }
634 635 636
            _ => ()
        }
    }
637

638
    fn check_foreign_fn(cx: &Context, decl: &ast::fn_decl) {
D
Daniel Micay 已提交
639
        for input in decl.inputs.iter() {
640
            check_ty(cx, &input.ty);
641
        }
J
James Miller 已提交
642
        check_ty(cx, &decl.output)
643 644
    }

645
    match it.node {
646
      ast::item_foreign_mod(ref nmod) if !nmod.abis.is_intrinsic() => {
D
Daniel Micay 已提交
647
        for ni in nmod.items.iter() {
648
            match ni.node {
649
                ast::foreign_item_fn(ref decl, _) => {
650 651
                    check_foreign_fn(cx, decl);
                }
J
James Miller 已提交
652
                ast::foreign_item_static(ref t, _) => { check_ty(cx, t); }
653 654
            }
        }
655
      }
B
Brian Anderson 已提交
656
      _ => {/* nothing to do */ }
657 658
    }
}
659

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
fn check_heap_type(cx: &Context, span: Span, ty: ty::t) {
    let xs = [managed_heap_memory, owned_heap_memory, heap_memory];
    for &lint in xs.iter() {
        if cx.get_level(lint) == allow { continue }

        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
        });
675

676 677 678 679 680
        if n_uniq > 0 && lint != managed_heap_memory {
            let s = ty_to_str(cx.tcx, ty);
            let m = format!("type uses owned (~ type) pointers: {}", s);
            cx.span_lint(lint, span, m);
        }
681

682 683 684 685 686
        if n_box > 0 && lint != owned_heap_memory {
            let s = ty_to_str(cx.tcx, ty);
            let m = format!("type uses managed (@ type) pointers: {}", s);
            cx.span_lint(lint, span, m);
        }
687
    }
688
}
689

690
fn check_heap_item(cx: &Context, it: &ast::item) {
691
    match it.node {
692 693 694 695 696 697 698
        ast::item_fn(*) |
        ast::item_ty(*) |
        ast::item_enum(*) |
        ast::item_struct(*) => check_heap_type(cx, it.span,
                                               ty::node_id_to_type(cx.tcx,
                                                                   it.id)),
        _ => ()
699
    }
700

701 702 703
    // If it's a struct, we also have to check the fields' types
    match it.node {
        ast::item_struct(struct_def, _) => {
D
Daniel Micay 已提交
704
            for struct_field in struct_def.fields.iter() {
705 706 707
                check_heap_type(cx, struct_field.span,
                                ty::node_id_to_type(cx.tcx,
                                                    struct_field.node.id));
708 709 710 711
            }
        }
        _ => ()
    }
712
}
713

714 715 716
fn check_heap_expr(cx: &Context, e: &ast::Expr) {
    let ty = ty::expr_ty(cx.tcx, e);
    check_heap_type(cx, e.span, ty);
717 718
}

719 720 721 722 723 724 725
fn check_path_statement(cx: &Context, s: &ast::Stmt) {
    match s.node {
        ast::StmtSemi(@ast::Expr { node: ast::ExprPath(_), _ }, _) => {
            cx.span_lint(path_statement, s.span,
                         "path statement with no effect");
        }
        _ => ()
726 727 728
    }
}

729
fn check_item_non_camel_case_types(cx: &Context, it: &ast::item) {
730
    fn is_camel_case(cx: ty::ctxt, ident: ast::Ident) -> bool {
P
Paul Stansifer 已提交
731
        let ident = cx.sess.str_of(ident);
P
Patrick Walton 已提交
732
        assert!(!ident.is_empty());
733
        let ident = ident.trim_chars(&'_');
734 735 736 737

        // 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() &&
738 739 740
            !ident.contains_char('_')
    }

741
    fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
742
        if !is_camel_case(cx.tcx, ident) {
743 744
            cx.span_lint(
                non_camel_case_types, span,
A
Alex Crichton 已提交
745
                format!("{} `{}` should have a camel case identifier",
746
                    sort, cx.tcx.sess.str_of(ident)));
747 748 749
        }
    }

750
    match it.node {
751 752 753
        ast::item_ty(*) | ast::item_struct(*) => {
            check_case(cx, "type", it.ident, it.span)
        }
E
Erick Tryzelaar 已提交
754
        ast::item_trait(*) => {
755
            check_case(cx, "trait", it.ident, it.span)
756
        }
E
Erick Tryzelaar 已提交
757
        ast::item_enum(ref enum_definition, _) => {
758
            check_case(cx, "type", it.ident, it.span);
D
Daniel Micay 已提交
759
            for variant in enum_definition.variants.iter() {
760
                check_case(cx, "variant", variant.node.name, variant.span);
E
Erick Tryzelaar 已提交
761 762 763
            }
        }
        _ => ()
764 765 766
    }
}

767 768 769
fn check_item_non_uppercase_statics(cx: &Context, it: &ast::item) {
    match it.node {
        // only check static constants
770
        ast::item_static(_, ast::MutImmutable, _) => {
771 772 773 774
            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)
775
            if s.iter().any(|c| c.is_lowercase()) {
776 777 778 779 780 781 782 783
                cx.span_lint(non_uppercase_statics, it.span,
                             "static constant should have an uppercase identifier");
            }
        }
        _ => {}
    }
}

784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) {
    // Lint for constants that look like binding identifiers (#7526)
    match (&p.node, cx.tcx.def_map.find(&p.id)) {
        (&ast::PatIdent(_, ref path, _), Some(&ast::DefStatic(_, false))) => {
            // last identifier alone is right choice for this lint.
            let ident = path.segments.last().identifier;
            let s = cx.tcx.sess.str_of(ident);
            if s.iter().any(|c| c.is_lowercase()) {
                cx.span_lint(non_uppercase_pattern_statics, path.span,
                             "static constant in pattern should be all caps");
            }
        }
        _ => {}
    }
}

800 801 802 803 804 805 806 807 808
fn check_unused_unsafe(cx: &Context, e: &ast::Expr) {
    match e.node {
        // Don't warn about generated blocks, that'll just pollute the
        // output.
        ast::ExprBlock(ref blk) => {
            if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
                !cx.tcx.used_unsafe.contains(&blk.id) {
                cx.span_lint(unused_unsafe, blk.span,
                             "unnecessary `unsafe` block");
809 810
            }
        }
811
        _ => ()
812
    }
813 814
}

815 816 817 818 819 820
fn check_unused_mut_pat(cx: &Context, p: @ast::Pat) {
    let mut used = false;
    let mut bindings = 0;
    do pat_util::pat_bindings(cx.tcx.def_map, p) |_, id, _, _| {
        used = used || cx.tcx.used_mut_nodes.contains(&id);
        bindings += 1;
821
    }
822 823 824 825 826 827 828
    if !used {
        let msg = if bindings == 1 {
            "variable does not need to be mutable"
        } else {
            "variables do not need to be mutable"
        };
        cx.span_lint(unused_mut, p.span, msg);
829 830 831
    }
}

832 833 834 835
fn check_unused_mut_fn_decl(cx: &Context, fd: &ast::fn_decl) {
    for arg in fd.inputs.iter() {
        if arg.is_mutbl {
            check_unused_mut_pat(cx, arg.pat);
836
        }
837 838 839
    }
}

840
fn check_unnecessary_allocation(cx: &Context, e: &ast::Expr) {
841 842
    // Warn if string and vector literals with sigils are immediately borrowed.
    // Those can have the sigil removed.
843 844 845 846 847 848 849
    match e.node {
        ast::ExprVstore(e2, ast::ExprVstoreUniq) |
        ast::ExprVstore(e2, ast::ExprVstoreBox) => {
            match e2.node {
                ast::ExprLit(@codemap::Spanned{node: ast::lit_str(*), _}) |
                ast::ExprVec(*) => {}
                _ => return
850 851 852
            }
        }

853
        _ => return
854 855
    }

856 857 858 859 860 861
    match cx.tcx.adjustments.find_copy(&e.id) {
        Some(@ty::AutoDerefRef(ty::AutoDerefRef {
            autoref: Some(ty::AutoBorrowVec(*)), _ })) => {
            cx.span_lint(unnecessary_allocation, e.span,
                         "unnecessary allocation, the sigil can be removed");
        }
862

863 864
        _ => ()
    }
865 866
}

867
struct MissingDocLintVisitor(ty::ctxt);
868 869

impl MissingDocLintVisitor {
870 871 872 873 874
    fn check_attrs(&self, attrs: &[ast::Attribute], id: ast::NodeId,
                   sp: Span, msg: ~str) {
        if !attrs.iter().any(|a| a.node.is_sugared_doc) {
            self.sess.add_lint(missing_doc, id, sp, msg);
        }
875
    }
S
Steven Fackler 已提交
876

877 878 879 880 881 882
    fn check_struct(&self, sdef: &ast::struct_def) {
        for field in sdef.fields.iter() {
            match field.node.kind {
                ast::named_field(_, vis) if vis != ast::private => {
                    self.check_attrs(field.node.attrs, field.node.id, field.span,
                                     ~"missing documentation for a field");
S
Steven Fackler 已提交
883 884 885 886 887
                }
                ast::unnamed_field | ast::named_field(*) => {}
            }
        }
    }
888

889 890 891 892 893 894 895 896
    fn doc_hidden(&self, attrs: &[ast::Attribute]) -> bool {
        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(...)]
                }
        }
897
    }
898
}
899

900 901 902
impl Visitor<()> for MissingDocLintVisitor {
    fn visit_ty_method(&mut self, m:&ast::TypeMethod, _: ()) {
        if self.doc_hidden(m.attrs) { return }
903

904 905 906 907 908
        // All ty_method objects are linted about because they're part of a
        // trait (no visibility)
        self.check_attrs(m.attrs, m.id, m.span,
                         ~"missing documentation for a method");
        visit::walk_ty_method(self, m, ());
909 910
    }

911 912 913 914 915 916 917 918 919 920 921 922 923
    fn visit_fn(&mut self, fk: &visit::fn_kind, d: &ast::fn_decl,
                b: &ast::Block, sp: Span, id: ast::NodeId, _: ()) {
        // Only warn about explicitly public methods.
        match *fk {
            visit::fk_method(_, _, m) => {
                if self.doc_hidden(m.attrs) {
                    return;
                }
                // If we're in a trait implementation, no need to duplicate
                // documentation
                if m.vis == ast::public {
                    self.check_attrs(m.attrs, id, sp,
                                     ~"missing documentation for a method");
924
                }
925
            }
926 927 928
            _ => {}
        }
        visit::walk_fn(self, fk, d, b, sp, id, ());
929 930
    }

931 932 933 934 935 936 937 938 939 940 941
    fn visit_item(&mut self, it: @ast::item, _: ()) {
        // If we're building a test harness, then warning about documentation is
        // probably not really relevant right now
        if self.sess.opts.test { return }
        if self.doc_hidden(it.attrs) { return }

        match it.node {
            ast::item_struct(sdef, _) if it.vis == ast::public => {
                self.check_attrs(it.attrs, it.id, it.span,
                                 ~"missing documentation for a struct");
                self.check_struct(sdef);
S
Steven Fackler 已提交
942
            }
943

944 945 946
            // Skip implementations because they inherit documentation from the
            // trait (which was already linted)
            ast::item_impl(_, Some(*), _, _) => return,
947

948 949 950 951
            ast::item_trait(*) if it.vis == ast::public => {
                self.check_attrs(it.attrs, it.id, it.span,
                                 ~"missing documentation for a trait");
            }
952

953 954 955 956
            ast::item_fn(*) if it.vis == ast::public => {
                self.check_attrs(it.attrs, it.id, it.span,
                                 ~"missing documentation for a function");
            }
S
Steven Fackler 已提交
957

958 959 960 961 962 963 964 965 966 967 968 969
            ast::item_enum(ref edef, _) if it.vis == ast::public => {
                self.check_attrs(it.attrs, it.id, it.span,
                                 ~"missing documentation for an enum");
                for variant in edef.variants.iter() {
                    if variant.node.vis == ast::private { continue; }

                    self.check_attrs(variant.node.attrs, variant.node.id,
                                     variant.span,
                                     ~"missing documentation for a variant");
                    match variant.node.kind {
                        ast::struct_variant_kind(sdef) => {
                            self.check_struct(sdef);
S
Steven Fackler 已提交
970
                        }
971
                        _ => ()
S
Steven Fackler 已提交
972 973
                    }
                }
974 975
            }

976 977 978 979
            _ => {}
        }
        visit::walk_item(self, it, ());
    }
980 981
}

982 983
/// Checks for use of items with #[deprecated], #[experimental] and
/// #[unstable] (or none of them) attributes.
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
fn check_stability(cx: &Context, e: &ast::Expr) {
    let def = match e.node {
        ast::ExprMethodCall(*) |
        ast::ExprPath(*) |
        ast::ExprStruct(*) => {
            match cx.tcx.def_map.find(&e.id) {
                Some(&def) => def,
                None => return
            }
        }
        _ => return
    };

    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| {
1004
                    do attrs.map |a| {
1005
                        attr::find_stability(a.iter().map(|a| a.meta()))
1006
                    }
1007 1008 1009 1010 1011 1012 1013 1014
                };
                match s {
                    Some(s) => s,

                    // no possibility of having attributes
                    // (e.g. it's a local variable), so just
                    // ignore it.
                    None => return
1015 1016
                }
            }
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
            _ => cx.tcx.sess.bug(format!("handle_def: {:?} not found", id))
        }
    } 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())
1028
            }
1029 1030 1031
        }
        s
    };
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
    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
    };
1044

1045 1046 1047 1048 1049 1050
    let msg = match stability {
        Some(attr::Stability { text: Some(ref s), _ }) => {
            format!("use of {} item: {}", label, *s)
        }
        _ => format!("use of {} item", label)
    };
1051

1052
    cx.span_lint(lint, e.span, msg);
1053 1054
}

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
impl Visitor<()> for Context {
    fn visit_item(&mut self, it: @ast::item, _: ()) {
        do self.with_lint_attrs(it.attrs) |cx| {
            check_item_ctypes(cx, it);
            check_item_non_camel_case_types(cx, it);
            check_item_non_uppercase_statics(cx, it);
            check_heap_item(cx, it);

            do cx.visit_ids |v| {
                v.visit_item(it, ());
            }
1066

1067 1068
            visit::walk_item(cx, it, ());
        }
1069 1070
    }

1071 1072 1073
    fn visit_pat(&mut self, p: @ast::Pat, _: ()) {
        check_pat_non_uppercase_statics(self, p);
        visit::walk_pat(self, p, ());
1074 1075
    }

1076 1077 1078 1079 1080 1081 1082
    fn visit_expr(&mut self, e: @ast::Expr, _: ()) {
        check_while_true_expr(self, e);
        check_stability(self, e);
        check_unused_unsafe(self, e);
        check_unnecessary_allocation(self, e);
        check_heap_expr(self, e);
        check_type_limits(self, e);
1083

1084
        visit::walk_expr(self, e, ());
1085 1086
    }

1087 1088
    fn visit_stmt(&mut self, s: @ast::Stmt, _: ()) {
        check_path_statement(self, s);
1089

1090 1091
        visit::walk_stmt(self, s, ());
    }
1092

1093 1094 1095 1096
    fn visit_ty_method(&mut self, tm: &ast::TypeMethod, _: ()) {
        check_unused_mut_fn_decl(self, &tm.decl);
        visit::walk_ty_method(self, tm, ());
    }
1097

1098 1099 1100 1101 1102 1103 1104
    fn visit_trait_method(&mut self, tm: &ast::trait_method, _: ()) {
        match *tm {
            ast::required(ref m) => check_unused_mut_fn_decl(self, &m.decl),
            ast::provided(ref m) => check_unused_mut_fn_decl(self, &m.decl)
        }
        visit::walk_trait_method(self, tm, ());
    }
1105

1106 1107 1108 1109 1110
    fn visit_local(&mut self, l: @ast::Local, _: ()) {
        if l.is_mutbl {
            check_unused_mut_pat(self, l.pat);
        }
        visit::walk_local(self, l, ());
1111 1112
    }

1113 1114 1115 1116 1117 1118
    fn visit_fn(&mut self, fk: &visit::fn_kind, decl: &ast::fn_decl,
                body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
        let recurse = |this: &mut Context| {
            check_unused_mut_fn_decl(this, decl);
            visit::walk_fn(this, fk, decl, body, span, id, ());
        };
1119

1120 1121 1122 1123 1124
        match *fk {
            visit::fk_method(_, _, m) => {
                do self.with_lint_attrs(m.attrs) |cx| {
                    do cx.visit_ids |v| {
                        v.visit_fn(fk, decl, body, span, id, ());
1125
                    }
1126
                    recurse(cx);
1127
                }
1128 1129 1130
            }
            _ => recurse(self),
        }
1131
    }
1132
}
1133

1134 1135 1136 1137 1138 1139 1140
impl ast_util::IdVisitingOperation for Context {
    fn visit_id(&self, id: ast::NodeId) {
        match self.tcx.sess.lints.pop(&id) {
            None => {}
            Some(l) => {
                for (lint, span, msg) in l.move_iter() {
                    self.span_lint(lint, span, msg)
1141
                }
1142 1143
            }
        }
1144
    }
1145 1146
}

A
Alex Crichton 已提交
1147
pub fn check_crate(tcx: ty::ctxt, crate: &ast::Crate) {
1148 1149 1150 1151 1152 1153 1154
    // This visitor contains more state than is currently maintained in Context,
    // and there's no reason for the Context to keep track of this information
    // really
    let mut dox = MissingDocLintVisitor(tcx);
    visit::walk_crate(&mut dox, crate, ());

    let mut cx = Context {
1155
        dict: @get_lint_dict(),
1156
        cur: SmallIntMap::new(),
1157 1158 1159 1160
        tcx: tcx,
        lint_stack: ~[],
    };

1161 1162
    // Install default lint levels, followed by the command line levels, and
    // then actually visit the whole crate.
D
Daniel Micay 已提交
1163
    for (_, spec) in cx.dict.iter() {
1164
        cx.set_level(spec.lint, spec.default, Default);
1165
    }
D
Daniel Micay 已提交
1166
    for &(lint, level) in tcx.sess.opts.lint_opts.iter() {
1167
        cx.set_level(lint, level, CommandLine);
1168
    }
1169 1170 1171 1172 1173 1174
    do cx.with_lint_attrs(crate.attrs) |cx| {
        do cx.visit_ids |v| {
            v.visited_outermost = true;
            visit::walk_crate(v, crate, ());
        }
        visit::walk_crate(cx, crate, ());
1175 1176
    }

1177 1178
    // If we missed any lints added to the session, then there's a bug somewhere
    // in the iteration code.
D
Daniel Micay 已提交
1179
    for (id, v) in tcx.sess.lints.iter() {
1180 1181 1182 1183 1184 1185 1186
        for &(lint, span, ref msg) in v.iter() {
            tcx.sess.span_bug(span, format!("unprocessed lint {:?} at {}: {}",
                                            lint,
                                            ast_map::node_id_to_str(tcx.items,
                                                *id,
                                                token::get_ident_interner()),
                                            *msg))
1187 1188
        }
    }
1189

1190
    tcx.sess.abort_if_errors();
1191
}