lint.rs 50.0 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;
37
use middle::privacy;
J
Jed Davis 已提交
38
use middle::trans::adt; // for `adt::is_ffi_safe`
P
Patrick Walton 已提交
39
use middle::ty;
40
use middle::typeck;
41
use middle::pat_util;
42
use metadata::csearch;
P
Patrick Walton 已提交
43
use util::ppaux::{ty_to_str};
F
Florian Hahn 已提交
44 45 46 47
use std::to_str::ToStr;

use middle::typeck::infer;
use middle::typeck::astconv::{ast_ty_to_ty, AstConv};
48

49 50 51 52 53 54 55 56 57 58
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;
59
use extra::smallintmap::SmallIntMap;
60
use syntax::ast_map;
61
use syntax::attr;
62
use syntax::attr::{AttrMetaMethods, AttributeMethods};
63
use syntax::codemap::Span;
J
John Clements 已提交
64
use syntax::codemap;
65
use syntax::parse::token;
66
use syntax::{ast, ast_util, visit};
67
use syntax::ast_util::IdVisitingOperation;
68
use syntax::visit::Visitor;
69

70
#[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
B
Brian Anderson 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
pub enum Lint {
    CTypes,
    UnusedImports,
    UnnecessaryQualification,
    WhileTrue,
    PathStatement,
    UnrecognizedLint,
    NonCamelCaseTypes,
    NonUppercaseStatics,
    NonUppercasePatternStatics,
    TypeLimits,
    TypeOverflow,
    UnusedUnsafe,
    UnsafeBlock,
    AttributeUsage,
    UnknownFeatures,
    UnknownCrateType,

    ManagedHeapMemory,
    OwnedHeapMemory,
    HeapMemory,

    UnusedVariable,
    DeadAssignment,
    UnusedMut,
    UnnecessaryAllocation,
    DeadCode,
    UnnecessaryTypecast,

    MissingDoc,
    UnreachableCode,

    Deprecated,
    Experimental,
    Unstable,

    Warnings,
108 109
}

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

119
#[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
120
pub enum level {
121
    allow, warn, deny, forbid
122 123
}

124
#[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
125
pub struct LintSpec {
126
    default: level,
B
Brian Anderson 已提交
127
    lint: Lint,
128
    desc: &'static str,
129 130
}

131
pub type LintDict = HashMap<&'static str, LintSpec>;
132

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

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

    ("unused_imports",
     LintSpec {
B
Brian Anderson 已提交
150
        lint: UnusedImports,
S
Sangeun Kim 已提交
151 152 153 154
        desc: "imports that are never used",
        default: warn
     }),

155 156
    ("unnecessary_qualification",
     LintSpec {
B
Brian Anderson 已提交
157
        lint: UnnecessaryQualification,
158 159 160 161
        desc: "detects unnecessarily qualified names",
        default: allow
     }),

S
Sangeun Kim 已提交
162 163
    ("while_true",
     LintSpec {
B
Brian Anderson 已提交
164
        lint: WhileTrue,
S
Sangeun Kim 已提交
165 166 167 168 169 170
        desc: "suggest using loop { } instead of while(true) { }",
        default: warn
     }),

    ("path_statement",
     LintSpec {
B
Brian Anderson 已提交
171
        lint: PathStatement,
S
Sangeun Kim 已提交
172 173 174 175 176 177
        desc: "path statements with no effect",
        default: warn
     }),

    ("unrecognized_lint",
     LintSpec {
B
Brian Anderson 已提交
178
        lint: UnrecognizedLint,
S
Sangeun Kim 已提交
179 180 181 182 183 184
        desc: "unrecognized lint attribute",
        default: warn
     }),

    ("non_camel_case_types",
     LintSpec {
B
Brian Anderson 已提交
185
        lint: NonCamelCaseTypes,
S
Sangeun Kim 已提交
186 187 188 189
        desc: "types, variants and traits should have camel case names",
        default: allow
     }),

190 191
    ("non_uppercase_statics",
     LintSpec {
B
Brian Anderson 已提交
192
         lint: NonUppercaseStatics,
193
         desc: "static constants should have uppercase identifiers",
194
         default: allow
195 196
     }),

197 198
    ("non_uppercase_pattern_statics",
     LintSpec {
B
Brian Anderson 已提交
199
         lint: NonUppercasePatternStatics,
200
         desc: "static constants in match patterns should be all caps",
201 202 203
         default: warn
     }),

S
Sangeun Kim 已提交
204 205
    ("managed_heap_memory",
     LintSpec {
B
Brian Anderson 已提交
206
        lint: ManagedHeapMemory,
S
Sangeun Kim 已提交
207 208 209 210 211 212
        desc: "use of managed (@ type) heap memory",
        default: allow
     }),

    ("owned_heap_memory",
     LintSpec {
B
Brian Anderson 已提交
213
        lint: OwnedHeapMemory,
S
Sangeun Kim 已提交
214 215 216 217 218 219
        desc: "use of owned (~ type) heap memory",
        default: allow
     }),

    ("heap_memory",
     LintSpec {
B
Brian Anderson 已提交
220
        lint: HeapMemory,
S
Sangeun Kim 已提交
221 222 223 224 225 226
        desc: "use of any (~ type or @ type) heap memory",
        default: allow
     }),

    ("type_limits",
     LintSpec {
B
Brian Anderson 已提交
227
        lint: TypeLimits,
S
Sangeun Kim 已提交
228 229 230 231
        desc: "comparisons made useless by limits of the types involved",
        default: warn
     }),

232 233
    ("type_overflow",
     LintSpec {
B
Brian Anderson 已提交
234
        lint: TypeOverflow,
235 236 237 238 239
        desc: "literal out of range for its type",
        default: warn
     }),


S
Sangeun Kim 已提交
240 241
    ("unused_unsafe",
     LintSpec {
B
Brian Anderson 已提交
242
        lint: UnusedUnsafe,
S
Sangeun Kim 已提交
243 244 245 246
        desc: "unnecessary use of an `unsafe` block",
        default: warn
    }),

D
Daniel Micay 已提交
247 248
    ("unsafe_block",
     LintSpec {
B
Brian Anderson 已提交
249
        lint: UnsafeBlock,
D
Daniel Micay 已提交
250 251 252 253
        desc: "usage of an `unsafe` block",
        default: allow
    }),

254 255
    ("attribute_usage",
     LintSpec {
B
Brian Anderson 已提交
256
        lint: AttributeUsage,
257 258 259 260
        desc: "detects bad use of attributes",
        default: warn
    }),

S
Sangeun Kim 已提交
261 262
    ("unused_variable",
     LintSpec {
B
Brian Anderson 已提交
263
        lint: UnusedVariable,
S
Sangeun Kim 已提交
264 265 266 267 268 269
        desc: "detect variables which are not used in any way",
        default: warn
    }),

    ("dead_assignment",
     LintSpec {
B
Brian Anderson 已提交
270
        lint: DeadAssignment,
S
Sangeun Kim 已提交
271 272 273 274
        desc: "detect assignments that will never be read",
        default: warn
    }),

