]> git.lizzy.rs Git - rust.git/blob - src/librustc/lint/context.rs
bc92d69a747c4b3dbd7d4ecd35252ada5d045d5f
[rust.git] / src / librustc / lint / context.rs
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.
4 //
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.
10
11 //! Implementation of lint checking.
12 //!
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.
19 //!
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.
26
27 use middle::privacy::ExportedItems;
28 use middle::ty;
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};
35 use lint::builtin;
36
37 use std::collections::HashMap;
38 use std::rc::Rc;
39 use std::cell::RefCell;
40 use std::tuple::Tuple2;
41 use std::mem;
42 use syntax::ast_util::IdVisitingOperation;
43 use syntax::attr::AttrMetaMethods;
44 use syntax::attr;
45 use syntax::codemap::Span;
46 use syntax::visit::{Visitor, FnKind};
47 use syntax::{ast, ast_util, visit};
48
49 /// Information about the registered lints.
50 ///
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)>,
57
58     /// Trait objects for each lint pass.
59     /// This is only `None` while iterating over the objects. See the definition
60     /// of run_lints.
61     passes: Option<Vec<LintPassObject>>,
62
63     /// Lints indexed by name.
64     by_name: HashMap<&'static str, LintId>,
65
66     /// Current levels of each lint, and where they were set.
67     levels: HashMap<LintId, LevelSource>,
68 }
69
70 impl LintStore {
71     fn get_level_source(&self, lint: LintId) -> LevelSource {
72         match self.levels.find(&lint) {
73             Some(&s) => s,
74             None => (Allow, Default),
75         }
76     }
77
78     fn set_level(&mut self, lint: LintId, lvlsrc: LevelSource) {
79         if lvlsrc.val0() == Allow {
80             self.levels.remove(&lint);
81         } else {
82             self.levels.insert(lint, lvlsrc);
83         }
84     }
85
86     pub fn new() -> LintStore {
87         LintStore {
88             lints: vec!(),
89             passes: Some(vec!()),
90             by_name: HashMap::new(),
91             levels: HashMap::new(),
92         }
93     }
94
95     pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
96         self.lints.as_slice()
97     }
98
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));
103
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()),
112
113                     // A duplicate name from a plugin is a user error.
114                     (Some(sess), true)  => sess.err(msg.as_slice()),
115                 }
116             }
117
118             if lint.default_level != Allow {
119                 self.levels.insert(id, (lint.default_level, Default));
120             }
121         }
122         self.passes.get_mut_ref().push(pass);
123     }
124
125     pub fn register_builtin(&mut self, sess: Option<&Session>) {
126         macro_rules! add_builtin ( ( $sess:ident, $($name:ident),*, ) => (
127             {$(
128                 self.register_pass($sess, false, box builtin::$name as LintPassObject);
129             )*}
130         ))
131
132         macro_rules! add_builtin_with_new ( ( $sess:ident, $($name:ident),*, ) => (
133             {$(
134                 self.register_pass($sess, false, box builtin::$name::new() as LintPassObject);
135             )*}
136         ))
137
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,
146         )
147
148         add_builtin_with_new!(sess,
149             TypeLimits, RawPointerDeriving, MissingDoc,
150         )
151
152         // We have one lint pass defined in this module.
153         self.register_pass(sess, false, box GatherNodeLevels as LintPassObject);
154     }
155
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()),
162             }
163         }
164     }
165 }
166
167 /// Context for lint checking.
168 pub struct Context<'a> {
169     /// Type context we're checking in.
170     pub tcx: &'a ty::ctxt,
171
172     /// The store of registered lints.
173     lints: LintStore,
174
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
177     /// was modified.
178     level_stack: Vec<(LintId, LevelSource)>,
179
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>>,
183 }
184
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),*);
192     }
193     $cx.lints.passes = Some(passes);
194 }))
195
196 /// Emit a lint as a warning or an error (or not at all)
197 /// according to `level`.
198 ///
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 }
207
208     let mut note = None;
209     let msg = match source {
210         Default => {
211             format!("{}, #[{}({})] on by default", msg,
212                 level.as_str(), lint.name)
213         },
214         CommandLine => {
215             format!("{} [-{} {}]", msg,
216                 match level {
217                     Warn => 'W', Deny => 'D', Forbid => 'F',
218                     Allow => fail!()
219                 }, lint.name.replace("_", "-"))
220         },
221         Node(src) => {
222             note = Some(src);
223             msg.to_string()
224         }
225     };
226
227     // For purposes of printing, we can treat forbid as deny.
228     if level == Forbid { level = Deny; }
229
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"),
236     }
237
238     for span in note.move_iter() {
239         sess.span_note(span, "lint level defined here");
240     }
241 }
242
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(),
247             LintStore::new());
248
249         Context {
250             lints: lint_store,
251             tcx: tcx,
252             level_stack: vec!(),
253             node_levels: RefCell::new(HashMap::new()),
254         }
255     }
256
257     /// Get the overall compiler `Session` object.
258     pub fn sess(&'a self) -> &'a Session {
259         &self.tcx.sess
260     }
261
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)) {
264             None => return,
265             Some(&(Warn, src)) => {
266                 let lint_id = LintId::of(builtin::warnings);
267                 (self.lints.get_level_source(lint_id).val0(), src)
268             }
269             Some(&pair) => pair,
270         };
271
272         raw_emit_lint(&self.tcx.sess, lint, (level, src), span, msg);
273     }
274
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);
278     }
279
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);
283     }
284
285     /**
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.
289      */
290     fn with_lint_attrs(&mut self,
291                        attrs: &[ast::Attribute],
292                        f: |&mut Context|) {
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
296         // specified closure
297         let lint_attrs = self.gather_lint_attrs(attrs);
298         let mut pushed = 0u;
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)));
309                 pushed += 1;
310                 self.lints.set_level(lint_id, (level, Node(span)));
311             }
312         }
313
314         run_lints!(self, enter_lint_attrs, attrs);
315         f(self);
316         run_lints!(self, exit_lint_attrs, attrs);
317
318         // rollback
319         for _ in range(0, pushed) {
320             let (lint, lvlsrc) = self.level_stack.pop().unwrap();
321             self.lints.set_level(lint, lvlsrc);
322         }
323     }
324
325     fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
326         let mut v = ast_util::IdVisitor {
327             operation: self,
328             pass_through_items: false,
329             visited_outermost: false,
330         };
331         f(&mut v);
332     }
333
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()) {
340                 None => continue,
341                 Some(lvl) => lvl,
342             };
343
344             attr::mark_used(attr);
345
346             let meta = attr.node.value;
347             let metas = match meta.node {
348                 ast::MetaList(_, ref metas) => metas,
349                 _ => {
350                     self.tcx.sess.span_err(meta.span, "malformed lint attribute");
351                     continue;
352                 }
353             };
354
355             for meta in metas.iter() {
356                 match meta.node {
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)),
360
361                             None => self.span_lint(builtin::unrecognized_lint,
362                                 meta.span,
363                                 format!("unknown `{}` attribute: `{}`",
364                                     level.as_str(), lint_name).as_slice()),
365                         }
366                     }
367                     _ => self.tcx.sess.span_err(meta.span, "malformed lint attribute"),
368                 }
369             }
370         }
371         out
372     }
373 }
374
375 impl<'a> AstConv for Context<'a>{
376     fn tcx<'a>(&'a self) -> &'a ty::ctxt { self.tcx }
377
378     fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
379         ty::lookup_item_type(self.tcx, id)
380     }
381
382     fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> {
383         ty::lookup_trait_def(self.tcx, id)
384     }
385
386     fn ty_infer(&self, _span: Span) -> ty::t {
387         infer::new_infer_ctxt(self.tcx).next_ty_var()
388     }
389 }
390
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, ());
397         })
398     }
399
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, ());
404         })
405     }
406
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, ());
412         })
413     }
414
415     fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
416         run_lints!(self, check_pat, p);
417         visit::walk_pat(self, p, ());
418     }
419
420     fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
421         run_lints!(self, check_expr, e);
422         visit::walk_expr(self, e, ());
423     }
424
425     fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
426         run_lints!(self, check_stmt, s);
427         visit::walk_stmt(self, s, ());
428     }
429
430     fn visit_fn(&mut self, fk: &FnKind, decl: &ast::FnDecl,
431                 body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
432         match *fk {
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);
436                     cx.visit_ids(|v| {
437                         v.visit_fn(fk, decl, body, span, id, ());
438                     });
439                     visit::walk_fn(cx, fk, decl, body, span, ());
440                 })
441             },
442             _ => {
443                 run_lints!(self, check_fn, fk, decl, body, span, id);
444                 visit::walk_fn(self, fk, decl, body, span, ());
445             }
446         }
447     }
448
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, ());
453         })
454     }
455
456     fn visit_struct_def(&mut self,
457                         s: &ast::StructDef,
458                         ident: ast::Ident,
459                         g: &ast::Generics,
460                         id: ast::NodeId,
461                         _: ()) {
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);
465     }
466
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, ());
471         })
472     }
473
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, ());
478         })
479     }
480
481     // FIXME(#10894) should continue recursing
482     fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
483         run_lints!(self, check_ty, t);
484     }
485
486     fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
487         run_lints!(self, check_ident, sp, id);
488     }
489
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, ());
493     }
494
495     fn visit_local(&mut self, l: &ast::Local, _: ()) {
496         run_lints!(self, check_local, l);
497         visit::walk_local(self, l, ());
498     }
499
500     fn visit_block(&mut self, b: &ast::Block, _: ()) {
501         run_lints!(self, check_block, b);
502         visit::walk_block(self, b, ());
503     }
504
505     fn visit_arm(&mut self, a: &ast::Arm, _: ()) {
506         run_lints!(self, check_arm, a);
507         visit::walk_arm(self, a, ());
508     }
509
510     fn visit_decl(&mut self, d: &ast::Decl, _: ()) {
511         run_lints!(self, check_decl, d);
512         visit::walk_decl(self, d, ());
513     }
514
515     fn visit_expr_post(&mut self, e: &ast::Expr, _: ()) {
516         run_lints!(self, check_expr_post, e);
517     }
518
519     fn visit_generics(&mut self, g: &ast::Generics, _: ()) {
520         run_lints!(self, check_generics, g);
521         visit::walk_generics(self, g, ());
522     }
523
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, ());
527     }
528
529     fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<ast::Lifetime>, _: ()) {
530         run_lints!(self, check_opt_lifetime_ref, sp, lt);
531     }
532
533     fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime, _: ()) {
534         run_lints!(self, check_lifetime_ref, lt);
535     }
536
537     fn visit_lifetime_decl(&mut self, lt: &ast::Lifetime, _: ()) {
538         run_lints!(self, check_lifetime_decl, lt);
539     }
540
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, ());
544     }
545
546     fn visit_mac(&mut self, mac: &ast::Mac, _: ()) {
547         run_lints!(self, check_mac, mac);
548         visit::walk_mac(self, mac, ());
549     }
550
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, ());
554     }
555
556     fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
557         run_lints!(self, check_attribute, attr);
558     }
559 }
560
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) {
565             None => {}
566             Some(lints) => {
567                 for (lint_id, span, msg) in lints.move_iter() {
568                     self.span_lint(lint_id.lint, span, msg.as_slice())
569                 }
570             }
571         }
572     }
573 }
574
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
578 // `raw_emit_lint`.
579
580 struct GatherNodeLevels;
581
582 impl LintPass for GatherNodeLevels {
583     fn get_lints(&self) -> LintArray {
584         lint_array!()
585     }
586
587     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
588         match it.node {
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);
595                     },
596                     _ => { }
597                 }
598             },
599             _ => { }
600         }
601     }
602 }
603
604 /// Perform lint checking on a crate.
605 ///
606 /// Consumes the `lint_store` field of the `Session`.
607 pub fn check_crate(tcx: &ty::ctxt,
608                    krate: &ast::Crate,
609                    exported_items: &ExportedItems) {
610     let mut cx = Context::new(tcx);
611
612     // Visit the whole crate.
613     cx.with_lint_attrs(krate.attrs.as_slice(), |cx| {
614         cx.visit_id(ast::CRATE_NODE_ID);
615         cx.visit_ids(|v| {
616             v.visited_outermost = true;
617             visit::walk_crate(v, krate, ());
618         });
619
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);
623
624         visit::walk_crate(cx, krate, ());
625     });
626
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)
634                 .as_slice())
635         }
636     }
637
638     tcx.sess.abort_if_errors();
639     *tcx.node_lint_levels.borrow_mut() = cx.node_levels.unwrap();
640 }