1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Implementation of lint checking.
13 //! The lint checking is mostly consolidated into one pass which runs just
14 //! before translation to LLVM bytecode. Throughout compilation, lint warnings
15 //! can be added via the `add_lint` method on the Session structure. This
16 //! requires a span and an id of the node that the lint is being added to. The
17 //! lint isn't actually emitted at that time because it is unknown what the
18 //! actual lint level at that location is.
20 //! To actually emit lint warnings/errors, a separate pass is used just before
21 //! translation. A context keeps track of the current state of all lint levels.
22 //! Upon entering a node of the ast which can modify the lint settings, the
23 //! previous lint state is pushed onto a stack and the ast is then recursed
24 //! upon. As the ast is traversed, this keeps track of the current lint level
25 //! for all lint attributes.
27 use middle::privacy::ExportedItems;
29 use middle::typeck::astconv::AstConv;
30 use middle::typeck::infer;
31 use driver::session::Session;
32 use driver::early_error;
33 use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass, LintPassObject};
34 use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid};
37 use std::collections::HashMap;
39 use std::cell::RefCell;
40 use std::tuple::Tuple2;
42 use syntax::ast_util::IdVisitingOperation;
43 use syntax::attr::AttrMetaMethods;
45 use syntax::codemap::Span;
46 use syntax::visit::{Visitor, FnKind};
47 use syntax::{ast, ast_util, visit};
49 /// Information about the registered lints.
51 /// This is basically the subset of `Context` that we can
52 /// build early in the compile pipeline.
53 pub struct LintStore {
54 /// Registered lints. The bool is true if the lint was
55 /// added by a plugin.
56 lints: Vec<(&'static Lint, bool)>,
58 /// Trait objects for each lint pass.
59 /// This is only `None` while iterating over the objects. See the definition
61 passes: Option<Vec<LintPassObject>>,
63 /// Lints indexed by name.
64 by_name: HashMap<String, LintId>,
66 /// Current levels of each lint, and where they were set.
67 levels: HashMap<LintId, LevelSource>,
71 fn get_level_source(&self, lint: LintId) -> LevelSource {
72 match self.levels.find(&lint) {
74 None => (Allow, Default),
78 fn set_level(&mut self, lint: LintId, lvlsrc: LevelSource) {
79 if lvlsrc.val0() == Allow {
80 self.levels.remove(&lint);
82 self.levels.insert(lint, lvlsrc);
86 pub fn new() -> LintStore {
90 by_name: HashMap::new(),
91 levels: HashMap::new(),
95 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
99 pub fn register_pass(&mut self, sess: Option<&Session>,
100 from_plugin: bool, pass: LintPassObject) {
101 for &lint in pass.get_lints().iter() {
102 self.lints.push((lint, from_plugin));
104 let id = LintId::of(lint);
105 if !self.by_name.insert(lint.name_lower(), id) {
106 let msg = format!("duplicate specification of lint {}", lint.name_lower());
107 match (sess, from_plugin) {
108 // We load builtin lints first, so a duplicate is a compiler bug.
109 // Use early_error when handling -W help with no crate.
110 (None, _) => early_error(msg.as_slice()),
111 (Some(sess), false) => sess.bug(msg.as_slice()),
113 // A duplicate name from a plugin is a user error.
114 (Some(sess), true) => sess.err(msg.as_slice()),
118 if lint.default_level != Allow {
119 self.levels.insert(id, (lint.default_level, Default));
122 self.passes.get_mut_ref().push(pass);
125 pub fn register_builtin(&mut self, sess: Option<&Session>) {
126 macro_rules! add_builtin ( ( $sess:ident, $($name:ident),*, ) => (
128 self.register_pass($sess, false, box builtin::$name as LintPassObject);
132 macro_rules! add_builtin_with_new ( ( $sess:ident, $($name:ident),*, ) => (
134 self.register_pass($sess, false, box builtin::$name::new() as LintPassObject);
138 add_builtin!(sess, HardwiredLints,
139 WhileTrue, UnusedCasts, CTypes, HeapMemory,
140 UnusedAttribute, PathStatement, UnusedResult,
141 DeprecatedOwnedVector, NonCamelCaseTypes,
142 NonSnakeCaseFunctions, NonUppercaseStatics,
143 NonUppercasePatternStatics, UppercaseVariables,
144 UnnecessaryParens, UnusedUnsafe, UnsafeBlock,
145 UnusedMut, UnnecessaryAllocation, Stability,
148 add_builtin_with_new!(sess,
149 TypeLimits, RawPointerDeriving, MissingDoc,
152 // We have one lint pass defined in this module.
153 self.register_pass(sess, false, box GatherNodeLevels as LintPassObject);
156 pub fn process_command_line(&mut self, sess: &Session) {
157 for &(ref lint_name, level) in sess.opts.lint_opts.iter() {
158 match self.by_name.find_equiv(&lint_name.as_slice()) {
159 Some(&lint_id) => self.set_level(lint_id, (level, CommandLine)),
160 None => sess.err(format!("unknown {} flag: {}",
161 level.as_str(), lint_name).as_slice()),
167 /// Context for lint checking.
168 pub struct Context<'a> {
169 /// Type context we're checking in.
170 pub tcx: &'a ty::ctxt,
172 /// The store of registered lints.
175 /// When recursing into an attributed node of the ast which modifies lint
176 /// levels, this stack keeps track of the previous lint levels of whatever
178 level_stack: Vec<(LintId, LevelSource)>,
180 /// Level of lints for certain NodeIds, stored here because the body of
181 /// the lint needs to run in trans.
182 node_levels: RefCell<HashMap<(ast::NodeId, LintId), LevelSource>>,
185 /// Convenience macro for calling a `LintPass` method on every pass in the context.
186 macro_rules! run_lints ( ($cx:expr, $f:ident, $($args:expr),*) => ({
187 // Move the vector of passes out of `$cx` so that we can
188 // iterate over it mutably while passing `$cx` to the methods.
189 let mut passes = $cx.lints.passes.take_unwrap();
190 for obj in passes.mut_iter() {
191 obj.$f($cx, $($args),*);
193 $cx.lints.passes = Some(passes);
196 /// Emit a lint as a warning or an error (or not at all)
197 /// according to `level`.
199 /// This lives outside of `Context` so it can be used by checks
200 /// in trans that run after the main lint pass is finished. Most
201 /// lints elsewhere in the compiler should call
202 /// `Session::add_lint()` instead.
203 pub fn raw_emit_lint(sess: &Session, lint: &'static Lint,
204 lvlsrc: LevelSource, span: Option<Span>, msg: &str) {
205 let (mut level, source) = lvlsrc;
206 if level == Allow { return }
208 let name = lint.name_lower();
210 let msg = match source {
212 format!("{}, #[{}({})] on by default", msg,
213 level.as_str(), name)
216 format!("{} [-{} {}]", msg,
218 Warn => 'W', Deny => 'D', Forbid => 'F',
220 }, name.replace("_", "-"))
228 // For purposes of printing, we can treat forbid as deny.
229 if level == Forbid { level = Deny; }
231 match (level, span) {
232 (Warn, Some(sp)) => sess.span_warn(sp, msg.as_slice()),
233 (Warn, None) => sess.warn(msg.as_slice()),
234 (Deny, Some(sp)) => sess.span_err(sp, msg.as_slice()),
235 (Deny, None) => sess.err(msg.as_slice()),
236 _ => sess.bug("impossible level in raw_emit_lint"),
239 for span in note.move_iter() {
240 sess.span_note(span, "lint level defined here");
244 impl<'a> Context<'a> {
245 fn new(tcx: &'a ty::ctxt) -> Context<'a> {
246 // We want to own the lint store, so move it out of the session.
247 let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(),
254 node_levels: RefCell::new(HashMap::new()),
258 /// Get the overall compiler `Session` object.
259 pub fn sess(&'a self) -> &'a Session {
263 fn lookup_and_emit(&self, lint: &'static Lint, span: Option<Span>, msg: &str) {
264 let (level, src) = match self.lints.levels.find(&LintId::of(lint)) {
266 Some(&(Warn, src)) => {
267 let lint_id = LintId::of(builtin::warnings);
268 (self.lints.get_level_source(lint_id).val0(), src)
273 raw_emit_lint(&self.tcx.sess, lint, (level, src), span, msg);
276 /// Emit a lint at the appropriate level, with no associated span.
277 pub fn lint(&self, lint: &'static Lint, msg: &str) {
278 self.lookup_and_emit(lint, None, msg);
281 /// Emit a lint at the appropriate level, for a particular span.
282 pub fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) {
283 self.lookup_and_emit(lint, Some(span), msg);
287 * Merge the lints specified by any lint attributes into the
288 * current lint context, call the provided function, then reset the
289 * lints in effect to their previous state.
291 fn with_lint_attrs(&mut self,
292 attrs: &[ast::Attribute],
294 // Parse all of the lint attributes, and then add them all to the
295 // current dictionary of lint information. Along the way, keep a history
296 // of what we changed so we can roll everything back after invoking the
298 let lint_attrs = self.gather_lint_attrs(attrs);
300 for (lint_id, level, span) in lint_attrs.move_iter() {
301 let now = self.lints.get_level_source(lint_id).val0();
302 if now == Forbid && level != Forbid {
303 let lint_name = lint_id.as_str();
304 self.tcx.sess.span_err(span,
305 format!("{}({}) overruled by outer forbid({})",
306 level.as_str(), lint_name, lint_name).as_slice());
307 } else if now != level {
308 let src = self.lints.get_level_source(lint_id).val1();
309 self.level_stack.push((lint_id, (now, src)));
311 self.lints.set_level(lint_id, (level, Node(span)));
315 run_lints!(self, enter_lint_attrs, attrs);
317 run_lints!(self, exit_lint_attrs, attrs);
320 for _ in range(0, pushed) {
321 let (lint, lvlsrc) = self.level_stack.pop().unwrap();
322 self.lints.set_level(lint, lvlsrc);
326 fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
327 let mut v = ast_util::IdVisitor {
329 pass_through_items: false,
330 visited_outermost: false,
335 fn gather_lint_attrs(&mut self, attrs: &[ast::Attribute]) -> Vec<(LintId, Level, Span)> {
336 // Doing this as an iterator is messy due to multiple borrowing.
337 // Allocating and copying these should be quick.
338 let mut out = vec!();
339 for attr in attrs.iter() {
340 let level = match Level::from_str(attr.name().get()) {
345 attr::mark_used(attr);
347 let meta = attr.node.value;
348 let metas = match meta.node {
349 ast::MetaList(_, ref metas) => metas,
351 self.tcx.sess.span_err(meta.span, "malformed lint attribute");
356 for meta in metas.iter() {
358 ast::MetaWord(ref lint_name) => {
359 match self.lints.by_name.find_equiv(&lint_name.get()) {
360 Some(lint_id) => out.push((*lint_id, level, meta.span)),
362 None => self.span_lint(builtin::unrecognized_lint,
364 format!("unknown `{}` attribute: `{}`",
365 level.as_str(), lint_name).as_slice()),
368 _ => self.tcx.sess.span_err(meta.span, "malformed lint attribute"),
376 impl<'a> AstConv for Context<'a>{
377 fn tcx<'a>(&'a self) -> &'a ty::ctxt { self.tcx }
379 fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
380 ty::lookup_item_type(self.tcx, id)
383 fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> {
384 ty::lookup_trait_def(self.tcx, id)
387 fn ty_infer(&self, _span: Span) -> ty::t {
388 infer::new_infer_ctxt(self.tcx).next_ty_var()
392 impl<'a> Visitor<()> for Context<'a> {
393 fn visit_item(&mut self, it: &ast::Item, _: ()) {
394 self.with_lint_attrs(it.attrs.as_slice(), |cx| {
395 run_lints!(cx, check_item, it);
396 cx.visit_ids(|v| v.visit_item(it, ()));
397 visit::walk_item(cx, it, ());
401 fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
402 self.with_lint_attrs(it.attrs.as_slice(), |cx| {
403 run_lints!(cx, check_foreign_item, it);
404 visit::walk_foreign_item(cx, it, ());
408 fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
409 self.with_lint_attrs(i.attrs.as_slice(), |cx| {
410 run_lints!(cx, check_view_item, i);
411 cx.visit_ids(|v| v.visit_view_item(i, ()));
412 visit::walk_view_item(cx, i, ());
416 fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
417 run_lints!(self, check_pat, p);
418 visit::walk_pat(self, p, ());
421 fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
422 run_lints!(self, check_expr, e);
423 visit::walk_expr(self, e, ());
426 fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
427 run_lints!(self, check_stmt, s);
428 visit::walk_stmt(self, s, ());
431 fn visit_fn(&mut self, fk: &FnKind, decl: &ast::FnDecl,
432 body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
434 visit::FkMethod(_, _, m) => {
435 self.with_lint_attrs(m.attrs.as_slice(), |cx| {
436 run_lints!(cx, check_fn, fk, decl, body, span, id);
438 v.visit_fn(fk, decl, body, span, id, ());
440 visit::walk_fn(cx, fk, decl, body, span, ());
444 run_lints!(self, check_fn, fk, decl, body, span, id);
445 visit::walk_fn(self, fk, decl, body, span, ());
450 fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
451 self.with_lint_attrs(t.attrs.as_slice(), |cx| {
452 run_lints!(cx, check_ty_method, t);
453 visit::walk_ty_method(cx, t, ());
457 fn visit_struct_def(&mut self,
463 run_lints!(self, check_struct_def, s, ident, g, id);
464 visit::walk_struct_def(self, s, ());
465 run_lints!(self, check_struct_def_post, s, ident, g, id);
468 fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
469 self.with_lint_attrs(s.node.attrs.as_slice(), |cx| {
470 run_lints!(cx, check_struct_field, s);
471 visit::walk_struct_field(cx, s, ());
475 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
476 self.with_lint_attrs(v.node.attrs.as_slice(), |cx| {
477 run_lints!(cx, check_variant, v, g);
478 visit::walk_variant(cx, v, g, ());
482 // FIXME(#10894) should continue recursing
483 fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
484 run_lints!(self, check_ty, t);
487 fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
488 run_lints!(self, check_ident, sp, id);
491 fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId, _: ()) {
492 run_lints!(self, check_mod, m, s, n);
493 visit::walk_mod(self, m, ());
496 fn visit_local(&mut self, l: &ast::Local, _: ()) {
497 run_lints!(self, check_local, l);
498 visit::walk_local(self, l, ());
501 fn visit_block(&mut self, b: &ast::Block, _: ()) {
502 run_lints!(self, check_block, b);
503 visit::walk_block(self, b, ());
506 fn visit_arm(&mut self, a: &ast::Arm, _: ()) {
507 run_lints!(self, check_arm, a);
508 visit::walk_arm(self, a, ());
511 fn visit_decl(&mut self, d: &ast::Decl, _: ()) {
512 run_lints!(self, check_decl, d);
513 visit::walk_decl(self, d, ());
516 fn visit_expr_post(&mut self, e: &ast::Expr, _: ()) {
517 run_lints!(self, check_expr_post, e);
520 fn visit_generics(&mut self, g: &ast::Generics, _: ()) {
521 run_lints!(self, check_generics, g);
522 visit::walk_generics(self, g, ());
525 fn visit_trait_method(&mut self, m: &ast::TraitMethod, _: ()) {
526 run_lints!(self, check_trait_method, m);
527 visit::walk_trait_method(self, m, ());
530 fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<ast::Lifetime>, _: ()) {
531 run_lints!(self, check_opt_lifetime_ref, sp, lt);
534 fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime, _: ()) {
535 run_lints!(self, check_lifetime_ref, lt);
538 fn visit_lifetime_decl(&mut self, lt: &ast::Lifetime, _: ()) {
539 run_lints!(self, check_lifetime_decl, lt);
542 fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf, _: ()) {
543 run_lints!(self, check_explicit_self, es);
544 visit::walk_explicit_self(self, es, ());
547 fn visit_mac(&mut self, mac: &ast::Mac, _: ()) {
548 run_lints!(self, check_mac, mac);
549 visit::walk_mac(self, mac, ());
552 fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId, _: ()) {
553 run_lints!(self, check_path, p, id);
554 visit::walk_path(self, p, ());
557 fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
558 run_lints!(self, check_attribute, attr);
562 // Output any lints that were previously added to the session.
563 impl<'a> IdVisitingOperation for Context<'a> {
564 fn visit_id(&self, id: ast::NodeId) {
565 match self.tcx.sess.lints.borrow_mut().pop(&id) {
568 for (lint_id, span, msg) in lints.move_iter() {
569 self.span_lint(lint_id.lint, span, msg.as_slice())
576 // This lint pass is defined here because it touches parts of the `Context`
577 // that we don't want to expose. It records the lint level at certain AST
578 // nodes, so that the variant size difference check in trans can call
581 struct GatherNodeLevels;
583 impl LintPass for GatherNodeLevels {
584 fn get_lints(&self) -> LintArray {
588 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
590 ast::ItemEnum(..) => {
591 let lint_id = LintId::of(builtin::variant_size_difference);
592 match cx.lints.get_level_source(lint_id) {
593 lvlsrc @ (lvl, _) if lvl != Allow => {
594 cx.node_levels.borrow_mut()
595 .insert((it.id, lint_id), lvlsrc);
605 /// Perform lint checking on a crate.
607 /// Consumes the `lint_store` field of the `Session`.
608 pub fn check_crate(tcx: &ty::ctxt,
610 exported_items: &ExportedItems) {
611 let mut cx = Context::new(tcx);
613 // Visit the whole crate.
614 cx.with_lint_attrs(krate.attrs.as_slice(), |cx| {
615 cx.visit_id(ast::CRATE_NODE_ID);
617 v.visited_outermost = true;
618 visit::walk_crate(v, krate, ());
621 // since the root module isn't visited as an item (because it isn't an
622 // item), warn for it here.
623 run_lints!(cx, check_crate, exported_items, krate);
625 visit::walk_crate(cx, krate, ());
628 // If we missed any lints added to the session, then there's a bug somewhere
629 // in the iteration code.
630 for (id, v) in tcx.sess.lints.borrow().iter() {
631 for &(lint, span, ref msg) in v.iter() {
632 tcx.sess.span_bug(span,
633 format!("unprocessed lint {} at {}: {}",
634 lint.as_str(), tcx.map.node_to_str(*id), *msg)
639 tcx.sess.abort_if_errors();
640 *tcx.node_lint_levels.borrow_mut() = cx.node_levels.unwrap();