F
Florian Hahn 已提交
275 276
    ("unnecessary_typecast",
     LintSpec {
B
Brian Anderson 已提交
277
        lint: UnnecessaryTypecast,
F
Florian Hahn 已提交
278 279 280 281
        desc: "detects unnecessary type casts, that can be removed",
        default: allow,
    }),

S
Sangeun Kim 已提交
282 283
    ("unused_mut",
     LintSpec {
B
Brian Anderson 已提交
284
        lint: UnusedMut,
S
Sangeun Kim 已提交
285 286 287
        desc: "detect mut variables which don't need to be mutable",
        default: warn
    }),
288 289 290

    ("unnecessary_allocation",
     LintSpec {
B
Brian Anderson 已提交
291
        lint: UnnecessaryAllocation,
292 293 294
        desc: "detects unnecessary allocations that can be eliminated",
        default: warn
    }),
295

K
Kiet Tran 已提交
296 297
    ("dead_code",
     LintSpec {
B
Brian Anderson 已提交
298
        lint: DeadCode,
K
Kiet Tran 已提交
299 300 301 302
        desc: "detect piece of code that will never be used",
        default: warn
    }),

303
    ("missing_doc",
304
     LintSpec {
B
Brian Anderson 已提交
305
        lint: MissingDoc,
306
        desc: "detects missing documentation for public members",
307 308
        default: allow
    }),
309 310 311

    ("unreachable_code",
     LintSpec {
B
Brian Anderson 已提交
312
        lint: UnreachableCode,
313 314 315
        desc: "detects unreachable code",
        default: warn
    }),
316

317 318
    ("deprecated",
     LintSpec {
B
Brian Anderson 已提交
319
        lint: Deprecated,
320 321 322 323 324 325
        desc: "detects use of #[deprecated] items",
        default: warn
    }),

    ("experimental",
     LintSpec {
B
Brian Anderson 已提交
326
        lint: Experimental,
327 328 329 330 331 332
        desc: "detects use of #[experimental] items",
        default: warn
    }),

    ("unstable",
     LintSpec {
B
Brian Anderson 已提交
333
        lint: Unstable,
334 335 336 337
        desc: "detects use of #[unstable] items (incl. items with no stability attribute)",
        default: allow
    }),

338 339
    ("warnings",
     LintSpec {
B
Brian Anderson 已提交
340
        lint: Warnings,
341 342 343
        desc: "mass-change the level for lints which produce warnings",
        default: warn
    }),
344 345 346

    ("unknown_features",
     LintSpec {
B
Brian Anderson 已提交
347
        lint: UnknownFeatures,
A
a_m0d 已提交
348
        desc: "unknown features found in crate-level #[feature] directives",
349 350
        default: deny,
    }),
351 352
     ("unknown_crate_type",
     LintSpec {
B
Brian Anderson 已提交
353
         lint: UnknownCrateType,
354 355 356
         desc: "unknown crate type found in #[crate_type] directive",
         default: deny,
     }),
S
Sangeun Kim 已提交
357 358
];

359 360 361 362
/*
  Pass names should not contain a '-', as the compiler normalizes
  '-' to '_' in command-line flags
 */
363
pub fn get_lint_dict() -> LintDict {
364
    let mut map = HashMap::new();
D
Daniel Micay 已提交
365
    for &(k, v) in lint_table.iter() {
366
        map.insert(k, v);
367
    }
368
    return map;
369 370
}

E
Erik Price 已提交
371
struct Context<'a> {
372 373 374
    // All known lint modes (string versions)
    dict: @LintDict,
    // Current levels of each lint warning
375
    cur: SmallIntMap<(level, LintSource)>,
376 377
    // context we're checking in (used to access fields like sess)
    tcx: ty::ctxt,
378 379 380
    // maps from an expression id that corresponds to a method call to the
    // details of the method to be invoked
    method_map: typeck::method_map,
381
    // Items exported by the crate; used by the missing_doc lint.
E
Erik Price 已提交
382
    exported_items: &'a privacy::ExportedItems,
383
    // The id of the current `ast::StructDef` being walked.
384 385 386 387
    cur_struct_def_id: ast::NodeId,
    // Whether some ancestor of the current node was marked
    // #[doc(hidden)].
    is_doc_hidden: bool,
388

389 390 391
    // 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.
B
Brian Anderson 已提交
392
    lint_stack: ~[(Lint, level, LintSource)],
393 394 395

    // id of the last visited negated expression
    negated_expr_id: ast::NodeId
396
}
397

E
Erik Price 已提交
398
impl<'a> Context<'a> {
B
Brian Anderson 已提交
399
    fn get_level(&self, lint: Lint) -> level {
400
        match self.cur.find(&(lint as uint)) {
401
          Some(&(lvl, _)) => lvl,
402 403
          None => allow
        }
404 405
    }

B
Brian Anderson 已提交
406
    fn get_source(&self, lint: Lint) -> LintSource {
407
        match self.cur.find(&(lint as uint)) {
408 409 410 411 412
          Some(&(_, src)) => src,
          None => Default
        }
    }

B
Brian Anderson 已提交
413
    fn set_level(&mut self, lint: Lint, level: level, src: LintSource) {
414
        if level == allow {
415
            self.cur.remove(&(lint as uint));
416
        } else {
417
            self.cur.insert(lint as uint, (level, src));
418 419 420
        }
    }

B
Brian Anderson 已提交
421
    fn lint_to_str(&self, lint: Lint) -> &'static str {
D
Daniel Micay 已提交
422
        for (k, v) in self.dict.iter() {
423
            if v.lint == lint {
424
                return *k;
425
            }
426
        }
427
        fail!("unregistered lint {:?}", lint);
428 429
    }

B
Brian Anderson 已提交
430
    fn span_lint(&self, lint: Lint, span: Span, msg: &str) {
431
        let (level, src) = match self.cur.find(&(lint as uint)) {
432
            None => { return }
B
Brian Anderson 已提交
433
            Some(&(warn, src)) => (self.get_level(Warnings), src),
434 435
            Some(&pair) => pair,
        };
436
        if level == allow { return }
437 438 439

        let mut note = None;
        let msg = match src {
G
Geoff Hill 已提交
440 441 442 443 444 445 446
            Default => {
                format!("{}, \\#[{}({})] on by default", msg,
                    level_to_str(level), self.lint_to_str(lint))
            },
            CommandLine => {
                format!("{} [-{} {}]", msg,
                    match level {
447
                        warn => 'W', deny => 'D', forbid => 'F',
448
                        allow => fail!()
G
Geoff Hill 已提交
449
                    }, self.lint_to_str(lint).replace("_", "-"))
450 451 452 453 454 455 456 457 458
            },
            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);  }
459
            allow => fail!(),
460 461
        }

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

467
    /**
468
     * Merge the lints specified by any lint attributes into the
469
     * current lint context, call the provided function, then reset the
470
     * lints in effect to their previous state.
471
     */
