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<&'static str, 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, id) {
106 let msg = format!("duplicate specification of lint {}", lint.name);
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 }
209 let msg = match source {
211 format!("{}, #[{}({})] on by default", msg,
212 level.as_str(), lint.name)
215 format!("{} [-{} {}]", msg,
217 Warn => 'W', Deny => 'D', Forbid => 'F',
219 }, lint.name.replace("_", "-"))
227 // For purposes of printing, we can treat forbid as deny.
228 if level == Forbid { level = Deny; }
230 match (level, span) {
231 (Warn, Some(sp)) => sess.span_warn(sp, msg.as_slice()),
232 (Warn, None) => sess.warn(msg.as_slice()),
233 (Deny, Some(sp)) => sess.span_err(sp, msg.as_slice()),
234 (Deny, None) => sess.err(msg.as_slice()),
235 _ => sess.bug("impossible level in raw_emit_lint"),
238 for span in note.move_iter() {
239 sess.span_note(span, "lint level defined here");
243 impl<'a> Context<'a> {
244 fn new(tcx: &'a ty::ctxt) -> Context<'a> {
245 // We want to own the lint store, so move it out of the session.
246 let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(),
253 node_levels: RefCell::new(HashMap::new()),
257 /// Get the overall compiler `Session` object.
258 pub fn sess(&'a self) -> &'a Session {
262 fn lookup_and_emit(&self, lint: &'static Lint, span: Option<Span>, msg: &str) {
263 let (level, src) = match self.lints.levels.find(&LintId::of(lint)) {
265 Some(&(Warn, src)) => {
266 let lint_id = LintId::of(builtin::warnings);
267 (self.lints.get_level_source(lint_id).val0(), src)
272 raw_emit_lint(&self.tcx.sess, lint, (level, src), span, msg);
275 /// Emit a lint at the appropriate level, with no associated span.
276 pub fn lint(&self, lint: &'static Lint, msg: &str) {
277 self.lookup_and_emit(lint, None, msg);
280 /// Emit a lint at the appropriate level, for a particular span.
281 pub fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) {
282 self.lookup_and_emit(lint, Some(span), msg);
286 * Merge the lints specified by any lint attributes into the
287 * current lint context, call the provided function, then reset the
288 * lints in effect to their previous state.
290 fn with_lint_attrs(&mut self,
291 attrs: &[ast::Attribute],
293 // Parse all of the lint attributes, and then add them all to the
294 // current dictionary of lint information. Along the way, keep a history
295 // of what we changed so we can roll everything back after invoking the
297 let lint_attrs = self.gather_lint_attrs(attrs);
299 for (lint_id, level, span) in lint_attrs.move_iter() {
300 let now = self.lints.get_level_source(lint_id).val0();
301 if now == Forbid && level != Forbid {
302 let lint_name = lint_id.as_str();
303 self.tcx.sess.span_err(span,
304 format!("{}({}) overruled by outer forbid({})",
305 level.as_str(), lint_name, lint_name).as_slice());
306 } else if now != level {
307 let src = self.lints.get_level_source(lint_id).val1();
308 self.level_stack.push((lint_id, (now, src)));
310 self.lints.set_level(lint_id, (level, Node(span)));
314 run_lints!(self, enter_lint_attrs, attrs);
316 run_lints!(self, exit_lint_attrs, attrs);
319 for _ in range(0, pushed) {
320 let (lint, lvlsrc) = self.level_stack.pop().unwrap();
321 self.lints.set_level(lint, lvlsrc);
325 fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
326 let mut v = ast_util::IdVisitor {
328 pass_through_items: false,
329 visited_outermost: false,
334 fn gather_lint_attrs(&mut self, attrs: &[ast::Attribute]) -> Vec<(LintId, Level, Span)> {
335 // Doing this as an iterator is messy due to multiple borrowing.
336 // Allocating and copying these should be quick.
337 let mut out = vec!();
338 for attr in attrs.iter() {
339 let level = match Level::from_str(attr.name().get()) {
344 attr::mark_used(attr);
346 let meta = attr.node.value;
347 let metas = match meta.node {
348 ast::MetaList(_, ref metas) => metas,
350 self.tcx.sess.span_err(meta.span, "malformed lint attribute");
355 for meta in metas.iter() {
357 ast::MetaWord(ref lint_name) => {
358 match self.lints.by_name.find_equiv(lint_name) {
359 Some(lint_id) => out.push((*lint_id, level, meta.span)),
361 None => self.span_lint(builtin::unrecognized_lint,
363 format!("unknown `{}` attribute: `{}`",
364 level.as_str(), lint_name).as_slice()),
367 _ => self.tcx.sess.span_err(meta.span, "malformed lint attribute"),
375 impl<'a> AstConv for Context<'a>{
376 fn tcx<'a>(&'a self) -> &'a ty::ctxt { self.tcx }
378 fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
379 ty::lookup_item_type(self.tcx, id)
382 fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> {
383 ty::lookup_trait_def(self.tcx, id)
386 fn ty_infer(&self, _span: Span) -> ty::t {
387 infer::new_infer_ctxt(self.tcx).next_ty_var()
391 impl<'a> Visitor<()> for Context<'a> {
392 fn visit_item(&mut self, it: &ast::Item, _: ()) {
393 self.with_lint_attrs(it.attrs.as_slice(), |cx| {
394 run_lints!(cx, check_item, it);
395 cx.visit_ids(|v| v.visit_item(it, ()));
396 visit::walk_item(cx, it, ());
400 fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
401 self.with_lint_attrs(it.attrs.as_slice(), |cx| {
402 run_lints!(cx, check_foreign_item, it);
403 visit::walk_foreign_item(cx, it, ());
407 fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
408 self.with_lint_attrs(i.attrs.as_slice(), |cx| {
409 run_lints!(cx, check_view_item, i);
410 cx.visit_ids(|v| v.visit_view_item(i, ()));
411 visit::walk_view_item(cx, i, ());
415 fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
416 run_lints!(self, check_pat, p);
417 visit::walk_pat(self, p, ());
420 fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
421 run_lints!(self, check_expr, e);
422 visit::walk_expr(self, e, ());
425 fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
426 run_lints!(self, check_stmt, s);
427 visit::walk_stmt(self, s, ());
430 fn visit_fn(&mut self, fk: &FnKind, decl: &ast::FnDecl,
431 body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
433 visit::FkMethod(_, _, m) => {
434 self.with_lint_attrs(m.attrs.as_slice(), |cx| {
435 run_lints!(cx, check_fn, fk, decl, body, span, id);
437 v.visit_fn(fk, decl, body, span, id, ());
439 visit::walk_fn(cx, fk, decl, body, span, ());
443 run_lints!(self, check_fn, fk, decl, body, span, id);
444 visit::walk_fn(self, fk, decl, body, span, ());
449 fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
450 self.with_lint_attrs(t.attrs.as_slice(), |cx| {
451 run_lints!(cx, check_ty_method, t);
452 visit::walk_ty_method(cx, t, ());
456 fn visit_struct_def(&mut self,
462 run_lints!(self, check_struct_def, s, ident, g, id);
463 visit::walk_struct_def(self, s, ());
464 run_lints!(self, check_struct_def_post, s, ident, g, id);
467 fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
468 self.with_lint_attrs(s.node.attrs.as_slice(), |cx| {
469 run_lints!(cx, check_struct_field, s);
470 visit::walk_struct_field(cx, s, ());
474 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
475 self.with_lint_attrs(v.node.attrs.as_slice(), |cx| {
476 run_lints!(cx, check_variant, v, g);
477 visit::walk_variant(cx, v, g, ());
481 // FIXME(#10894) should continue recursing
482 fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
483 run_lints!(self, check_ty, t);
486 fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
487 run_lints!(self, check_ident, sp, id);
490 fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId, _: ()) {
491 run_lints!(self, check_mod, m, s, n);
492 visit::walk_mod(self, m, ());
495 fn visit_local(&mut self, l: &ast::Local, _: ()) {
496 run_lints!(self, check_local, l);
497 visit::walk_local(self, l, ());
500 fn visit_block(&mut self, b: &ast::Block, _: ()) {
501 run_lints!(self, check_block, b);
502 visit::walk_block(self, b, ());
505 fn visit_arm(&mut self, a: &ast::Arm, _: ()) {
506 run_lints!(self, check_arm, a);
507 visit::walk_arm(self, a, ());
510 fn visit_decl(&mut self, d: &ast::Decl, _: ()) {
511 run_lints!(self, check_decl, d);
512 visit::walk_decl(self, d, ());
515 fn visit_expr_post(&mut self, e: &ast::Expr, _: ()) {
516 run_lints!(self, check_expr_post, e);
519 fn visit_generics(&mut self, g: &ast::Generics, _: ()) {
520 run_lints!(self, check_generics, g);
521 visit::walk_generics(self, g, ());
524 fn visit_trait_method(&mut self, m: &ast::TraitMethod, _: ()) {
525 run_lints!(self, check_trait_method, m);
526 visit::walk_trait_method(self, m, ());
529 fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<ast::Lifetime>, _: ()) {
530 run_lints!(self, check_opt_lifetime_ref, sp, lt);
533 fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime, _: ()) {
534 run_lints!(self, check_lifetime_ref, lt);
537 fn visit_lifetime_decl(&mut self, lt: &ast::Lifetime, _: ()) {
538 run_lints!(self, check_lifetime_decl, lt);
541 fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf, _: ()) {
542 run_lints!(self, check_explicit_self, es);
543 visit::walk_explicit_self(self, es, ());
546 fn visit_mac(&mut self, mac: &ast::Mac, _: ()) {
547 run_lints!(self, check_mac, mac);
548 visit::walk_mac(self, mac, ());
551 fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId, _: ()) {
552 run_lints!(self, check_path, p, id);
553 visit::walk_path(self, p, ());
556 fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
557 run_lints!(self, check_attribute, attr);
561 // Output any lints that were previously added to the session.
562 impl<'a> IdVisitingOperation for Context<'a> {
563 fn visit_id(&self, id: ast::NodeId) {
564 match self.tcx.sess.lints.borrow_mut().pop(&id) {
567 for (lint_id, span, msg) in lints.move_iter() {
568 self.span_lint(lint_id.lint, span, msg.as_slice())
575 // This lint pass is defined here because it touches parts of the `Context`
576 // that we don't want to expose. It records the lint level at certain AST
577 // nodes, so that the variant size difference check in trans can call
580 struct GatherNodeLevels;
582 impl LintPass for GatherNodeLevels {
583 fn get_lints(&self) -> LintArray {
587 fn check_item(&mut self, cx: &Context, it: &ast::Item) {
589 ast::ItemEnum(..) => {
590 let lint_id = LintId::of(builtin::variant_size_difference);
591 match cx.lints.get_level_source(lint_id) {
592 lvlsrc @ (lvl, _) if lvl != Allow => {
593 cx.node_levels.borrow_mut()
594 .insert((it.id, lint_id), lvlsrc);
604 /// Perform lint checking on a crate.
606 /// Consumes the `lint_store` field of the `Session`.
607 pub fn check_crate(tcx: &ty::ctxt,
609 exported_items: &ExportedItems) {
610 let mut cx = Context::new(tcx);
612 // Visit the whole crate.
613 cx.with_lint_attrs(krate.attrs.as_slice(), |cx| {
614 cx.visit_id(ast::CRATE_NODE_ID);
616 v.visited_outermost = true;
617 visit::walk_crate(v, krate, ());
620 // since the root module isn't visited as an item (because it isn't an
621 // item), warn for it here.
622 run_lints!(cx, check_crate, exported_items, krate);
624 visit::walk_crate(cx, krate, ());
627 // If we missed any lints added to the session, then there's a bug somewhere
628 // in the iteration code.
629 for (id, v) in tcx.sess.lints.borrow().iter() {
630 for &(lint, span, ref msg) in v.iter() {
631 tcx.sess.span_bug(span,
632 format!("unprocessed lint {} at {}: {}",
633 lint.as_str(), tcx.map.node_to_str(*id), *msg)
638 tcx.sess.abort_if_errors();
639 *tcx.node_lint_levels.borrow_mut() = cx.node_levels.unwrap();