472 473 474
    fn with_lint_attrs(&mut self,
                       attrs: &[ast::Attribute],
                       f: |&mut Context|) {
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
        each_lint(self.tcx.sess, attrs, |meta, level, lintname| {
481 482 483
            match self.dict.find_equiv(&lintname) {
                None => {
                    self.span_lint(
B
Brian Anderson 已提交
484
                        UnrecognizedLint,
485
                        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
            true
506
        });
507

508 509 510 511 512 513
        let old_is_doc_hidden = self.is_doc_hidden;
        self.is_doc_hidden = self.is_doc_hidden ||
            attrs.iter().any(|attr| ("doc" == attr.name() && match attr.meta_item_list()
                                     { None => false,
                                       Some(l) => attr::contains_name(l, "hidden") }));

514
        f(self);
515

516
        // rollback
517
        self.is_doc_hidden = old_is_doc_hidden;
518
        pushed.times(|| {
519 520
            let (lint, lvl, src) = self.lint_stack.pop();
            self.set_level(lint, lvl, src);
521
        })
522 523
    }

524
    fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
525 526 527 528 529 530
        let mut v = ast_util::IdVisitor {
            operation: self,
            pass_through_items: false,
            visited_outermost: false,
        };
        f(&mut v);
531 532 533
    }
}

534
pub fn each_lint(sess: session::Session,
535
                 attrs: &[ast::Attribute],
536 537
                 f: |@ast::MetaItem, level, @str| -> bool)
                 -> bool {
538
    let xs = [allow, warn, deny, forbid];
D
Daniel Micay 已提交
539
    for &level in xs.iter() {
540
        let level_name = level_to_str(level);
D
Daniel Micay 已提交
541
        for attr in attrs.iter().filter(|m| level_name == m.name()) {
542 543
            let meta = attr.node.value;
            let metas = match meta.node {
544
                ast::MetaList(_, ref metas) => metas,
545
                _ => {
546
                    sess.span_err(meta.span, "malformed lint attribute");
547
                    continue;
548 549
                }
            };
D
Daniel Micay 已提交
550
            for meta in metas.iter() {
551
                match meta.node {
552
                    ast::MetaWord(lintname) => {
553 554 555 556 557
                        if !f(*meta, level, lintname) {
                            return false;
                        }
                    }
                    _ => {
558
                        sess.span_err(meta.span, "malformed lint attribute");
559 560 561 562 563
                    }
                }
            }
        }
    }
564
    true
565 566
}

567 568 569 570 571
fn check_while_true_expr(cx: &Context, e: &ast::Expr) {
    match e.node {
        ast::ExprWhile(cond, _) => {
            match cond.node {
                ast::ExprLit(@codemap::Spanned {
572
                    node: ast::LitBool(true), ..}) =>
573
                {
B
Brian Anderson 已提交
574
                    cx.span_lint(WhileTrue, e.span,
575
                                 "denote infinite loops with loop { ... }");
576
                }
577 578
                _ => ()
            }
579 580
        }
        _ => ()
581 582
    }
}
F
Florian Hahn 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
impl<'a> AstConv for Context<'a>{
    fn tcx(&self) -> ty::ctxt { self.tcx }

    fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
        ty::lookup_item_type(self.tcx, id)
    }

    fn get_trait_def(&self, id: ast::DefId) -> @ty::TraitDef {
        ty::lookup_trait_def(self.tcx, id)
    }

    fn ty_infer(&self, _span: Span) -> ty::t {
        let infcx: @infer::InferCtxt = infer::new_infer_ctxt(self.tcx);
        infcx.next_ty_var()
    }
}


fn check_unused_casts(cx: &Context, e: &ast::Expr) {
    return match e.node {
        ast::ExprCast(expr, ty) => {
            let infcx: @infer::InferCtxt = infer::new_infer_ctxt(cx.tcx);
            let t_t = ast_ty_to_ty(cx, &infcx, ty);
            if  ty::get(ty::expr_ty(cx.tcx, expr)).sty == ty::get(t_t).sty {
B
Brian Anderson 已提交
607
                cx.span_lint(UnnecessaryTypecast, ty.span,
F
Florian Hahn 已提交
608 609 610 611 612 613
                             "unnecessary type cast");
            }
        }
        _ => ()
    };
}
614

615 616 617 618
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) {
B
Brian Anderson 已提交
619
                cx.span_lint(TypeLimits, e.span,
620
                             "comparison is useless due to type limits");
621
            }
622 623 624 625
        },
        ast::ExprLit(lit) => {
            match ty::get(ty::expr_ty(cx.tcx, e)).sty {
                ty::ty_int(t) => {
626
                    let int_type = if t == ast::TyI {
627 628 629 630
                        cx.tcx.sess.targ_cfg.int_type
                    } else { t };
                    let (min, max) = int_ty_range(int_type);
                    let mut lit_val: i64 = match lit.node {
631 632 633
                        ast::LitInt(v, _) => v,
                        ast::LitUint(v, _) => v as i64,
                        ast::LitIntUnsuffixed(v) => v,
634 635 636 637 638 639
                        _ => fail!()
                    };
                    if cx.negated_expr_id == e.id {
                        lit_val *= -1;
                    }
                    if  lit_val < min || lit_val > max {
B
Brian Anderson 已提交
640
                        cx.span_lint(TypeOverflow, e.span,
641 642 643 644
                                     "literal out of range for its type");
                    }
                },
                ty::ty_uint(t) => {
645
                    let uint_type = if t == ast::TyU {
646 647 648 649
                        cx.tcx.sess.targ_cfg.uint_type
                    } else { t };
                    let (min, max) = uint_ty_range(uint_type);
                    let lit_val: u64 = match lit.node {
650 651 652
                        ast::LitInt(v, _) => v as u64,
                        ast::LitUint(v, _) => v,
                        ast::LitIntUnsuffixed(v) => v as u64,
653 654 655
                        _ => fail!()
                    };
                    if  lit_val < min || lit_val > max {
B
Brian Anderson 已提交
656
                        cx.span_lint(TypeOverflow, e.span,
657 658 659 660 661 662 663
                                     "literal out of range for its type");
                    }
                },

                _ => ()
            };
        },
664 665
        _ => ()
    };
666

667 668
    fn is_valid<T:cmp::Ord>(binop: ast::BinOp, v: T,
                            min: T, max: T) -> bool {
669
        match binop {
670 671 672 673 674
            ast::BiLt => v <= max,
            ast::BiLe => v < max,
            ast::BiGt => v >= min,
            ast::BiGe => v > min,
            ast::BiEq | ast::BiNe => v >= min && v <= max,
675
            _ => fail!()
676 677 678
        }
    }

679
    fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
680
        match binop {
681 682 683 684
            ast::BiLt => ast::BiGt,
            ast::BiLe => ast::BiGe,
            ast::BiGt => ast::BiLt,
            ast::BiGe => ast::BiLe,
685 686 687 688
            _ => binop
        }
    }

689 690
    // for int & uint, be conservative with the warnings, so that the
    // warnings are consistent between 32- and 64-bit platforms
691
    fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
692
        match int_ty {
693 694 695 696 697
            ast::TyI =>    (i64::min_value,        i64::max_value),
            ast::TyI8 =>   (i8::min_value  as i64, i8::max_value  as i64),
            ast::TyI16 =>  (i16::min_value as i64, i16::max_value as i64),
            ast::TyI32 =>  (i32::min_value as i64, i32::max_value as i64),
            ast::TyI64 =>  (i64::min_value,        i64::max_value)
698 699 700
        }
    }

701
    fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
702
        match uint_ty {
703 704 705 706 707
            ast::TyU =>   (u64::min_value,         u64::max_value),
            ast::TyU8 =>  (u8::min_value   as u64, u8::max_value   as u64),
            ast::TyU16 => (u16::min_value  as u64, u16::max_value  as u64),
            ast::TyU32 => (u32::min_value  as u64, u32::max_value  as u64),
            ast::TyU64 => (u64::min_value,         u64::max_value)
708 709 710
        }
    }

711 712
    fn check_limits(tcx: ty::ctxt, binop: ast::BinOp,
                    l: &ast::Expr, r: &ast::Expr) -> bool {
713
        let (lit, expr, swap) = match (&l.node, &r.node) {
714 715
            (&ast::ExprLit(_), _) => (l, r, true),
            (_, &ast::ExprLit(_)) => (r, l, false),
716 717 718 719
            _ => return true
        };
        // Normalize the binop so that the literal is always on the RHS in
        // the comparison
720 721
        let norm_binop = if swap { rev_binop(binop) } else { binop };
        match ty::get(ty::expr_ty(tcx, expr)).sty {
722
            ty::ty_int(int_ty) => {
723
                let (min, max) = int_ty_range(int_ty);
724
                let lit_val: i64 = match lit.node {
725
                    ast::ExprLit(li) => match li.node {
726 727 728
                        ast::LitInt(v, _) => v,
                        ast::LitUint(v, _) => v as i64,
                        ast::LitIntUnsuffixed(v) => v,
729 730
                        _ => return true
                    },
731
                    _ => fail!()
732
                };
733
                is_valid(norm_binop, lit_val, min, max)
734 735
            }
            ty::ty_uint(uint_ty) => {
736
                let (min, max): (u64, u64) = uint_ty_range(uint_ty);
737
                let lit_val: u64 = match lit.node {
738
                    ast::ExprLit(li) => match li.node {
739 740 741
                        ast::LitInt(v, _) => v as u64,
                        ast::LitUint(v, _) => v,
                        ast::LitIntUnsuffixed(v) => v as u64,
742 743
                        _ => return true
                    },
744
                    _ => fail!()
745
                };
746
                is_valid(norm_binop, lit_val, min, max)
747 748 749 750 751
            }
            _ => true
        }
    }

752
    fn is_comparison(binop: ast::BinOp) -> bool {
753
        match binop {
754 755
            ast::BiEq | ast::BiLt | ast::BiLe |
            ast::BiNe | ast::BiGe | ast::BiGt => true,
756 757 758
            _ => false
        }
    }
759 760
}

761
fn check_item_ctypes(cx: &Context, it: &ast::Item) {
762
    fn check_ty(cx: &Context, ty: &ast::Ty) {
763
        match ty.node {
764
            ast::TyPath(_, _, id) => {
P
Patrick Walton 已提交
765 766
                let def_map = cx.tcx.def_map.borrow();
                match def_map.get().get_copy(&id) {
767
                    ast::DefPrimTy(ast::TyInt(ast::TyI)) => {
B
Brian Anderson 已提交
768
                        cx.span_lint(CTypes, ty.span,
769 770 771
                                "found rust type `int` in foreign module, while \
                                libc::c_int or libc::c_long should be used");
                    }
772
                    ast::DefPrimTy(ast::TyUint(ast::TyU)) => {
B
Brian Anderson 已提交
773
                        cx.span_lint(CTypes, ty.span,
774 775 776
                                "found rust type `uint` in foreign module, while \
                                libc::c_uint or libc::c_ulong should be used");
                    }
J
Jed Davis 已提交
777 778
                    ast::DefTy(def_id) => {
                        if !adt::is_ffi_safe(cx.tcx, def_id) {
B
Brian Anderson 已提交
779
                            cx.span_lint(CTypes, ty.span,
J
Jed Davis 已提交
780 781
                                         "found enum type without foreign-function-safe \
                                          representation annotation in foreign module");
A
Alex Crichton 已提交
782
                            // hmm... this message could be more helpful
J
Jed Davis 已提交
783 784
                        }
                    }
785 786 787
                    _ => ()
                }
            }
788 789
            ast::TyPtr(ref mt) => { check_ty(cx, mt.ty) }
            _ => {}
790 791
        }
    }
792

793
    fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
D
Daniel Micay 已提交
794
        for input in decl.inputs.iter() {
795
            check_ty(cx, input.ty);
796
        }
797
        check_ty(cx, decl.output)
798 799
    }

800
    match it.node {
801
      ast::ItemForeignMod(ref nmod) if !nmod.abis.is_intrinsic() => {
D
Daniel Micay 已提交
802
        for ni in nmod.items.iter() {
803
            match ni.node {
804 805
                ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, decl),
                ast::ForeignItemStatic(t, _) => check_ty(cx, t)
806 807
            }
        }
808
      }
B
Brian Anderson 已提交
809
      _ => {/* nothing to do */ }
810 811
    }
}
812

813
fn check_heap_type(cx: &Context, span: Span, ty: ty::t) {
B
Brian Anderson 已提交
814
    let xs = [ManagedHeapMemory, OwnedHeapMemory, HeapMemory];
815 816 817 818 819 820 821
    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 {
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
                ty::ty_box(_) | ty::ty_estr(ty::vstore_box) |
                ty::ty_evec(_, ty::vstore_box) |
                ty::ty_trait(_, _, ty::BoxTraitStore, _, _) => {
                    n_box += 1;
                }
                ty::ty_uniq(_) | ty::ty_estr(ty::vstore_uniq) |
                ty::ty_evec(_, ty::vstore_uniq) |
                ty::ty_trait(_, _, ty::UniqTraitStore, _, _) => {
                    n_uniq += 1;
                }
                ty::ty_closure(ref c) if c.sigil == ast::OwnedSigil => {
                    n_uniq += 1;
                }

                _ => ()
837 838 839
            };
            t
        });
840

B
Brian Anderson 已提交
841
        if n_uniq > 0 && lint != ManagedHeapMemory {
842 843 844 845
            let s = ty_to_str(cx.tcx, ty);
            let m = format!("type uses owned (~ type) pointers: {}", s);
            cx.span_lint(lint, span, m);
        }
846

B
Brian Anderson 已提交
847
        if n_box > 0 && lint != OwnedHeapMemory {
848 849 850 851
            let s = ty_to_str(cx.tcx, ty);
            let m = format!("type uses managed (@ type) pointers: {}", s);
            cx.span_lint(lint, span, m);
        }
852
    }
853
}
854

855
fn check_heap_item(cx: &Context, it: &ast::Item) {
856
    match it.node {
857 858 859 860
        ast::ItemFn(..) |
        ast::ItemTy(..) |
        ast::ItemEnum(..) |
        ast::ItemStruct(..) => check_heap_type(cx, it.span,
861 862 863
                                               ty::node_id_to_type(cx.tcx,
                                                                   it.id)),
        _ => ()
864
    }
865

866 867
    // If it's a struct, we also have to check the fields' types
    match it.node {
868
        ast::ItemStruct(struct_def, _) => {
D
Daniel Micay 已提交
869
            for struct_field in struct_def.fields.iter() {
870 871 872
                check_heap_type(cx, struct_field.span,
                                ty::node_id_to_type(cx.tcx,
                                                    struct_field.node.id));
873 874 875 876
            }
        }
        _ => ()
    }
877
}
878

K
klutzy 已提交
879
static crate_attrs: &'static [&'static str] = &[
A
Alex Crichton 已提交
880
    "crate_type", "feature", "no_uv", "no_main", "no_std", "crate_id",
K
klutzy 已提交
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
    "desc", "comment", "license", "copyright", // not used in rustc now
];


static obsolete_attrs: &'static [(&'static str, &'static str)] = &[
    ("abi", "Use `extern \"abi\" fn` instead"),
    ("auto_encode", "Use `#[deriving(Encodable)]` instead"),
    ("auto_decode", "Use `#[deriving(Decodable)]` instead"),
    ("fast_ffi", "Remove it"),
    ("fixed_stack_segment", "Remove it"),
    ("rust_stack", "Remove it"),
];

static other_attrs: &'static [&'static str] = &[
    // item-level
    "address_insignificant", // can be crate-level too
D
Daniel Micay 已提交
897
    "thread_local", // for statics
K
klutzy 已提交
898 899 900 901
    "allow", "deny", "forbid", "warn", // lint options
    "deprecated", "experimental", "unstable", "stable", "locked", "frozen", //item stability
    "crate_map", "cfg", "doc", "export_name", "link_section", "no_freeze",
    "no_mangle", "no_send", "static_assert", "unsafe_no_drop_flag",
A
Alex Crichton 已提交
902
    "packed", "simd", "repr", "deriving", "unsafe_destructor", "link",
K
klutzy 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920

    //mod-level
    "path", "link_name", "link_args", "nolink", "macro_escape", "no_implicit_prelude",

    // fn-level
    "test", "bench", "should_fail", "ignore", "inline", "lang", "main", "start",
    "no_split_stack", "cold",

    // internal attribute: bypass privacy inside items
    "!resolve_unexported",
];

fn check_crate_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {

    for attr in attrs.iter() {
        let name = attr.node.value.name();
        let mut iter = crate_attrs.iter().chain(other_attrs.iter());
        if !iter.any(|other_attr| { name.equiv(other_attr) }) {
B
Brian Anderson 已提交
921
            cx.span_lint(AttributeUsage, attr.span, "unknown crate attribute");
K
klutzy 已提交
922
        }
923 924 925 926 927 928
        if name.equiv(& &"link") {
            cx.tcx.sess.span_err(attr.span,
                                 "obsolete crate `link` attribute");
            cx.tcx.sess.note("the link attribute has been superceded by the crate_id \
                             attribute, which has the format `#[crate_id = \"name#version\"]`");
        }
K
klutzy 已提交
929 930 931
    }
}

K
klutzy 已提交
932 933 934 935
fn check_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
    // check if element has crate-level, obsolete, or any unknown attributes.

    for attr in attrs.iter() {
936 937 938 939
        let name = attr.node.value.name();
        for crate_attr in crate_attrs.iter() {
            if name.equiv(crate_attr) {
                let msg = match attr.node.style {
K
klutzy 已提交
940 941
                    ast::AttrOuter => "crate-level attribute should be an inner attribute: \
                                       add semicolon at end",
942 943
                    ast::AttrInner => "crate-level attribute should be in the root module",
                };
B
Brian Anderson 已提交
944
                cx.span_lint(AttributeUsage, attr.span, msg);
K
klutzy 已提交
945
                return;
946 947
            }
        }
K
klutzy 已提交
948 949 950

        for &(obs_attr, obs_alter) in obsolete_attrs.iter() {
            if name.equiv(&obs_attr) {
B
Brian Anderson 已提交
951
                cx.span_lint(AttributeUsage, attr.span,
K
klutzy 已提交
952
                             format!("obsolete attribute: {:s}", obs_alter));
K
klutzy 已提交
953
                return;
K
klutzy 已提交
954 955
            }
        }
K
klutzy 已提交
956 957

        if !other_attrs.iter().any(|other_attr| { name.equiv(other_attr) }) {
B
Brian Anderson 已提交
958
            cx.span_lint(AttributeUsage, attr.span, "unknown attribute");
K
klutzy 已提交
959
        }
960 961 962
    }
}

963 964 965
fn check_heap_expr(cx: &Context, e: &ast::Expr) {
    let ty = ty::expr_ty(cx.tcx, e);
    check_heap_type(cx, e.span, ty);
966 967
}

968 969
fn check_path_statement(cx: &Context, s: &ast::Stmt) {
    match s.node {
A
Alex Crichton 已提交
970
        ast::StmtSemi(@ast::Expr { node: ast::ExprPath(_), .. }, _) => {
B
Brian Anderson 已提交
971
            cx.span_lint(PathStatement, s.span,
972 973 974
                         "path statement with no effect");
        }
        _ => ()
975 976 977
    }
}

978
fn check_item_non_camel_case_types(cx: &Context, it: &ast::Item) {
979
    fn is_camel_case(cx: ty::ctxt, ident: ast::Ident) -> bool {
P
Paul Stansifer 已提交
980
        let ident = cx.sess.str_of(ident);
P
Patrick Walton 已提交
981
        assert!(!ident.is_empty());
982
        let ident = ident.trim_chars(&'_');
983 984 985 986

        // 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() &&
987 988 989
            !ident.contains_char('_')
    }

990
    fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
991
        if !is_camel_case(cx.tcx, ident) {
992
            cx.span_lint(
B
Brian Anderson 已提交
993
                NonCamelCaseTypes, span,
A
Alex Crichton 已提交
994
                format!("{} `{}` should have a camel case identifier",
995
                    sort, cx.tcx.sess.str_of(ident)));
996 997 998
        }
    }

999
    match it.node {
1000
        ast::ItemTy(..) | ast::ItemStruct(..) => {
1001 1002
            check_case(cx, "type", it.ident, it.span)
        }
1003
        ast::ItemTrait(..) => {
1004
            check_case(cx, "trait", it.ident, it.span)
1005
        }
1006
        ast::ItemEnum(ref enum_definition, _) => {
1007
            check_case(cx, "type", it.ident, it.span);
D
Daniel Micay 已提交
1008
            for variant in enum_definition.variants.iter() {
1009
                check_case(cx, "variant", variant.node.name, variant.span);
E
Erick Tryzelaar 已提交
1010 1011 1012
            }
        }
        _ => ()
1013 1014 1015
    }
}

1016
fn check_item_non_uppercase_statics(cx: &Context, it: &ast::Item) {
1017 1018
    match it.node {
        // only check static constants
1019
        ast::ItemStatic(_, ast::MutImmutable, _) => {
1020 1021 1022 1023
            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)
1024
            if s.chars().any(|c| c.is_lowercase()) {
B
Brian Anderson 已提交
1025
                cx.span_lint(NonUppercaseStatics, it.span,
1026 1027 1028 1029 1030 1031 1032
                             "static constant should have an uppercase identifier");
            }
        }
        _ => {}
    }
}

1033 1034
fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) {
    // Lint for constants that look like binding identifiers (#7526)
P
Patrick Walton 已提交
1035 1036
    let def_map = cx.tcx.def_map.borrow();
    match (&p.node, def_map.get().find(&p.id)) {
1037 1038 1039 1040
        (&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);
1041
            if s.chars().any(|c| c.is_lowercase()) {
B
Brian Anderson 已提交
1042
                cx.span_lint(NonUppercasePatternStatics, path.span,
1043 1044 1045 1046 1047 1048 1049
                             "static constant in pattern should be all caps");
            }
        }
        _ => {}
    }
}

1050 1051
fn check_unused_unsafe(cx: &Context, e: &ast::Expr) {
    match e.node {
D
Daniel Micay 已提交
1052
        // Don't warn about generated blocks, that'll just pollute the output.
1053
        ast::ExprBlock(ref blk) => {
1054
            let used_unsafe = cx.tcx.used_unsafe.borrow();
1055
            if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1056
                !used_unsafe.get().contains(&blk.id) {
B
Brian Anderson 已提交
1057
                cx.span_lint(UnusedUnsafe, blk.span,
1058
                             "unnecessary `unsafe` block");
1059 1060
            }
        }
1061
        _ => ()
1062
    }
1063 1064
}

D
Daniel Micay 已提交
1065 1066 1067 1068
fn check_unsafe_block(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) => {
B
Brian Anderson 已提交
1069
            cx.span_lint(UnsafeBlock, blk.span, "usage of an `unsafe` block");
D
Daniel Micay 已提交
1070 1071 1072 1073 1074
        }
        _ => ()
    }
}

S
Seo Sanghyeon 已提交
1075
fn check_unused_mut_pat(cx: &Context, p: &ast::Pat) {
1076
    match p.node {
1077 1078 1079 1080
        ast::PatIdent(ast::BindByValue(ast::MutMutable),
                      ref path, _) if pat_util::pat_is_binding(cx.tcx.def_map, p)=> {
            // `let mut _a = 1;` doesn't need a warning.
            let initial_underscore = match path.segments {
A
Alex Crichton 已提交
1081
                [ast::PathSegment { identifier: id, .. }] => {
1082 1083 1084 1085 1086 1087 1088 1089 1090
                    cx.tcx.sess.str_of(id).starts_with("_")
                }
                _ => {
                    cx.tcx.sess.span_bug(p.span,
                                         "mutable binding that doesn't \
                                         consist of exactly one segment");
                }
            };

1091 1092
            let used_mut_nodes = cx.tcx.used_mut_nodes.borrow();
            if !initial_underscore && !used_mut_nodes.get().contains(&p.id) {
B
Brian Anderson 已提交
1093
                cx.span_lint(UnusedMut, p.span,
1094
                             "variable does not need to be mutable");
1095 1096
            }
        }
1097 1098
        _ => ()
    }
1099 1100
}

1101 1102 1103 1104 1105
enum Allocation {
    VectorAllocation,
    BoxAllocation
}

1106
fn check_unnecessary_allocation(cx: &Context, e: &ast::Expr) {
1107 1108 1109
    // Warn if string and vector literals with sigils, or boxing expressions,
    // are immediately borrowed.
    let allocation = match e.node {
1110 1111 1112
        ast::ExprVstore(e2, ast::ExprVstoreUniq) |
        ast::ExprVstore(e2, ast::ExprVstoreBox) => {
            match e2.node {
1113
                ast::ExprLit(@codemap::Spanned{node: ast::LitStr(..), ..}) |
1114
                ast::ExprVec(..) => VectorAllocation,
1115
                _ => return
1116 1117
            }
        }
1118
        ast::ExprUnary(_, ast::UnUniq, _) |
1119
        ast::ExprUnary(_, ast::UnBox, _) => BoxAllocation,
1120

1121
        _ => return
1122 1123 1124
    };

    let report = |msg| {
B
Brian Anderson 已提交
1125
        cx.span_lint(UnnecessaryAllocation, e.span, msg);
1126
    };
1127

1128 1129 1130 1131 1132
    let adjustment = {
        let adjustments = cx.tcx.adjustments.borrow();
        adjustments.get().find_copy(&e.id)
    };
    match adjustment {
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
        Some(@ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. })) => {
            match (allocation, autoref) {
                (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
                    report("unnecessary allocation, the sigil can be removed");
                }
                (BoxAllocation, Some(ty::AutoPtr(_, ast::MutImmutable))) => {
                    report("unnecessary allocation, use & instead");
                }
                (BoxAllocation, Some(ty::AutoPtr(_, ast::MutMutable))) => {
                    report("unnecessary allocation, use &mut instead");
                }
                _ => ()
            }
1146
        }
1147

1148 1149
        _ => ()
    }
1150 1151
}

1152
fn check_missing_doc_attrs(cx: &Context,
1153
                           id: Option<ast::NodeId>,
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
                           attrs: &[ast::Attribute],
                           sp: Span,
                           desc: &'static str) {
    // 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 }

    // `#[doc(hidden)]` disables missing_doc check.
    if cx.is_doc_hidden { return }

1164 1165 1166 1167 1168 1169
    // Only check publicly-visible items, using the result from the privacy pass. It's an option so
    // the crate root can also use this function (it doesn't have a NodeId).
    match id {
        Some(ref id) if !cx.exported_items.contains(id) => return,
        _ => ()
    }
1170

1171 1172 1173 1174 1175 1176 1177
    let has_doc = attrs.iter().any(|a| {
        match a.node.value.node {
            ast::MetaNameValue(ref name, _) if "doc" == *name => true,
            _ => false
        }
    });
    if !has_doc {
B
Brian Anderson 已提交
1178
        cx.span_lint(MissingDoc, sp,
1179
                     format!("missing documentation for {}", desc));
1180
    }
1181
}
1182

1183
fn check_missing_doc_item(cx: &Context, it: &ast::Item) {
1184
    let desc = match it.node {
1185 1186 1187 1188 1189
        ast::ItemFn(..) => "a function",
        ast::ItemMod(..) => "a module",
        ast::ItemEnum(..) => "an enum",
        ast::ItemStruct(..) => "a struct",
        ast::ItemTrait(..) => "a trait",
1190 1191
        _ => return
    };
1192
    check_missing_doc_attrs(cx, Some(it.id), it.attrs, it.span, desc);
1193
}
1194

1195
fn check_missing_doc_method(cx: &Context, m: &ast::Method) {
1196 1197 1198 1199
    let did = ast::DefId {
        crate: ast::LOCAL_CRATE,
        node: m.id
    };
1200 1201 1202 1203 1204 1205 1206 1207

    let method_opt;
    {
        let methods = cx.tcx.methods.borrow();
        method_opt = methods.get().find(&did).map(|method| *method);
    }

    match method_opt {
1208 1209 1210 1211
        None => cx.tcx.sess.span_bug(m.span, "missing method descriptor?!"),
        Some(md) => {
            match md.container {
                // Always check default methods defined on traits.
A
Alex Crichton 已提交
1212
                ty::TraitContainer(..) => {}
1213 1214 1215 1216 1217
                // For methods defined on impls, it depends on whether
                // it is an implementation for a trait or is a plain
                // impl.
                ty::ImplContainer(cid) => {
                    match ty::impl_trait_ref(cx.tcx, cid) {
A
Alex Crichton 已提交
1218
                        Some(..) => return, // impl for trait: don't doc
1219 1220
                        None => {} // plain impl: doc according to privacy
                    }
1221
                }
1222
            }
1223
        }
1224
    }
1225
    check_missing_doc_attrs(cx, Some(m.id), m.attrs, m.span, "a method");
1226
}
1227

1228
fn check_missing_doc_ty_method(cx: &Context, tm: &ast::TypeMethod) {
1229
    check_missing_doc_attrs(cx, Some(tm.id), tm.attrs, tm.span, "a type method");
1230
}
1231

1232
fn check_missing_doc_struct_field(cx: &Context, sf: &ast::StructField) {
1233
    match sf.node.kind {
1234
        ast::NamedField(_, vis) if vis != ast::Private =>
1235
            check_missing_doc_attrs(cx, Some(cx.cur_struct_def_id), sf.node.attrs,
1236 1237
                                    sf.span, "a struct field"),
        _ => {}
1238
    }
1239 1240
}

1241
fn check_missing_doc_variant(cx: &Context, v: &ast::Variant) {
1242
    check_missing_doc_attrs(cx, Some(v.node.id), v.node.attrs, v.span, "a variant");
1243 1244
}

1245 1246
/// Checks for use of items with #[deprecated], #[experimental] and
/// #[unstable] (or none of them) attributes.
1247
fn check_stability(cx: &Context, e: &ast::Expr) {
1248 1249
    let id = match e.node {
        ast::ExprPath(..) | ast::ExprStruct(..) => {
P
Patrick Walton 已提交
1250 1251
            let def_map = cx.tcx.def_map.borrow();
            match def_map.get().find(&e.id) {
1252 1253 1254 1255 1256
                Some(&def) => ast_util::def_id_of_def(def),
                None => return
            }
        }
        ast::ExprMethodCall(..) => {
1257 1258
            let method_map = cx.method_map.borrow();
            match method_map.get().find(&e.id) {
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
                Some(&typeck::method_map_entry { origin, .. }) => {
                    match origin {
                        typeck::method_static(def_id) => {
                            // If this implements a trait method, get def_id
                            // of the method inside trait definition.
                            // Otherwise, use the current def_id (which refers
                            // to the method inside impl).
                            ty::trait_method_of_method(
                                cx.tcx, def_id).unwrap_or(def_id)
                        }
                        typeck::method_param(typeck::method_param {
                            trait_id: trait_id,
                            method_num: index,
                            ..
                        })
                        | typeck::method_object(typeck::method_object {
                            trait_id: trait_id,
                            method_num: index,
                            ..
                        }) => ty::trait_method(cx.tcx, trait_id, index).def_id
                    }
                }
1281 1282 1283 1284 1285 1286 1287 1288
                None => return
            }
        }
        _ => return
    };

    let stability = if ast_util::is_local(id) {
        // this crate
P
Patrick Walton 已提交
1289 1290
        let items = cx.tcx.items.borrow();
        match items.get().find(&id.node) {
1291
            Some(ast_node) => {
1292 1293
                let s = ast_node.with_attrs(|attrs| {
                    attrs.map(|a| {
1294
                        attr::find_stability(a.iter().map(|a| a.meta()))
1295 1296
                    })
                });
1297 1298 1299 1300 1301 1302 1303
                match s {
                    Some(s) => s,

                    // no possibility of having attributes
                    // (e.g. it's a local variable), so just
                    // ignore it.
                    None => return
1304 1305
                }
            }
1306 1307
            _ => cx.tcx.sess.span_bug(e.span,
                                      format!("handle_def: {:?} not found", id))
1308 1309 1310 1311 1312 1313 1314
        }
    } else {
        // cross-crate

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

1323 1324
    let (lint, label) = match stability {
        // no stability attributes == Unstable
B
Brian Anderson 已提交
1325
        None => (Unstable, "unmarked"),
A
Alex Crichton 已提交
1326
        Some(attr::Stability { level: attr::Unstable, .. }) =>
B
Brian Anderson 已提交
1327
                (Unstable, "unstable"),
A
Alex Crichton 已提交
1328
        Some(attr::Stability { level: attr::Experimental, .. }) =>
B
Brian Anderson 已提交
1329
                (Experimental, "experimental"),
A
Alex Crichton 已提交
1330
        Some(attr::Stability { level: attr::Deprecated, .. }) =>
B
Brian Anderson 已提交
1331
                (Deprecated, "deprecated"),
1332 1333
        _ => return
    };
1334

1335
    let msg = match stability {
A
Alex Crichton 已提交
1336
        Some(attr::Stability { text: Some(ref s), .. }) => {
1337 1338 1339 1340
            format!("use of {} item: {}", label, *s)
        }
        _ => format!("use of {} item", label)
    };
1341

1342
    cx.span_lint(lint, e.span, msg);
1343 1344
}

E
Erik Price 已提交
1345
impl<'a> Visitor<()> for Context<'a> {
1346
    fn visit_item(&mut self, it: &ast::Item, _: ()) {
1347
        self.with_lint_attrs(it.attrs, |cx| {
1348 1349 1350 1351
            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);
1352
            check_missing_doc_item(cx, it);
K
klutzy 已提交
1353
            check_attrs_usage(cx, it.attrs);
1354

1355
            cx.visit_ids(|v| v.visit_item(it, ()));
1356

1357
            visit::walk_item(cx, it, ());
1358
        })
1359 1360
    }

1361
    fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
P
Patrick Walton 已提交
1362
        self.with_lint_attrs(it.attrs, |cx| {
K
klutzy 已提交
1363 1364
            check_attrs_usage(cx, it.attrs);
            visit::walk_foreign_item(cx, it, ());
P
Patrick Walton 已提交
1365
        })
K
klutzy 已提交
1366 1367
    }

1368
    fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
P
Patrick Walton 已提交
1369
        self.with_lint_attrs(i.attrs, |cx| {
K
klutzy 已提交
1370 1371
            check_attrs_usage(cx, i.attrs);
            visit::walk_view_item(cx, i, ());
P
Patrick Walton 已提交
1372
        })
K
klutzy 已提交
1373 1374
    }

S
Seo Sanghyeon 已提交
1375
    fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
1376
        check_pat_non_uppercase_statics(self, p);
1377 1378
        check_unused_mut_pat(self, p);

1379
        visit::walk_pat(self, p, ());
1380 1381
    }

E
Eduard Burtescu 已提交
1382
    fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
        match e.node {
            ast::ExprUnary(_, ast::UnNeg, expr) => {
                // propagate negation, if the negation itself isn't negated
                if self.negated_expr_id != e.id {
                    self.negated_expr_id = expr.id;
                }
            },
            ast::ExprParen(expr) => if self.negated_expr_id == e.id {
                self.negated_expr_id = expr.id
            },
            _ => ()
        };

1396 1397 1398
        check_while_true_expr(self, e);
        check_stability(self, e);
        check_unused_unsafe(self, e);
D
Daniel Micay 已提交
1399
        check_unsafe_block(self, e);
1400 1401
        check_unnecessary_allocation(self, e);
        check_heap_expr(self, e);
1402

1403
        check_type_limits(self, e);
F
Florian Hahn 已提交
1404
        check_unused_casts(self, e);
1405

1406
        visit::walk_expr(self, e, ());
1407 1408
    }

E
Eduard Burtescu 已提交
1409
    fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
1410
        check_path_statement(self, s);
1411

1412 1413
        visit::walk_stmt(self, s, ());
    }
1414

1415
    fn visit_fn(&mut self, fk: &visit::FnKind, decl: &ast::FnDecl,
E
Eduard Burtescu 已提交
1416
                body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
1417 1418 1419
        let recurse = |this: &mut Context| {
            visit::walk_fn(this, fk, decl, body, span, id, ());
        };
1420

1421
        match *fk {
1422
            visit::FkMethod(_, _, m) => {
1423
                self.with_lint_attrs(m.attrs, |cx| {
1424
                    check_missing_doc_method(cx, m);
K
klutzy 已提交
1425
                    check_attrs_usage(cx, m.attrs);
1426

1427
                    cx.visit_ids(|v| {
1428
                        v.visit_fn(fk, decl, body, span, id, ());
1429
                    });
1430
                    recurse(cx);
1431
                })
1432 1433 1434
            }
            _ => recurse(self),
        }
1435
    }
1436

K
klutzy 已提交
1437

1438
    fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
1439
        self.with_lint_attrs(t.attrs, |cx| {
1440
            check_missing_doc_ty_method(cx, t);
K
klutzy 已提交
1441
            check_attrs_usage(cx, t.attrs);
1442 1443

            visit::walk_ty_method(cx, t, ());
1444
        })
1445 1446 1447
    }

    fn visit_struct_def(&mut self,
1448
                        s: &ast::StructDef,
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
                        i: ast::Ident,
                        g: &ast::Generics,
                        id: ast::NodeId,
                        _: ()) {
        let old_id = self.cur_struct_def_id;
        self.cur_struct_def_id = id;
        visit::walk_struct_def(self, s, i, g, id, ());
        self.cur_struct_def_id = old_id;
    }

1459
    fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
1460
        self.with_lint_attrs(s.node.attrs, |cx| {
1461
            check_missing_doc_struct_field(cx, s);
K
klutzy 已提交
1462
            check_attrs_usage(cx, s.node.attrs);
1463 1464

            visit::walk_struct_field(cx, s, ());
1465
        })
1466 1467
    }

1468
    fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
1469
        self.with_lint_attrs(v.node.attrs, |cx| {
1470
            check_missing_doc_variant(cx, v);
K
klutzy 已提交
1471
            check_attrs_usage(cx, v.node.attrs);
1472 1473

            visit::walk_variant(cx, v, g, ());
1474
        })
1475
    }
1476 1477 1478

    // FIXME(#10894) should continue recursing
    fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {}
1479
}
1480

E
Erik Price 已提交
1481
impl<'a> IdVisitingOperation for Context<'a> {
1482
    fn visit_id(&self, id: ast::NodeId) {
1483 1484
        let mut lints = self.tcx.sess.lints.borrow_mut();
        match lints.get().pop(&id) {
1485 1486 1487 1488
            None => {}
            Some(l) => {
                for (lint, span, msg) in l.move_iter() {
                    self.span_lint(lint, span, msg)
1489
                }
1490 1491
            }
        }
1492
    }
1493 1494
}

1495
pub fn check_crate(tcx: ty::ctxt,
1496
                   method_map: typeck::method_map,
1497 1498
                   exported_items: &privacy::ExportedItems,
                   crate: &ast::Crate) {
1499
    let mut cx = Context {
1500
        dict: @get_lint_dict(),
1501
        cur: SmallIntMap::new(),
1502
        tcx: tcx,
1503
        method_map: method_map,
1504 1505 1506
        exported_items: exported_items,
        cur_struct_def_id: -1,
        is_doc_hidden: false,
1507
        lint_stack: ~[],
1508
        negated_expr_id: -1
1509 1510
    };

1511 1512
    // Install default lint levels, followed by the command line levels, and
    // then actually visit the whole crate.
D
Daniel Micay 已提交
1513
    for (_, spec) in cx.dict.iter() {
1514
        cx.set_level(spec.lint, spec.default, Default);
1515
    }
D
Daniel Micay 已提交
1516
    for &(lint, level) in tcx.sess.opts.lint_opts.iter() {
1517
        cx.set_level(lint, level, CommandLine);
1518
    }
1519
    cx.with_lint_attrs(crate.attrs, |cx| {
1520
        cx.visit_id(ast::CRATE_NODE_ID);
1521
        cx.visit_ids(|v| {
1522 1523
            v.visited_outermost = true;
            visit::walk_crate(v, crate, ());
1524
        });
K
klutzy 已提交
1525 1526

        check_crate_attrs_usage(cx, crate.attrs);
1527 1528 1529
        // since the root module isn't visited as an item (because it isn't an item), warn for it
        // here.
        check_missing_doc_attrs(cx, None, crate.attrs, crate.span, "crate");
K
klutzy 已提交
1530

1531
        visit::walk_crate(cx, crate, ());
1532
    });
1533

1534 1535
    // If we missed any lints added to the session, then there's a bug somewhere
    // in the iteration code.
1536 1537
    let lints = tcx.sess.lints.borrow();
    for (id, v) in lints.get().iter() {
1538 1539 1540 1541 1542 1543 1544
        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))
1545 1546
        }
    }
1547

1548
    tcx.sess.abort_if_errors();
1549
}